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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Saving: write the source tokenizer_class instead of TokenizersBackend (#16104)
Leo Borcherding073f6e0cc7e0
diff --git a/tests/saving/test_restore_bytelevel_tokenizer_class.py b/tests/saving/test_restore_bytelevel_tokenizer_class.pynew file mode 100644index 00000000000..e0f49fdc536--- /dev/null+++ b/tests/saving/test_restore_bytelevel_tokenizer_class.py@@ -0,0 +1,137 @@+# SPDX-License-Identifier: AGPL-3.0-or-later++import ast+import json+import os+import types+from pathlib import Path++import pytest+import transformers+from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers+from transformers import AutoTokenizer, PreTrainedTokenizerFast+++def _restore():+ source = Path(__file__).parents[2] / "unsloth" / "save.py"+ tree = ast.parse(source.read_text(encoding = "utf-8"))+ node = next(+ node+ for node in tree.body+ if isinstance(node, ast.FunctionDef) and node.name == "_restore_source_tokenizer_class"+ )+ namespace = {+ "json": json,+ "os": os,+ "logger": types.SimpleNamespace(warning_once = lambda *args: None),+ "_source_tokenizer_class": lambda *args, **kwargs: None,+ }+ exec(compile(ast.Module(body = [node], type_ignores = []), str(source), "exec"), namespace)+ return namespace[node.name]+++def _backend(sequence = False):+ backend = Tokenizer(models.BPE(unk_token = "<unk>"))+ bytelevel = pre_tokenizers.ByteLevel(add_prefix_space = False)+ backend.pre_tokenizer = (+ pre_tokenizers.Sequence([pre_tokenizers.WhitespaceSplit(), bytelevel])+ if sequence+ else bytelevel+ )+ backend.decoder = decoders.ByteLevel()+ backend.train_from_iterator(+ ["Hello world, this is a test."] * 4,+ trainers.BpeTrainer(+ vocab_size = 300,+ special_tokens = ["<unk>"],+ initial_alphabet = pre_tokenizers.ByteLevel.alphabet(),+ ),+ )+ return backend++[email protected]("source_class", ["LlamaTokenizer", "LlamaTokenizerFast"])[email protected]("sequence", [False, True])+def test_bytelevel_llama_uses_portable_class_and_preserves_ids(tmp_path, source_class, sequence):+ tokenizer = PreTrainedTokenizerFast(tokenizer_object = _backend(sequence), unk_token = "<unk>")+ probe = "Hello world, this is a test."+ expected = tokenizer.encode(probe, add_special_tokens = False)+ tokenizer.save_pretrained(tmp_path)+ config_path = tmp_path / "tokenizer_config.json"+ config = json.loads(config_path.read_text(encoding = "utf-8"))+ config["tokenizer_class"] = "TokenizersBackend"+ config_path.write_text(json.dumps(config), encoding = "utf-8")++ _restore()(tokenizer, tmp_path, source_class = source_class)++ config = json.loads(config_path.read_text(encoding = "utf-8"))+ assert config["tokenizer_class"] == "PreTrainedTokenizerFast"+ reloaded = AutoTokenizer.from_pretrained(tmp_path)+ assert reloaded.encode(probe, add_special_tokens = False) == expected+ assert reloaded.decode(expected) == tokenizer.decode(expected)+++ "source_class,bytelevel", [("LlamaTokenizer", False), ("Qwen2Tokenizer", True)]+)+def test_valid_source_classes_remain_specific(tmp_path, source_class, bytelevel):+ backend = _backend()+ if not bytelevel:+ backend.pre_tokenizer = pre_tokenizers.Metaspace()+ tokenizer = PreTrainedTokenizerFast(tokenizer_object = backend, unk_token = "<unk>")+ config_path = tmp_path / "tokenizer_config.json"+ config_path.write_text(json.dumps({"tokenizer_class": "TokenizersBackend"}), encoding = "utf-8")++ _restore()(tokenizer, tmp_path, source_class = source_class)++ assert json.loads(config_path.read_text(encoding = "utf-8"))["tokenizer_class"] == source_class+++def test_unknown_source_uses_portable_class_and_preserves_ids(tmp_path):+ tokenizer = PreTrainedTokenizerFast(tokenizer_object = _backend(), unk_token = "<unk>")+ probe = "Hello world, this is a test."+ expected = tokenizer.encode(probe, add_special_tokens = False)+ tokenizer.save_pretrained(tmp_path)+ config_path = tmp_path / "tokenizer_config.json"+ config = json.loads(config_path.read_text(encoding = "utf-8"))+ config["tokenizer_class"] = "TokenizersBackend"+ config_path.write_text(json.dumps(config), encoding = "utf-8")++ _restore()(tokenizer, tmp_path)++ assert (+ json.loads(config_path.read_text(encoding = "utf-8"))["tokenizer_class"]+ == "PreTrainedTokenizerFast"+ )+ reloaded = AutoTokenizer.from_pretrained(tmp_path)+ assert reloaded.encode(probe, add_special_tokens = False) == expected+ assert reloaded.decode(expected) == probe+++ transformers.__version__.split(".")[0] != "5", reason = "V5 generic backend reload"+)+def test_v5_source_llama_bytelevel_round_trip_preserves_spaces(tmp_path):+ source = tmp_path / "source"+ source.mkdir()+ _backend().save(str(source / "tokenizer.json"))+ (source / "tokenizer_config.json").write_text(+ json.dumps(+ {"tokenizer_class": "LlamaTokenizerFast", "unk_token": "<unk>", "add_bos_token": False}+ ),+ encoding = "utf-8",+ )+ (source / "config.json").write_text(json.dumps({"model_type": "deepseek_v3"}), encoding = "utf-8")+ tokenizer = AutoTokenizer.from_pretrained(source)+ assert type(tokenizer).__name__ == "TokenizersBackend"+ assert not getattr(tokenizer, "_unsloth_tokenizer_json_repaired", False)+ probe = "Hello world, this is a test."+ expected = tokenizer.encode(probe, add_special_tokens = False)+ output = tmp_path / "output"+ tokenizer.save_pretrained(output)++ _restore()(tokenizer, output, source_class = "LlamaTokenizerFast")++ reloaded = AutoTokenizer.from_pretrained(output)+ assert reloaded.encode(probe, add_special_tokens = False) == expected+ assert reloaded.decode(expected) == probediff --git a/tests/saving/test_restore_source_tokenizer_class.py b/tests/saving/test_restore_source_tokenizer_class.pynew file mode 100644index 00000000000..a351a62279c--- /dev/null+++ b/tests/saving/test_restore_source_tokenizer_class.py@@ -0,0 +1,340 @@+# SPDX-License-Identifier: AGPL-3.0-or-later++import ast+import json+import os+import types+from contextlib import contextmanager+from pathlib import Path++import pytest+from tokenizers import Tokenizer, models+from transformers import PreTrainedTokenizerFast, Qwen2TokenizerFast+++class _Logger:+ def warning_once(self, *args, **kwargs):+ pass+++def _load_restore_helper(hub_path = None):+ source = Path(__file__).parents[2] / "unsloth" / "save.py"+ tree = ast.parse(source.read_text(encoding = "utf-8"))+ wanted = {+ "_capture_source_tokenizer_class",+ "_source_tokenizer_class",+ "_restore_source_tokenizer_class",+ "_unsloth_tokenizer_save_pretrained",+ "_without_runtime_truncation",+ }+ nodes = [+ node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in wanted+ ]+ module = ast.Module(body = nodes, type_ignores = [])+ ast.fix_missing_locations(module)+ namespace = {+ "json": json,+ "os": os,+ "logger": _Logger(),+ "contextmanager": contextmanager,+ "_resolve_hub_repo_cached_file": lambda *args, **kwargs: hub_path,+ "_tokenizer_cache_dir": lambda tokenizer: None,+ "_tokenizer_revision": lambda tokenizer: None,+ "_preserve_sentencepiece_tokenizer_assets": lambda *args, **kwargs: None,+ "_preserve_tokenizer_eos_token": lambda *args, **kwargs: None,+ "_preserve_repaired_tokenizer_class": lambda *args, **kwargs: None,+ }+ exec(compile(module, str(source), "exec"), namespace)+ restore = namespace["_restore_source_tokenizer_class"]+ restore.save = namespace["_unsloth_tokenizer_save_pretrained"]+ restore.capture = namespace["_capture_source_tokenizer_class"]+ return restore+++def _write(path, config):+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_text(json.dumps(config), encoding = "utf-8")+++def _read(path):+ return json.loads(path.read_text(encoding = "utf-8"))+++def _real_source(path, source_class = "Qwen2Tokenizer"):+ tokenizer = Qwen2TokenizerFast(+ tokenizer_object = Tokenizer(models.BPE({"[UNK]": 0, "a": 1}, [], unk_token = "[UNK]")),+ unk_token = "[UNK]",+ )+ tokenizer.save_pretrained(path)+ tokenizer._tokenizer.model.save(str(path))+ config = _read(path / "tokenizer_config.json")+ config["tokenizer_class"] = source_class+ _write(path / "tokenizer_config.json", config)+ loaded = Qwen2TokenizerFast.from_pretrained(path, local_files_only = True)+ _load_restore_helper().capture(loaded, source = str(path))+ return loaded+++def test_restores_class_from_local_source(tmp_path):+ restore = _load_restore_helper()+ _write(tmp_path / "base" / "tokenizer_config.json", {"tokenizer_class": "Qwen2Tokenizer"})+ _write(+ tmp_path / "out" / "tokenizer_config.json",+ {"tokenizer_class": "TokenizersBackend", "other": 1},+ )+ tokenizer = _real_source(tmp_path / "base")++ restore(tokenizer, tmp_path / "out")++ saved = _read(tmp_path / "out" / "tokenizer_config.json")+ assert saved["tokenizer_class"] == "Qwen2Tokenizer"+ assert saved["other"] == 1+++def test_restores_class_from_cached_hub_source_through_processor(tmp_path):+ hub_config = tmp_path / "hub" / "tokenizer_config.json"+ _write(hub_config, {"tokenizer_class": "Qwen2Tokenizer"})+ restore = _load_restore_helper(hub_path = str(hub_config))+ _write(tmp_path / "out" / "tokenizer_config.json", {"tokenizer_class": "TokenizersBackend"})+ processor = types.SimpleNamespace(tokenizer = _real_source(hub_config.parent))++ restore(processor, tmp_path / "out")++ assert _read(tmp_path / "out" / "tokenizer_config.json")["tokenizer_class"] == "Qwen2Tokenizer"+++def test_leaves_specific_classes_alone(tmp_path):+ restore = _load_restore_helper()+ _write(tmp_path / "base" / "tokenizer_config.json", {"tokenizer_class": "Qwen2Tokenizer"})+ _write(tmp_path / "out" / "tokenizer_config.json", {"tokenizer_class": "Qwen3_5Tokenizer"})+ tokenizer = _real_source(tmp_path / "base")++ restore(tokenizer, tmp_path / "out")++ assert (+ _read(tmp_path / "out" / "tokenizer_config.json")["tokenizer_class"] == "Qwen3_5Tokenizer"+ )+++def test_generic_source_uses_portable_backend_alias(tmp_path):+ restore = _load_restore_helper()+ _write(tmp_path / "base" / "tokenizer_config.json", {"tokenizer_class": "TokenizersBackend"})+ _write(tmp_path / "out" / "tokenizer_config.json", {"tokenizer_class": "TokenizersBackend"})+ tokenizer = _real_source(tmp_path / "base", source_class = "TokenizersBackend")++ restore(tokenizer, tmp_path / "out")++ assert (+ _read(tmp_path / "out" / "tokenizer_config.json")["tokenizer_class"]+ == "PreTrainedTokenizerFast"+ )+++def test_unknown_source_uses_portable_backend_alias(tmp_path):+ restore = _load_restore_helper(hub_path = None)+ _write(tmp_path / "out" / "tokenizer_config.json", {"tokenizer_class": "TokenizersBackend"})+ tokenizer = types.SimpleNamespace(name_or_path = "someone/not-cached")++ restore(tokenizer, tmp_path / "out")++ assert (+ _read(tmp_path / "out" / "tokenizer_config.json")["tokenizer_class"]+ == "PreTrainedTokenizerFast"+ )+++def test_filename_prefix(tmp_path):+ restore = _load_restore_helper()+ _write(tmp_path / "base" / "tokenizer_config.json", {"tokenizer_class": "Qwen2Tokenizer"})+ _write(+ tmp_path / "out" / "adapter-tokenizer_config.json", {"tokenizer_class": "TokenizersBackend"}+ )+ tokenizer = _real_source(tmp_path / "base")++ restore(tokenizer, tmp_path / "out", filename_prefix = "adapter")++ assert (+ _read(tmp_path / "out" / "adapter-tokenizer_config.json")["tokenizer_class"]+ == "Qwen2Tokenizer"+ )+++def test_in_place_save_keeps_the_source_class(tmp_path):+ restore = _load_restore_helper()+ checkpoint = tmp_path / "checkpoint"+ _write(checkpoint / "tokenizer_config.json", {"tokenizer_class": "Qwen2Tokenizer"})++ def overwrite_with_generic_class(path, **kwargs):+ _write(Path(path) / "tokenizer_config.json", {"tokenizer_class": "TokenizersBackend"})++ tokenizer = _real_source(checkpoint)+ tokenizer.original_save_pretrained = overwrite_with_generic_class++ restore.save(tokenizer, str(checkpoint))++ assert _read(checkpoint / "tokenizer_config.json")["tokenizer_class"] == "Qwen2Tokenizer"+++def _load_cache_helpers():+ root = Path(__file__).parents[2] / "unsloth"+ namespace = {+ "os": os,+ "json": json,+ "functools": __import__("functools"),+ "_LOADED_CACHE_DIR_ATTR": "_unsloth_loaded_cache_dir",+ "_LOADED_REVISION_ATTR": "_unsloth_loaded_revision",+ "_get_effective_local_files_only": lambda kwargs: False,+ "_progress_bars_were_disabled": lambda: False,+ }+ wanted = {+ "models/loader_utils.py": {+ "_mark_loaded_revision",+ "_tokenizer_cache_dir",+ "_tokenizer_revision",+ "_resolve_hub_repo_cached_file",+ "_resolve_hub_repo_local_dir",+ "_offline_aware_load",+ },+ "tokenizer_utils.py": {"_apply_post_load_tokenizer_fixes", "_load_correct_tokenizer"},+ "save.py": {+ "_capture_source_tokenizer_class",+ "_source_tokenizer_class",+ "_restore_source_tokenizer_class",+ },+ }+ for filename, names in wanted.items():+ source = root / filename+ tree = ast.parse(source.read_text(encoding = "utf-8"))+ nodes = [+ node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in names+ ]+ for node in nodes:+ node.body = [+ child+ for child in node.body+ if not (isinstance(child, ast.ImportFrom) and child.level)+ ]+ module = ast.fix_missing_locations(ast.Module(body = nodes, type_ignores = []))+ exec(compile(module, str(source), "exec"), namespace)+ return namespace++[email protected]("cache_kind", ["explicit", "colab", "kaggle"])+def test_online_custom_cache_restores_source_class(tmp_path, monkeypatch, cache_kind):+ monkeypatch.chdir(tmp_path)+ helpers = _load_cache_helpers()+ cache = {+ "explicit": tmp_path / "custom",+ "colab": Path("huggingface_tokenizers_cache"),+ "kaggle": tmp_path / "kaggle" / "custom",+ }[cache_kind]+ repo = "synthetic-review/tokenizer-class-cache"+ snapshot = cache / "models--synthetic-review--tokenizer-class-cache" / "snapshots" / ("1" * 40)+ _real_source(snapshot)+ refs = snapshot.parents[1] / "refs"+ refs.mkdir()+ (refs / "main").write_text("1" * 40, encoding = "utf-8")+ tokenizer = Qwen2TokenizerFast.from_pretrained(+ repo,+ cache_dir = cache,+ local_files_only = True,+ )+ assert not hasattr(tokenizer, "_unsloth_source_tokenizer_class")+ if cache_kind != "explicit":+ helpers.update(+ IS_COLAB_ENVIRONMENT = cache_kind == "colab",+ IS_KAGGLE_ENVIRONMENT = cache_kind == "kaggle",+ KAGGLE_TMP = str(tmp_path / "kaggle"),+ AutoTokenizer = types.SimpleNamespace(from_pretrained = lambda *args, **kwargs: tokenizer),+ _repair_tokenizer_backend_from_json = lambda value, **kwargs: value,+ _fix_llava_num_additional_image_tokens = lambda value, **kwargs: value,+ )+ load = helpers["_offline_aware_load"](+ lambda **kwargs: helpers["_load_correct_tokenizer"](repo, fix_tokenizer = False, **kwargs)+ )+ loaded = load(cache_dir = "custom") if cache_kind == "kaggle" else load()+ else:+ load = helpers["_offline_aware_load"](lambda **kwargs: tokenizer)+ loaded = load(cache_dir = cache)+ assert loaded is tokenizer+ assert not getattr(loaded, "_unsloth_local_files_only", False)+ assert helpers["_tokenizer_cache_dir"](loaded) == str(cache)+ assert helpers["_source_tokenizer_class"](loaded) == "Qwen2Tokenizer"+ _write(tmp_path / "out" / "tokenizer_config.json", {"tokenizer_class": "TokenizersBackend"})+ helpers["_restore_source_tokenizer_class"](loaded, tmp_path / "out")+ assert _read(tmp_path / "out" / "tokenizer_config.json")["tokenizer_class"] == "Qwen2Tokenizer"++[email protected]("cached", [False, True])[email protected]("subfolder", ["", "nested"])+def test_managed_tokenizer_json_source_survives_source_changes(tmp_path, cached, subfolder):+ helpers = _load_cache_helpers()+ cache = tmp_path / "cache"+ repo = "synthetic-review/source-provenance"+ snapshot = cache / "models--synthetic-review--source-provenance" / "snapshots" / ("1" * 40)+ root = snapshot if cached else tmp_path / "source"+ backend = Tokenizer(models.WordLevel({"[UNK]": 0, "a": 1}, unk_token = "[UNK]"))+ tokenizer = PreTrainedTokenizerFast(tokenizer_object = backend, unk_token = "[UNK]")+ tokenizer.save_pretrained(root / subfolder)+ config_path = root / subfolder / "tokenizer_config.json"+ config = _read(config_path)+ config["tokenizer_class"] = "Qwen2Tokenizer"+ _write(config_path, config)+ if subfolder:+ _write(root / "tokenizer_config.json", {"tokenizer_class": "LlamaTokenizer"})+ if cached:+ refs = snapshot.parents[1] / "refs"+ refs.mkdir()+ (refs / "main").write_text("1" * 40, encoding = "utf-8")+ source = repo if cached else str(root)+ load_kwargs = dict(cache_dir = cache, local_files_only = True, subfolder = subfolder)+ load = lambda **kwargs: PreTrainedTokenizerFast.from_pretrained(source, **kwargs)+ external = load(**load_kwargs)+ assert helpers["_source_tokenizer_class"](external) is None+ loaded = helpers["_offline_aware_load"](load)(**load_kwargs)+ assert helpers["_source_tokenizer_class"](loaded) == "Qwen2Tokenizer"+ if cached:+ replacement = snapshot.parent / ("2" * 40)+ _write(+ replacement / subfolder / "tokenizer_config.json", {"tokenizer_class": "BertTokenizer"}+ )+ (refs / "main").write_text("2" * 40, encoding = "utf-8")+ config_path.unlink()+ assert helpers["_source_tokenizer_class"](loaded) == "Qwen2Tokenizer"++[email protected]("known_source", [False, True])+def test_inner_tokenizer_context_wins_over_model_only_subfolder(tmp_path, known_source):+ helpers = _load_cache_helpers()+ helpers.update(+ _repair_tokenizer_backend_from_json = lambda value, **kwargs: value,+ _fix_llava_num_additional_image_tokens = lambda value, **kwargs: value,+ )+ tokenizer = PreTrainedTokenizerFast(+ tokenizer_object = Tokenizer(models.WordLevel({"[UNK]": 0}, unk_token = "[UNK]")),+ unk_token = "[UNK]",+ )+ tokenizer.save_pretrained(tmp_path)+ config = _read(tmp_path / "tokenizer_config.json")+ config["tokenizer_class"] = "Qwen2Tokenizer" if known_source else None+ _write(tmp_path / "tokenizer_config.json", config)+ _write(tmp_path / "nested" / "tokenizer_config.json", {"tokenizer_class": "BertTokenizer"})++ def load(**kwargs):+ loaded = PreTrainedTokenizerFast.from_pretrained(tmp_path, local_files_only = True)+ return helpers["_apply_post_load_tokenizer_fixes"](loaded, fix_tokenizer = False)++ loaded = helpers["_offline_aware_load"](load)(subfolder = "nested")+ assert helpers["_source_tokenizer_class"](loaded) == (+ "Qwen2Tokenizer" if known_source else None+ )+++def test_resolved_vocab_directory_wins_over_outer_source_context(tmp_path):+ helpers = _load_cache_helpers()+ _real_source(tmp_path / "nested")+ _write(tmp_path / "tokenizer_config.json", {"tokenizer_class": "BertTokenizer"})+ loaded = Qwen2TokenizerFast.from_pretrained(tmp_path, subfolder = "nested", local_files_only = True)+ assert Path(loaded.init_kwargs["vocab_file"]).parent == tmp_path / "nested"+ helpers["_mark_loaded_revision"](loaded, None, load_kwargs = {})+ assert helpers["_source_tokenizer_class"](loaded) == "Qwen2Tokenizer"diff --git a/tests/saving/test_tokenizer_class_export_finalization.py b/tests/saving/test_tokenizer_class_export_finalization.pynew file mode 100644index 00000000000..03f549b86a0--- /dev/null+++ b/tests/saving/test_tokenizer_class_export_finalization.py@@ -0,0 +1,206 @@+# SPDX-License-Identifier: AGPL-3.0-or-later++import ast+import json+import os+from pathlib import Path+from types import SimpleNamespace++import pytest+import transformers+from packaging.version import Version+from tokenizers import Tokenizer, models+from transformers import AutoTokenizer, Qwen2TokenizerFast+++SOURCE = Path(__file__).parents[2] / "unsloth/save.py"+EXPORTS = (+ "_unsloth_save_compressed_tensors",+ "_unsloth_save_torchao",+ "_unsloth_save_openvino",+)+++def _tree():+ return ast.parse(SOURCE.read_text(encoding = "utf-8"))+++def _calls(node, name):+ return any(+ isinstance(child, ast.Call) and isinstance(child.func, ast.Name) and child.func.id == name+ for child in ast.walk(node)+ )+++def _execute(nodes, namespace):+ module = ast.fix_missing_locations(ast.Module(body = nodes, type_ignores = []))+ exec(compile(module, str(SOURCE), "exec"), namespace)+++def _namespace(tokenizer, output):+ namespace = {+ "os": os,+ "json": json,+ "tokenizer": tokenizer,+ "token": None,+ "out_dir": str(output),+ "final_dir": str(output),+ "source_tokenizer_class": None,+ "logger": SimpleNamespace(warning_once = lambda *a, **k: None),+ }+ helpers = {+ "_capture_source_tokenizer_class",+ "_source_tokenizer_class",+ "_restore_source_tokenizer_class",+ "_preserve_repaired_tokenizer_class",+ }+ _execute(+ [+ node+ for node in _tree().body+ if isinstance(node, ast.FunctionDef) and node.name in helpers+ ],+ namespace,+ )+ capture = namespace.get("_capture_source_tokenizer_class")+ if capture is not None and tokenizer is not None:+ capture(tokenizer, source = tokenizer.name_or_path)+ return namespace+++def _capture_and_finalize(name, namespace, action):+ fn = next(+ node for node in _tree().body if isinstance(node, ast.FunctionDef) and node.name == name+ )+ capture = [+ node+ for node in fn.body+ if isinstance(node, ast.Assign)+ and any(+ isinstance(target, ast.Name) and target.id == "source_tokenizer_class"+ for target in node.targets+ )+ ]+ _execute(capture, namespace)+ action()+ finalizers = [+ node+ for node in ast.walk(fn)+ if isinstance(node, ast.If)+ and any(+ isinstance(child, ast.Expr) and _calls(child, "_restore_source_tokenizer_class")+ for child in node.body+ )+ and any(+ isinstance(child, ast.Expr) and _calls(child, "_preserve_repaired_tokenizer_class")+ for child in node.body+ )+ ]+ _execute(finalizers, namespace)+++def _tokenizer(source):+ source.mkdir(parents = True, exist_ok = True)+ Tokenizer(models.BPE({"a": 0, "b": 1}, [])).model.save(str(source))+ tokenizer = Qwen2TokenizerFast(+ vocab_file = str(source / "vocab.json"), merges_file = str(source / "merges.txt")+ )+ tokenizer.save_pretrained(source)+ return Qwen2TokenizerFast.from_pretrained(source)++[email protected]("export", EXPORTS)[email protected]("repaired", [False, True])+def test_final_export_repairs_secondary_tokenizer_save(tmp_path, export, repaired):+ tokenizer = _tokenizer(tmp_path / "source")+ tokenizer._unsloth_tokenizer_json_repaired = repaired+ output = tmp_path / "final"+ namespace = _namespace(tokenizer, output)++ def secondary_save():+ tokenizer.save_pretrained(output)+ config_path = output / "tokenizer_config.json"+ config = json.loads(config_path.read_text(encoding = "utf-8"))+ config["tokenizer_class"] = "TokenizersBackend"+ config["exporter_metadata"] = "retained"+ config_path.write_text(json.dumps(config), encoding = "utf-8")++ _capture_and_finalize(export, namespace, secondary_save)++ config = json.loads((output / "tokenizer_config.json").read_text(encoding = "utf-8"))+ assert config["tokenizer_class"] == (+ "PreTrainedTokenizerFast" if repaired else "Qwen2Tokenizer"+ )+ assert config["exporter_metadata"] == "retained"++[email protected]("export", EXPORTS)+def test_final_export_without_tokenizer_leaves_exporter_metadata(tmp_path, export):+ output = tmp_path / "final"+ namespace = _namespace(None, output)++ def secondary_save():+ output.mkdir()+ (output / "tokenizer_config.json").write_text(+ '{"tokenizer_class":"TokenizersBackend"}', encoding = "utf-8"+ )++ _capture_and_finalize(export, namespace, secondary_save)+ assert (+ json.loads((output / "tokenizer_config.json").read_text(encoding = "utf-8"))[+ "tokenizer_class"+ ]+ == "TokenizersBackend"+ )+++def test_merged_save_captures_source_before_cache_purge(tmp_path):+ tokenizer = _tokenizer(tmp_path / "source")+ output = tmp_path / "final"+ namespace = _namespace(tokenizer, output)+ fn = next(+ node+ for node in _tree().body+ if isinstance(node, ast.FunctionDef) and node.name == "unsloth_save_model"+ )+ purge_index = next(i for i, node in enumerate(fn.body) if _calls(node, "_free_cached_model"))+ capture = [+ node+ for node in fn.body[:purge_index]+ if isinstance(node, ast.Assign) and _calls(node, "_source_tokenizer_class")+ ]+ _execute(capture, namespace)+ assert namespace["source_tokenizer_class"] == "Qwen2Tokenizer"+ (tmp_path / "source/tokenizer_config.json").unlink()+ tokenizer.save_pretrained(output)+ config_path = output / "tokenizer_config.json"+ config_path.write_text('{"tokenizer_class":"TokenizersBackend"}', encoding = "utf-8")+ namespace["tokenizer_save_settings"] = {"save_directory": str(output)}+ finalizers = [+ node+ for node in ast.walk(fn)+ if isinstance(node, ast.Expr) and _calls(node, "_restore_source_tokenizer_class")+ ]+ _execute(finalizers, namespace)+ assert (+ json.loads(config_path.read_text(encoding = "utf-8"))["tokenizer_class"] == "Qwen2Tokenizer"+ )+++ not Version("5.2") <= Version(transformers.__version__) <= Version("5.5.0"),+ reason = "generic Qwen3.5 serialization in Transformers 5.2-5.5",+)[email protected]("export", EXPORTS)+def test_real_secondary_qwen3_5_save_keeps_compatible_class(tmp_path, export):+ original = _tokenizer(tmp_path / "staging")+ (tmp_path / "staging/config.json").write_text('{"model_type":"qwen3_5"}', encoding = "utf-8")+ reloaded = AutoTokenizer.from_pretrained(tmp_path / "staging")+ output = tmp_path / "final"+ namespace = _namespace(original, output)+ assert type(reloaded).__name__ == "TokenizersBackend"++ _capture_and_finalize(export, namespace, lambda: reloaded.save_pretrained(output))++ config = json.loads((output / "tokenizer_config.json").read_text(encoding = "utf-8"))+ assert config["tokenizer_class"] == "Qwen2Tokenizer"diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.pyindex bcfa311e4b5..7774ab77912 100644--- a/unsloth/models/loader_utils.py+++ b/unsloth/models/loader_utils.py@@ -4812,12 +4812,14 @@ _LOADED_CACHE_DIR_ATTR = "_unsloth_loaded_cache_dir"_LOADED_REVISION_ATTR = "_unsloth_loaded_revision"-def _mark_loaded_revision(result, revision):- """Stamp the ref a tokenizer/processor was loaded at onto the returned objects."""- if revision is None:- return result+def _mark_loaded_revision(+ result,+ revision,+ cache_dir = None,+ load_kwargs = None,+):+ from ..save import _capture_source_tokenizer_classfor obj in result if isinstance(result, (tuple, list)) else (result,):- # Objects that reject new attributes (__slots__) are skipped.try:targets = (obj, getattr(obj, "tokenizer", None))except Exception:@@ -4826,7 +4828,23 @@ def _mark_loaded_revision(result, revision):if target is None:continuetry:- setattr(target, _LOADED_REVISION_ATTR, str(revision))+ if revision is not None:+ setattr(target, _LOADED_REVISION_ATTR, str(revision))+ if cache_dir and not getattr(target, _LOADED_CACHE_DIR_ATTR, None):+ setattr(target, _LOADED_CACHE_DIR_ATTR, str(cache_dir))+ source_tokenizer = getattr(target, "tokenizer", target)+ context = load_kwargs or {}+ _capture_source_tokenizer_class(+ target,+ source = getattr(source_tokenizer, "name_or_path", None)+ if load_kwargs is not None+ else None,+ cache_dir = _tokenizer_cache_dir(source_tokenizer),+ revision = _tokenizer_revision(source_tokenizer)+ or context.get("tokenizer_revision")+ or context.get("revision"),+ subfolder = context.get("subfolder") or "",+ )except Exception:passreturn result@@ -5150,14 +5168,21 @@ def _offline_aware_load(fn):@functools.wraps(fn)def _wrapper(*args, **kwargs):+ def finish(result):+ return _mark_loaded_revision(+ result, None, cache_dir = kwargs.get("cache_dir"), load_kwargs = kwargs+ )+if _get_effective_local_files_only(kwargs):kwargs["local_files_only"] = Truewith _force_hf_offline():# Stamp inside the window: the env vars are restored on exit, so the request has to travel on the objects themselves to reach saving.- return _mark_loaded_local_files_only(fn(*args, **kwargs), kwargs.get("cache_dir"))+ return finish(+ _mark_loaded_local_files_only(fn(*args, **kwargs), kwargs.get("cache_dir"))+ )_pb_were_disabled = _progress_bars_were_disabled()try:- return fn(*args, **kwargs)+ return finish(fn(*args, **kwargs))except Exception as e:# Skip if not network-related, or already retried by a nested decorator (else outer layers reload the whole model again).if not _is_offline_related_error(e) or getattr(e, "_unsloth_offline_retried", False):@@ -5176,7 +5201,7 @@ def _offline_aware_load(fn):kwargs["local_files_only"] = Truetry:with _force_hf_offline():- return fn(*args, **kwargs)+ return finish(fn(*args, **kwargs))except Exception as e:# A real retry failure (corrupt checkpoint, OOM) is news and goes out as itself; only the empty-cache artifact is worth replacing.if not _empty_cache_artifact(e):diff --git a/unsloth/save.py b/unsloth/save.pyindex 16e52267af2..cf109c5d519 100644--- a/unsloth/save.py+++ b/unsloth/save.py@@ -1028,6 +1028,113 @@ def _without_runtime_truncation()+def _capture_source_tokenizer_class(+ tokenizer,+ *,+ source = None,+ cache_dir = None,+ revision = None,+ subfolder = "",+):+ source_tokenizer = getattr(tokenizer, "tokenizer", tokenizer)+ if source_tokenizer is None or hasattr(source_tokenizer, "_unsloth_source_tokenizer_class"):+ return+ init_kwargs = getattr(source_tokenizer, "init_kwargs", {})+ if not isinstance(init_kwargs, dict):+ return+ config_paths = []+ for name in ("tokenizer_file", "vocab_file", "merges_file"):+ path = init_kwargs.get(name) or getattr(source_tokenizer, name, None)+ if isinstance(path, (str, os.PathLike)) and os.path.isfile(path):+ config_paths.append(+ os.path.join(os.path.dirname(os.path.abspath(path)), "tokenizer_config.json")+ )+ if source and hasattr(source_tokenizer, "init_kwargs"):+ filename = "/".join(part for part in (subfolder, "tokenizer_config.json") if part)+ if os.path.isdir(source):+ config_paths.append(os.path.join(source, filename))+ else:+ from huggingface_hub import try_to_load_from_cache+ try:+ path = try_to_load_from_cache(+ source, filename, cache_dir = cache_dir, revision = revision+ )+ except (OSError, ValueError, TypeError):+ path = None+ if isinstance(path, str):+ config_paths.append(path)+ for config_path in config_paths:+ if not config_path:+ continue+ try:+ with open(config_path, "r", encoding = "utf-8") as file:+ source_class = json.load(file).get("tokenizer_class")+ except (OSError, ValueError, TypeError):+ continue+ source_tokenizer._unsloth_source_tokenizer_class = source_class+ return+ if source is not None:+ source_tokenizer._unsloth_source_tokenizer_class = None+++def _source_tokenizer_class(tokenizer, token = None):+ """Return the class retained during loading, never re-resolve a mutable source."""+ source_tokenizer = getattr(tokenizer, "tokenizer", tokenizer)+ source_class = getattr(source_tokenizer, "_unsloth_source_tokenizer_class", None)+ if not isinstance(source_class, str) or source_class in ("", "TokenizersBackend"):+ return None+ return source_class+++def _restore_source_tokenizer_class(+ tokenizer,+ save_directory,+ filename_prefix = None,+ token = None,+ source_class = None,+):+ if tokenizer is None or save_directory is None:+ return+ tokenizer_config_name = (+ f"{filename_prefix}-tokenizer_config.json" if filename_prefix else "tokenizer_config.json"+ )+ tokenizer_config = os.path.join(str(save_directory), tokenizer_config_name)+ if not os.path.isfile(tokenizer_config):+ return+ try:+ with open(tokenizer_config, "r", encoding = "utf-8") as file:+ config = json.load(file)+ if config.get("tokenizer_class") != "TokenizersBackend":+ return+ if source_class is None:+ source_class = _source_tokenizer_class(tokenizer, token = token)+ if source_class is None:+ source_class = "PreTrainedTokenizerFast"+ if source_class in ("LlamaTokenizer", "LlamaTokenizerFast"):+ source_tokenizer = getattr(tokenizer, "tokenizer", tokenizer)+ backend = getattr(source_tokenizer, "_tokenizer", None)+ pre_tokenizer = getattr(backend, "pre_tokenizer", None)+ if pre_tokenizer is not None:+ pending = [json.loads(pre_tokenizer.__getstate__())]+ while pending:+ item = pending.pop()+ if isinstance(item, dict):+ if item.get("type") == "ByteLevel":+ source_class = "PreTrainedTokenizerFast"+ break+ pending.extend(item.values())+ elif isinstance(item, list):+ pending.extend(item)+ config["tokenizer_class"] = source_class+ with open(tokenizer_config, "w", encoding = "utf-8") as file:+ json.dump(config, file, indent = 2, ensure_ascii = False)+ file.write("\n")+ except Exception as error:+ logger.warning_once(+ f"Unsloth: Could not restore tokenizer_class in {tokenizer_config}: {error}"+ )++def _preserve_repaired_tokenizer_class(tokenizer,save_directory,@@ -1811,6 +1918,8 @@ def unsloth_save_model(if not os.path.exists(temporary_location):os.makedirs(temporary_location)+ source_tokenizer_class = _source_tokenizer_class(tokenizer, token = token)+# Kaggle and Colab allow only 20GB of disk, so free up 4GB of space.if IS_KAGGLE_ENVIRONMENT or IS_COLAB_ENVIRONMENT:logger.warning_once(@@ -1979,6 +2088,13 @@ def unsloth_save_model(tokenizer_save_settings["save_directory"],filename_prefix = tokenizer_save_settings.get("filename_prefix"),)+ _restore_source_tokenizer_class(+ tokenizer,+ tokenizer_save_settings["save_directory"],+ filename_prefix = tokenizer_save_settings.get("filename_prefix"),+ token = tokenizer_save_settings.get("token"),+ source_class = source_tokenizer_class,+ )_preserve_repaired_tokenizer_class(tokenizer,tokenizer_save_settings["save_directory"],@@ -7901,6 +8017,7 @@ def _unsloth_save_compressed_tensors(# Only the main process installs deps, merges, quantizes and uploads, mirroring the non-PEFT save path; other ranks return at once rather than race on dirs or run pip installs.if not is_main_process:return None+ source_tokenizer_class = _source_tokenizer_class(tokenizer, token = token)if _attached_mtp_head(model) is not None:# The quantizer reloads through transformers, which drops native MTP tensors.print(@@ -8093,6 +8210,12 @@ def _unsloth_save_compressed_tensors(f"{e.returncode}). See the output above for details.")+ if tokenizer is not None:+ _restore_source_tokenizer_class(+ tokenizer, out_dir, token = token, source_class = source_tokenizer_class+ )+ _preserve_repaired_tokenizer_class(tokenizer, out_dir)+cfg_path = os.path.join(out_dir, "config.json")cfg = {}if os.path.exists(cfg_path):@@ -8166,6 +8289,7 @@ def _unsloth_save_torchao("GGUF to keep it.")+ source_tokenizer_class = _source_tokenizer_class(tokenizer, token = token)from transformers import (AutoModelForCausalLM,AutoTokenizer,@@ -8279,6 +8403,11 @@ def _unsloth_save_torchao(quantized_model.save_pretrained(out_dir, safe_serialization = safe_serialization)staged_tokenizer.save_pretrained(out_dir)+ if tokenizer is not None:+ _restore_source_tokenizer_class(+ tokenizer, out_dir, token = token, source_class = source_tokenizer_class+ )+ _preserve_repaired_tokenizer_class(tokenizer, out_dir)del quantized_model_collect_garbage(after = clean_gpu_cache)@@ -8609,6 +8738,7 @@ def _unsloth_save_openvino(return None# Everything that can reject the request runs before the merge, which writes a full 16bit checkpoint. optimum-cli takes one --trust-remote-code for the model and tokenizer loads together, so it follows the model's approved load decision, as the GGUF-LoRA converter does: a custom tokenizer alone must not let the reload run a built-in-loaded model's unvetted auto_map code.+ source_tokenizer_class = _source_tokenizer_class(tokenizer, token = token)export_kwargs = dict(export_kwargs)if _loaded_via_remote_code(model):export_kwargs.setdefault("trust_remote_code", True)@@ -8692,6 +8822,11 @@ def _unsloth_save_openvino(f"Unsloth: OpenVINO export failed (optimum-cli exit {e.returncode}). ""See the output above for details.")+ if tokenizer is not None:+ _restore_source_tokenizer_class(+ tokenizer, final_dir, token = token, source_class = source_tokenizer_class+ )+ _preserve_repaired_tokenizer_class(tokenizer, final_dir)exported = os.listdir(final_dir) if os.path.isdir(final_dir) else []if not any(f.startswith("openvino_") and f.endswith("model.xml") for f in exported):raise RuntimeError(f"Unsloth: OpenVINO export wrote no model to '{final_dir}'.")@@ -8878,6 +9013,7 @@ def _unsloth_tokenizer_save_pretrained(save_kwargs["legacy_format"] = legacy_formatif filename_prefix is not None:save_kwargs["filename_prefix"] = filename_prefix+ source_tokenizer_class = _source_tokenizer_class(self, token = kwargs.get("token", None))with _without_runtime_truncation(self, save_directory, filename_prefix):result = self.original_save_pretrained(save_directory,@@ -8894,6 +9030,13 @@ def _unsloth_tokenizer_save_pretrained(save_directory,filename_prefix = filename_prefix,)+ _restore_source_tokenizer_class(+ self,+ save_directory,+ filename_prefix = filename_prefix,+ token = kwargs.get("token", None),+ source_class = source_tokenizer_class,+ )_preserve_repaired_tokenizer_class(self,save_directory,diff --git a/unsloth/tokenizer_utils.py b/unsloth/tokenizer_utils.pyindex 3fe73d47242..b72e9462dfd 100644--- a/unsloth/tokenizer_utils.py+++ b/unsloth/tokenizer_utils.py@@ -536,6 +536,9 @@ def _apply_post_load_tokenizer_fixes(tokenizer = _repair_tokenizer_backend_from_json(tokenizer, cache_dir = cache_dir, revision = revision)+ from .models.loader_utils import _mark_loaded_revision++ _mark_loaded_revision(tokenizer, revision, cache_dir = cache_dir, load_kwargs = {})tokenizer = _fix_llava_num_additional_image_tokens(tokenizer, config = config)if not fix_tokenizer:return tokenizer