Prhub

#31863 [NPU]remove duplicate code

原始 PR 作者 zhaozx-cn 合并时间 2026-07-23 10:24 文件变更 1 提交数 1 评论 5 代码增减 +0 / -2

执行摘要

移除 NPU GDN 后端重复的 ssm_states 更新代码

PR body 明确说明 "just remove duplicate code",作者发现 forward_extend 方法中第 326-327 行与第 321-325 行重复了 last_recurrent_state.to(...)ssm_states[cache_indices] = last_recurrent_state 操作,属明显的代码复制遗漏。

值得合并。这是一个干净、低风险的 bugfix,专注地解决了重复代码问题,并且有充足的测试和 benchmark 验证。对于 NPU 平台的 Mamba 模型用户有正面效果。

讨论亮点

无实质 review 讨论。唯一审核来自 sglang-npu-bot 的 approve。bot 评论说 "Only modify the NPU-related parts. After passing the NPU test cases, integrate it." 意味着该 PR 仅聚焦 NPU 模块,通过 NPU 测试即可合入。

实现拆解

  1. 定位重复代码:在 python/sglang/srt/hardware_backend/npu/attention/ascend_gdn_backend.pyforward_extend 方法中,检查 last_recurrent_state 不为 None 后立即执行了 to() 并赋值给 ssm_states;紧接着,无论条件如何,又执行了完全相同的两行操作,导致在 last_recurrent_state 不为 None 时发生两次赋值。
  2. 删除重复行:直接删除第 326-327 行(last_recurrent_state = last_recurrent_state.to(ssm_states.dtype, copy=False)ssm_states[cache_indices] = last_recurrent_state),保留了条件内的正确赋值路径。
  3. 验证无回归:NPU CI 全部通过,且作者提供了 Qwen3.5 35B 的 acc 测试(ceval: 90.5,与官方 90.2 持平或略优)和 speed benchmark 截图,显示“repeated actions on device”问题得到修复。
文件 模块 状态 重要度
python/sglang/srt/hardware_backend/npu/attention/ascend_gdn_backend.py NPU 后端 modified 4.89

关键符号

forward_extend

关键源码片段

python/sglang/srt/hardware_backend/npu/attention/ascend_gdn_backend.py core-logic

唯一变更文件,移除 `forward_extend` 中两行重复的 ssm_states 更新语句,简化逻辑并消除潜在精度问题。

# python/sglang/srt/hardware_backend/npu/attention/ascend_gdn_backend.py
# 修改位置:forward_extend 方法,约第 321-327 行
# 删除重复的两行(原第 326-327 行),它们与第 321-325 行 if 块内的赋值完全相同def forward_extend(self, ...):
    # ... 前面的代码 ...
    core_attn_out, last_recurrent_state, h = self.kernel_dispatcher.extend(...)
​
    # 正确赋值:仅在 last_recurrent_state 非 None 时赋值一次
    if last_recurrent_state is not None:
        last_recurrent_state = last_recurrent_state.to(ssm_states.dtype, copy=False)
        ssm_states[cache_indices] = last_recurrent_state
    # 原来这里的重复行已被删除,避免无条件的二次赋值
​
    if h is not None:
        self._track_mamba_state_extend(forward_batch, h, ssm_states, forward_metadata)
​
    return core_attn_out

评论区精华

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

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

风险与影响

低风险。变更仅为删除两行重复且逻辑上冗余的代码,在 last_recurrent_stateNone 时不会影响任何路径(重复行本就不会执行)。作者已提供准确的 acc 和 speed 数据,CI 通过。但谨慎起见,应确认所有调用 forward_extend 的场景(包括非 NPU)是否有间接影响,不过该文件仅针对 NPU 后端,影响范围受控。

仅影响 NPU 硬件后端下的 GDN(Mamba2 风格注意力)的 forward_extend 路径。代码瘦身后避免了重复的数据转换和设备写入,理论上轻微提升推理速度并消除潜在的精度不一致(第二次 to(ssm_states.dtype) 可能在第一次已转换的基础上引入不必要的 rounding)。对用户无行为变更。

低风险

关联 Issue

未识别关联 Issue

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

完整报告

参与讨论