Files
Iluvatar_bi-100-vllm_03/selftest_fix_tokenizer.py
wangdongyun cb9b04c95f feat: vLLM 0.6.3 engine with sliding-window guard + tokenizer fix
- sliding-window guard: add --disable-sliding-window only when the model
  really has sliding_window and the xformers backend lacks
  make_local_attention; cap --max-model-len to the window size; skip
  models whose rope_scaling is not supported by this vLLM (yarn, ...)
- tokenizer fix: rewrite tokenizer_class / extra_special_tokens /
  from_slow, keep auto_map + copied repo code; every candidate is
  verified with AutoTokenizer.from_pretrained, all-fail falls back to
  starting vLLM unchanged
- head_size patch + ixformer ops patch + weight-load progress log kept
- selftests for tokenizer, sliding window and final argv
2026-11-10 22:08:34 +00:00

315 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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
_REAL_CLASS_EXISTS = fx.class_exists
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=["<a>", "<b>"])
cand, fixes = fx.apply_common_fixes(cfg, ["tokenizer.json"], force_fast=False)
assert cand["extra_special_tokens"] == {"<a>": "<a>", "<b>": "<b>"}
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({}) == []
# ── --real:用真 tokenizer 文件跑一遍(需要 transformers + tokenizers) ─────
def _build_tiny_tokenizer(path: str) -> None:
from tokenizers import Tokenizer, decoders, models, pre_tokenizers
from transformers import PreTrainedTokenizerFast
backend = Tokenizer(models.WordLevel(
vocab={"hello": 0, "world": 1, "hi": 2, "there": 3, "<unk>": 4}, unk_token="<unk>"))
backend.pre_tokenizer = pre_tokenizers.Whitespace()
backend.decoder = decoders.WordPiece(prefix="##")
PreTrainedTokenizerFast(tokenizer_object=backend, unk_token="<unk>").save_pretrained(path)
def _read_cfg(path: str) -> Dict:
with open(os.path.join(path, "tokenizer_config.json")) as fh:
return json.load(fh)
def _write_cfg(path: str, cfg: Dict) -> None:
with open(os.path.join(path, "tokenizer_config.json"), "w") as fh:
json.dump(cfg, fh)
def _load_ok(path: str, **kw) -> None:
from transformers import AutoTokenizer
AutoTokenizer.from_pretrained(path, **kw).encode("hello world")
def _with_real_classes(fn):
def wrapper() -> None:
saved = fx.class_exists
fx.class_exists = _REAL_CLASS_EXISTS
try:
fn()
finally:
fx.class_exists = saved
wrapper.__name__ = fn.__name__
return wrapper
@_with_real_classes
def real_case_clean_model_untouched() -> None:
with tempfile.TemporaryDirectory() as tmp:
model, out = os.path.join(tmp, "m"), os.path.join(tmp, "out")
_build_tiny_tokenizer(model)
assert fx.fix(model, out, verify=True, max_bytes=1 << 20, dry_run=False) == ""
@_with_real_classes
def real_case_bad_tokenizer_class() -> None:
with tempfile.TemporaryDirectory() as tmp:
model, out = os.path.join(tmp, "m"), os.path.join(tmp, "out")
_build_tiny_tokenizer(model)
cfg = _read_cfg(model)
cfg["tokenizer_class"] = "TokenizersBackend"
_write_cfg(model, cfg)
got = fx.fix(model, out, verify=True, max_bytes=1 << 20, dry_run=False)
assert got == out, got
_load_ok(out)
assert _read_cfg(out)["tokenizer_class"] == "PreTrainedTokenizerFast"
@_with_real_classes
def real_case_extra_special_tokens_list() -> None:
with tempfile.TemporaryDirectory() as tmp:
model, out = os.path.join(tmp, "m"), os.path.join(tmp, "out")
_build_tiny_tokenizer(model)
cfg = _read_cfg(model)
cfg["extra_special_tokens"] = ["<a>", "<b>"]
_write_cfg(model, cfg)
assert fx.fix(model, out, verify=True, max_bytes=1 << 20, dry_run=False) == out
assert _read_cfg(out)["extra_special_tokens"] == {"<a>": "<a>", "<b>": "<b>"}
_load_ok(out)
@_with_real_classes
def real_case_from_slow_dropped() -> None:
with tempfile.TemporaryDirectory() as tmp:
model, out = os.path.join(tmp, "m"), os.path.join(tmp, "out")
_build_tiny_tokenizer(model)
cfg = _read_cfg(model)
cfg["from_slow"] = True
_write_cfg(model, cfg)
assert fx.fix(model, out, verify=True, max_bytes=1 << 20, dry_run=False) == out
assert "from_slow" not in _read_cfg(out)
_load_ok(out)
@_with_real_classes
def real_case_auto_map_code_kept() -> None:
with tempfile.TemporaryDirectory() as tmp:
model, out = os.path.join(tmp, "m"), os.path.join(tmp, "out")
_build_tiny_tokenizer(model)
cfg = _read_cfg(model)
cfg["tokenizer_class"] = "FooTokenizer"
cfg["auto_map"] = {"AutoTokenizer": ["tokenization_foo.FooTokenizer", None]}
_write_cfg(model, cfg)
with open(os.path.join(model, "tokenization_foo.py"), "w") as fh:
fh.write(
"from transformers import PreTrainedTokenizerFast\n\n\n"
"class FooTokenizer(PreTrainedTokenizerFast):\n pass\n"
)
assert fx.fix(model, out, verify=True, max_bytes=1 << 20, dry_run=False) == out
kept = _read_cfg(out)
assert kept["tokenizer_class"] == "FooTokenizer", kept
assert kept.get("auto_map"), kept
assert os.path.isfile(os.path.join(out, "tokenization_foo.py"))
_load_ok(out, trust_remote_code=True)
def real_cases() -> List:
cases = [
real_case_clean_model_untouched,
real_case_bad_tokenizer_class,
real_case_extra_special_tokens_list,
real_case_from_slow_dropped,
real_case_auto_map_code_kept,
]
try:
import tokenizers # noqa: F401
import transformers # noqa: F401
except Exception as exc:
print(f"SKIP real cases: {type(exc).__name__}: {exc}")
return []
return cases
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,
]
if "--real" in sys.argv:
cases += real_cases()
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())