#!/usr/bin/env python3 """`fix_tokenizer.py` 的离线自测(不需要 transformers / tokenizers / GPU)。 只测「配置分析与候选排队」这段纯逻辑;真正的试加载在镜像里由 `AutoTokenizer.from_pretrained` 完成(线上每次启动都会跑一遍)。 用法: python3 selftest_fix_tokenizer.py # 全绿打印 OK,失败非 0 退出 """ from __future__ import annotations import json import os import sys import tempfile from typing import Dict, List sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import fix_tokenizer as fx # noqa: E402 # 让 class_exists 在无 transformers 的环境里也能给出确定答案 KNOWN = { "Qwen2Tokenizer", "Qwen2TokenizerFast", "LlamaTokenizer", "LlamaTokenizerFast", "GPT2Tokenizer", "GPT2TokenizerFast", "PreTrainedTokenizerFast", "BERTTokenizer", } def _fake_exists(name): return None if not name else name in KNOWN fx.class_exists = _fake_exists # type: ignore[assignment] def _cfg(**kw) -> Dict: base = {"tokenizer_class": "Qwen2Tokenizer"} base.update(kw) return base def case_detect_from_slow() -> None: """有 tokenizer.json + from_slow=true:必须当成问题,且在候选里被清掉。""" cfg = _cfg(tokenizer_class="TokenizersBackend", from_slow=True) cands = fx.build_candidates(cfg, ["tokenizer.json", "tokenizer_config.json"]) assert cands, "TokenizersBackend + tokenizer.json 应该给出候选" desc, cand, needs_remote = cands[0] assert "rewrite" in desc, desc assert cand["tokenizer_class"] == "PreTrainedTokenizerFast", cand["tokenizer_class"] assert "from_slow" not in cand, "from_slow 必须被删掉" assert needs_remote is False def case_keep_auto_map() -> None: """auto_map 的 tokenization_*.py 已拷过来:优先保留类名 + remote code。""" cfg = _cfg(tokenizer_class="MuPTTokenizer", auto_map={"AutoTokenizer": ["tokenization_mupt.MuPTTokenizer", None]}) files = ["tokenizer_config.json", "vocab.json", "merges.txt", "tokenization_mupt.py"] cands = fx.build_candidates(cfg, files) assert cands, "auto_map 场景应该给出候选" desc, cand, needs_remote = cands[0] assert "auto_map" in desc and needs_remote is True, (desc, needs_remote) assert cand["tokenizer_class"] == "MuPTTokenizer", cand["tokenizer_class"] # 兜底候选存在,但类名改成按数据文件挑的 fast 类,并去掉 auto_map if len(cands) > 1: d2, c2, r2 = cands[1] assert c2.get("auto_map") is None, "兜底候选必须去掉 auto_map,否则会去固定目录找 .py" assert r2 is False def case_auto_map_missing_py() -> None: """auto_map 指向的 .py 不在目录里(= 旧实现从没拷过):不能用「保留类名」候选。""" cfg = _cfg(tokenizer_class="QWenTokenizer", auto_map={"AutoTokenizer": ["tokenization_qwen.QWenTokenizer", None]}) cands = fx.build_candidates(cfg, ["tokenizer_config.json", "qwen.tiktoken"]) assert all("auto_map" not in d for d, _, _ in cands), cands assert not cands, "既没有 .py 也没有可用数据文件时应放弃(宁可不修)" def case_extra_special_tokens_list() -> None: """list → dict,其他不动。""" cfg = _cfg(extra_special_tokens=["", ""]) cand, fixes = fx.apply_common_fixes(cfg, ["tokenizer.json"], force_fast=False) assert cand["extra_special_tokens"] == {"": "", "": ""} assert any("extra_special_tokens" in f for f in fixes) assert isinstance(cfg["extra_special_tokens"], list), "不能改入参" def case_from_slow_without_tokenizer_json() -> None: """没有 tokenizer.json 时不要动 from_slow(那是给 sentencepiece 慢 tokenizer 用的)。""" cfg = _cfg(tokenizer_class="LlamaTokenizer", from_slow=True) cand, _ = fx.apply_common_fixes(cfg, ["tokenizer.model"], force_fast=False) assert cand.get("from_slow") is True, cand def case_choose_class() -> None: assert fx.choose_class(["tokenizer.json"]) == "PreTrainedTokenizerFast" assert fx.choose_class(["tokenizer.model"]) == "LlamaTokenizer" assert fx.choose_class(["vocab.json", "merges.txt"]) == "GPT2TokenizerFast" assert fx.choose_class(["tokenizer_config.json"]) is None def case_known_class_keeps_first() -> None: """类名合法时第一个候选必须是「不动类名」,兜底候选排在后面。""" cfg = _cfg(tokenizer_class="Qwen2TokenizerFast") cands = fx.build_candidates(cfg, ["tokenizer.json", "tokenizer_config.json"]) assert cands and cands[0][0] == "keep-class", cands assert cands[0][1]["tokenizer_class"] == "Qwen2TokenizerFast" # 目录里没有 tokenizer.json 时不该冒出「改写类名」的兜底候选 assert all("rewrite" not in d for d, _, _ in fx.build_candidates(cfg, ["tokenizer_config.json"])) def case_no_fix_writes_nothing() -> None: """端到端:干净模型 → stdout 为空、不创建输出目录。""" with tempfile.TemporaryDirectory() as tmp: model = os.path.join(tmp, "model") os.makedirs(model) with open(os.path.join(model, "tokenizer_config.json"), "w") as fh: json.dump(_cfg(tokenizer_class="Qwen2TokenizerFast"), fh) with open(os.path.join(model, "tokenizer.json"), "w") as fh: fh.write("{}") out = os.path.join(tmp, "out") got = fx.fix(model, out, verify=False, max_bytes=1 << 20, dry_run=False) assert got == "", got assert not os.path.exists(out) assert not os.path.exists(out + ".build") def case_payload_skips_weights() -> None: """权重文件不拷;tokenizer 数据 + 仓库自带 .py / .tiktoken 要拷。""" with tempfile.TemporaryDirectory() as tmp: model = os.path.join(tmp, "model") os.makedirs(model) for name in ("model.safetensors", "pytorch_model.bin", "tokenizer.json", "tokenization_qwen.py", "qwen.tiktoken", "config.json"): with open(os.path.join(model, name), "wb") as fh: fh.write(b"x" * 8) names = fx.payload_files(model, 1 << 20) assert "model.safetensors" not in names assert "pytorch_model.bin" not in names for keep in ("tokenizer.json", "tokenization_qwen.py", "qwen.tiktoken", "config.json"): assert keep in names, names def case_auto_map_modules() -> None: assert fx.auto_map_modules({"auto_map": {"AutoTokenizer": ["tokenization_qwen.QWenTokenizer", None]}}) == [ "tokenization_qwen.py" ] assert fx.auto_map_modules({"auto_map": ["tokenization_x.XTokenizer", "tokenization_x.XTokenizerFast"]}) == [ "tokenization_x.py" ] assert fx.auto_map_modules({}) == [] def main() -> int: cases: List = [ case_detect_from_slow, case_keep_auto_map, case_auto_map_missing_py, case_extra_special_tokens_list, case_from_slow_without_tokenizer_json, case_choose_class, case_known_class_keeps_first, case_no_fix_writes_nothing, case_payload_skips_weights, case_auto_map_modules, ] failed = 0 for case in cases: try: case() print(f" ok {case.__name__}") except AssertionError as exc: failed += 1 print(f" FAIL {case.__name__}: {exc}") print("OK" if not failed else f"{failed} failed") return 1 if failed else 0 if __name__ == "__main__": raise SystemExit(main())