Prhub

#30396 Fix garbage output for bare-tekken Mistral checkpoints (e.g. Leanstral)

原始 PR 作者 JustinTong0323 合并时间 2026-07-10 02:38 文件变更 4 提交数 3 评论 16 代码增减 +138 / -12

执行摘要

修复 bare-tekken 检查点 tokenizer 路由,消除生成垃圾输出

Serving bare-tekken Mistral 检查点(如 mistralai/Leanstral-1.5-119B-A6B)时产生纯垃圾输出,而相同权重在 vLLM 上工作正常。根因是 transformers 的 AutoTokenizer 在转换 tekken.json 时,将 BPE id 从 rank 0 开始分配,丢弃了 tekken id 空间中前 1000 个特殊 token 槽位,导致每个编码 id 偏移 1000,embedding 查找完全错误。

值得精读,展示了如何通过精确的文件存在性检测优雅解决 tokenizer 兼容性问题,并包含完整的测试和冷缓存兜底设计。团队可从中学习针对 Hugging Face Hub 缓存策略的边界处理模式。

讨论亮点
  • 冷缓存检测缺陷:gemini-code-assist[bot] 指出初始实现仅通过 local_files_only 缓存检测,远程仓库冷启动时文件未缓存,检测失败。alexnails 在后续提交中添加 _remote_file_exists 使用 HfApi.file_exists 进行远程 HEAD 探测,确保冷缓存也能正确检测。
  • 日志添加:alexnails 评论要求在路由分支添加日志,以便其他 tokenizer 后端知晓行为变更。最终在路由分支添加了 logger.info,明确打印检测信息和忽略的 tokenizer_backend。

实现拆解

  1. 新增文件存在性检测辅助函数:在 common.py 中添加 _cached_file_exists(基于 _resolve_local_or_cached_file 本地缓存检查)和 _remote_file_exists(使用 HfApi.file_exists 进行远程 HEAD 探测),为后续检测提供无网络/有网络两种模式。
  2. 核心检测逻辑:在 mistral_utils.py 中新增 is_bare_tekken_checkpoint(tokenizer_name, revision) 函数,按优先级依次判断:本地目录中同时存在 tekken.json 且不存在 tokenizer.json → HF 缓存中仅存在 tekken.json → 远程仓库仅存在 tekken.json(HEAD 请求),任一条件满足即返回 True。冷缓存场景通过远程探测兜底。
  3. 集成路由:在 tokenizer.py 的 get_tokenizer 函数的 try 块起始处插入检测分支,若 is_bare_tekken_checkpoint 返回 True,则直接调用 MistralCommonTokenizer.from_pretrained 加载 tokenizer,并输出日志表明绕过了默认 tokenizer_backend。否则仍走原 _auto_tokenizer_from_pretrained 路径。加载后的 tokenizer 仍经过 _apply_post_load_fixes 统一后处理。
  4. 测试覆盖:新增 test_tekken_tokenizer_routing.py,包含 TestBareTekkenDetection(验证检测函数对本地目录的 true/false 判断)和 TestTekkenRouting(从 Hugging Face Hub 下载真实 tekken.json,构造 bare-tekken 目录,断言 get_tokenizer 返回的 tokenizer 编码结果与 mistral-common 参考 id 一致)。
文件 模块 状态 重要度
python/sglang/srt/utils/hf_transformers/mistral_utils.py Mistral 工具 modified 7.3
python/sglang/srt/utils/hf_transformers/tokenizer.py Token 加载 modified 6.82
python/sglang/srt/utils/hf_transformers/common.py 文件工具 modified 6.86
test/registered/unit/tokenizer/test_tekken_tokenizer_routing.py 测试 added 6.91

关键符号

is_bare_tekken_checkpoint _cached_file_exists _remote_file_exists

关键源码片段

python/sglang/srt/utils/hf_transformers/mistral_utils.py core-logic

核心检测逻辑所在,新增 `is_bare_tekken_checkpoint` 函数,实现三步检测决定 tokenizer 路由。

def is_bare_tekken_checkpoint(tokenizer_name, revision=None) -> bool:
    """True iff the checkpoint ships tekken.json but no tokenizer.json.
​
    AutoTokenizer converts tekken.json on the fly, but the converter assigns
    BPE ids from rank 0, dropping the 1000 special-token slots that precede
    the BPE vocab in tekken's id space — every encoded id is shifted and
    generation produces garbage. Such checkpoints must load through the
    mistral-common backed tokenizer instead.
    """
    # 第 1 步:如果 tokenizer_name 是本地目录,直接检查文件存在性
    local_dir = Path(tokenizer_name)
    if local_dir.is_dir():
        return (local_dir / "tekken.json").is_file() and not (
            local_dir / "tokenizer.json"
        ).is_file()
​
    # 第 2 步:检查本地 Hugging Face 缓存(无网络)
    if _cached_file_exists(tokenizer_name, "tokenizer.json", revision):
        return False
    if _cached_file_exists(tokenizer_name, "tekken.json", revision):
        return True
​
    # 第 3 步:冷缓存远程探测(HEAD 请求,不下载文件)
    if not _remote_file_exists(tokenizer_name, "tekken.json", revision):
        return False
    return not _remote_file_exists(tokenizer_name, "tokenizer.json", revision)
python/sglang/srt/utils/hf_transformers/tokenizer.py dependency-wiring

集成路由入口,在 `get_tokenizer` 中插入 bare-tekken 检测分支,是变动生效的关键位置。

try:
    # 新增:bare-tekken 检查点检测 — 优先使用 mistral-common 原生 tokenizer
    if is_bare_tekken_checkpoint(tokenizer_name, tokenizer_revision):
        from transformers.tokenization_mistral_common import (
            MistralCommonTokenizer,
        )
​
        logger.info(
            "Detected bare-tekken checkpoint %s (tekken.json, no "
            "tokenizer.json); loading via mistral-common MistralCommonTokenizer, "
            "ignoring tokenizer_backend=%r.",
            tokenizer_name,
            tokenizer_backend,
        )
​
        tokenizer = MistralCommonTokenizer.from_pretrained(
            tokenizer_name, revision=tokenizer_revision
        )
    else:
        # 原有路径:标准 AutoTokenizer 加载
        tokenizer = _auto_tokenizer_from_pretrained(
            tokenizer_name, *args, **common_kwargs
        )
​
        # fastokens 兼容性处理(原有逻辑)
        if (
            type(tokenizer).__name__ == _TOKENIZERS_BACKEND
            and tokenizer_backend != "fastokens"
        ):
            tokenizer = _resolve_tokenizers_backend(
                tokenizer_name, *args, **common_kwargs
            )
​
    return _apply_post_load_fixes(tokenizer, tokenizer_name, tokenizer_revision)
except Exception as e:
    ...
python/sglang/srt/utils/hf_transformers/common.py dependency-wiring

新增两个文件存在性检查函数,为检测逻辑提供本地缓存和远程探测能力,是底层支撑。

def _cached_file_exists(model_name_or_path, filename, revision=None) -> bool:
    """Whether *filename* is available locally or in the HF cache (no network)."""
    try:
        # 复用已有的本地 / 缓存文件解析函数
        _resolve_local_or_cached_file(model_name_or_path, filename, revision)
        return True
    except Exception:
        # 任何异常(文件不存在、HF 缓存未命中、无效路径)均视为不存在
        return False
​
​
def _remote_file_exists(repo_id, filename, revision=None) -> bool:
    """Whether *filename* exists on the HF hub (HEAD request only, no download).
​
    Returns False on any error (offline, gated, network, invalid id) so callers
    fall back to their default path instead of crashing.
    """
    from huggingface_hub.constants import HF_HUB_OFFLINE
​
    if HF_HUB_OFFLINE:
        return False
    try:
        from huggingface_hub import HfApi
​
        return HfApi().file_exists(repo_id, filename, revision=revision)
    except Exception:
        return False

评论区精华

冷缓存下 is_bare_tekken_checkpoint 检测失效 正确性

gemini-code-assist[bot] 指出初始实现仅通过 local_files_only 检测缓存,对于远程仓库冷启动,文件未缓存时检测失败,无法正确路由。

结论:alexnails 在后续提交中添加 _remote_file_exists 使用 HfApi.file_exists 进行远程 HEAD 探测,确保冷缓存也能正确检测。 · 已解决

路由分支添加日志以便调试 style

alexnails 评论 'going to add log here or somewhere in path just so other tokenizer backends know as the non specific behavior here is not great'。

结论:最终在路由分支添加了 logger.info,明确打印检测信息和忽略 tokenizer_backend。 · 已解决

风险与影响

  • 冷缓存依赖远程 HEAD 请求:_remote_file_exists 在冷缓存场景发起 HTTP HEAD 请求,可能因网络故障、HF Hub 不可用或限流而返回 False,此时 fallback 到 AutoTokenizer 默认路径,仍有垃圾输出风险。但 PR 通过异常捕获确保不崩溃。
  • tokenizer 加载路径新增分支:get_tokenizer 中新增条件分支,可能与其他 tokenizer 后端(如 fastokens)产生交互,需要确保兼容性。当前实现仅在 bare-tekken 时忽略 tokenizer_backend,已有日志记录。
  • 影响范围可控:检测条件严格限定于「同时存在 tekken.json 且不存在 tokenizer.json」,官方的 Mistral 检查点(含 tokenizer.json)不受影响。

直接影响:之前无法正确推理的 bare-tekken Mistral 检查点(如 Leanstral)现在可生成正确文本,GSM8K 准确率从不可用恢复至 91%+。影响范围仅限于缺少 tokenizer.json 的 Mistral 原生检查点用户,对其他模型和完整检查点无影响。

冷缓存检测依赖远程 HEAD 请求 Mistral 检查点 tokenizer 路径变更 仅影响缺少 tokenizer.json 的检查点

关联 Issue

未识别关联 Issue

当前没有检测到明确关联的 Issue 链接,后续同步到相关引用后会出现在这里。

完整报告

参与讨论