Prhub

#27014 [Bug] Fix circular import in `forward_batch_info` from runtime `cp_utils` import

原始 PR 作者 hnyls2002 合并时间 2026-06-02 13:51 文件变更 1 提交数 1 评论 2 代码增减 +1 / -1

执行摘要

修复 forward_batch_info 循环导入问题

当 forward_batch_info 作为导入链入口(例如 http_server -> anthropic.serving -> req_time_stats)时,cp_utils 会触发 deep_gemm_wrapper.compile_utils 的回导,而 forward_batch_info 尚未初始化完成,导致 ImportError: cannot import name 'ForwardMode' from partially initialized module。

值得快速合入并关注。这类细粒度导入治理能预防后续类似问题,建议团队在代码审查中持续关注导入层级。

讨论亮点

无 review 讨论。

实现拆解

  1. 在 python/sglang/srt/model_executor/forward_batch_info.py 中,将第 57 行的运行时导入 from sglang.srt.layers.utils.cp_utils import ContextParallelMetadata 删除。
  2. 在文件末尾的 TYPE_CHECKING 块中(第 71 行附近)添加 from sglang.srt.layers.utils.cp_utils import ContextParallelMetadata。由于该模块已使用 from __future__ import annotations,所有注解在运行时均为字符串,不会被求值,因此移动后完全安全。
  3. 测试方面:本次为单行变更,未引入新测试文件,但现有 CI(run-ci-extra)通过,证明不会回归。
文件 模块 状态 重要度
python/sglang/srt/model_executor/forward_batch_info.py 核心数据结构 modified 5.5

关键源码片段

python/sglang/srt/model_executor/forward_batch_info.py data-contract

核心变更文件,将 ContextParallelMetadata 导入从模块级别移至 TYPE_CHECKING 块,消除循环导入。

# python/sglang/srt/model_executor/forward_batch_info.py# ... 前面的导入保持不变 ...# 删除的运行时导入:
# from sglang.srt.layers.utils.cp_utils import ContextParallelMetadata# 该导入被移动到 TYPE_CHECKING 块中,如下所示:
if TYPE_CHECKING:
    from sglang.srt.layers.logits_processor import LogitsProcessorOutput
    from sglang.srt.layers.utils.cp_utils import ContextParallelMetadata # 新位置
    from sglang.srt.managers.schedule_batch import MultimodalInputs, ScheduleBatch
    from sglang.srt.model_executor.model_runner import ModelRunner
    from sglang.srt.sampling.sampling_batch_info import SamplingBatchInfo
    from sglang.srt.speculative.spec_info import SpecInput, SpeculativeAlgorithm# 由于模块已使用 from __future__ import annotations,
# 所有类型注解在运行时均为字符串,不会被求值,
# 因此将 ContextParallelMetadata 放在 TYPE_CHECKING 下完全安全。

评论区精华

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

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

风险与影响

风险极低。ContextParallelMetadata 仅用于类型注解,移动后不影响运行时行为。依赖该类型的类型检查器(如 mypy)仍能通过 TYPE_CHECKING 块正确解析。

正面影响:消除了一个在特定依赖顺序下出现的循环导入崩溃,提升了模块导入的健壮性。影响范围仅限于以 forward_batch_info 为入口的调用路径,如 http_server 等服务启动场景。

关联 Issue

未识别关联 Issue

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

完整报告

参与讨论