Prhub

#37937 [Fix] Register triton.runtime.cache.triton_key in the MPS stub so torch.compile keeps working

原始 PR 作者 alexnails 合并时间 2026-09-04 13:56 文件变更 2 提交数 1 评论 0 代码增减 +28 / -1

执行摘要

修复 Apple Silicon 上导入 sglang 后 torch.compile 全局失效问题。

在 macOS arm64 上,由于 sglang 的 install_platform_stubs() 为 triton.runtime.cache 注册了元路径查找器但未预定义 triton_key 符号,导致 Python import 机制创建空命名空间模块覆盖 mock。当 torch inductor 从该路径导入 triton_key 时,获取到的是一个不可调用的模块对象,从而引发 TypeError,使得整个进程中所有 torch.compile 调用失败。

建议精读,特别是了解平台 stub 注册机制与 Python import 系统交互的微妙之处,以及如何为依赖 Triton 但无需实际执行的场景设计 mock 层。

讨论亮点

无评论。该 PR 已合并,无进一步讨论。

实现拆解

  1. 核心逻辑修复:在 python/sglang/_platform_stubs.py 的 install_platform_stubs 函数中,新增 _triton_key 函数并显式注册 triton.runtime.cache 子模块。
  2. 统一符号定义:将原 triton.compiler.compiler.triton_key 从匿名 lambda 改为共享的 _triton_key 函数,保持一致性。
  3. 回归测试:在 test/registered/unit/platforms/test_mps_triton_stub.py 中新增测试用例,验证导入 sglang 后 torch.compile 仍能正常工作。
文件 模块 状态 重要度
python/sglang/_platform_stubs.py 平台兼容层 modified 6.43
test/registered/unit/platforms/test_mps_triton_stub.py 平台测试 modified 5.28

关键符号

_triton_key install_platform_stubs

关键源码片段

python/sglang/_platform_stubs.py core-logic

核心修复文件,注册了缺失的 `triton.runtime.cache` 子模块和 `triton_key` 符号。

# 新增的辅助函数,提供稳定的 triton_key 字符串
​
def _triton_key() -> str:
    return "triton-stub"
​
# 在 install_platform_stubs 函数中,为 triton.runtime.cache 注册 mock
    cache_mod = _make_mock("triton.runtime.cache")
    cache_mod.triton_key = _triton_key # 显式绑定可调用对象
    runtime.cache = cache_mod
​
# 同时修改 triton.compiler.compiler 中的 triton_key 以保持一致
    compiler_impl.triton_key = _triton_key # 替换原来的 lambda: "triton-stub"

评论区精华

没有提炼出高价值讨论线程

当前评论区没有形成足够清晰的争议点或结论,后续有更多讨论时会体现在这里。

风险与影响

风险较低,变更仅限于 Apple Silicon 平台 stub 模块,不影响其他平台。但需注意 triton.__version__ 仍被设置为 "3.0.0",可能误导依赖版本检查的代码(但本次修复未涉及)。

影响范围:所有在 Apple Silicon 平台导入 sglang 的用户,修复了 torch.compile 全局失效问题,恢复了与非 sglang 代码的兼容性。

平台兼容性

关联 Issue

未识别关联 Issue

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

完整报告

参与讨论