# PR #27747 完整报告

- 仓库：`sgl-project/sglang`
- 标题：fix: DSV4 BCG compress-prefill plan OOB on underfilled (tiny) prefill replay
- 合并时间：2026-06-11 11:02
- 原文链接：http://prhub.com.cn/sgl-project/sglang/pull/27747

---

# PR 27747 分析报告

## 执行摘要

本 PR 修复了 DeepSeek-V4 在可中断 CUDA 图（BCG）模式下，因预填充请求远小于图桶大小时压缩预填充计划内核的越界访问问题。改动仅一行循环上界变更，但解决了启动时因 warmup 请求导致调度器崩溃的严重 bug。

## 功能与动机

当启用 `--enforce-piecewise-cuda-graph` 且图桶大小远大于请求时（例如 2048 token 桶回放 6 token 的 warmup 请求），`plan_compress_prefill_kernel0` 的 MTP 均匀路径使用填充后的缓冲区大小 `num_q` 作为循环上界，导致 `batch_id = k / E` 超出实际 batch 数。这引起读取未初始化共享状态、生成非法计划条目，并在后续内核中索引越界导致非法内存访问。

## 实现拆解

1. **定位问题路径**：`plan_compress_prefill_kernel0` 中 MTP 均匀路径（当 `min(extend_len) == max(extend_len) && extend_len <= 32` 时）使用 `num_q`（填充后的缓冲区大小）作为循环上界。
2. **修复循环边界**：将循环上界从 `num_q` 改为 `num_real_q = params.batch_size * E`，即真实 token 数。这样 `batch_id = k / E` 始终小于 `batch_size`，避免越界。
3. **保持行为一致**：填充的尾部 `[counter, num_q)` 条目已被 Stage D 标记为 `invalid`，后续内核会跳过，与通用路径行为一致。

### `python/sglang/jit_kernel/csrc/deepseek_v4/c_plan.cuh`

核心修复文件：修改了 MTP 均匀路径的循环上界，防止越界访问。

```cuda
__global__ __launch_bounds__(1024, 1)
void plan_compress_prefill_kernel0(...) {
    // ...
    if (is_mtp_extend) {
        // Path 1: token-driven. Each global token id maps to exactly one (batch_id, j).
        const uint32_t E = s_max_extend;
        // num_q is the padded buffer size (graph bucket), not the work size: cap the
        // loop at the real token count so batch_id = k / E stays < batch_size on an
        // underfilled replay; Stage D pads [counter, num_q) with invalid.
        const uint32_t num_real_q = params.batch_size * E;
        for (uint32_t k = tx; k < num_real_q; k += block_size) {
            const uint32_t batch_id = k / E;
            const uint32_t j = k % E;
            const int32_t pl = s_prefix_len[batch_id];
            // ...
        }
    }
    // ...
}

```

## 评论区精华

评审者 DarkSharpness 表示："LGTM. I never consider the padded prefill case in prefill plan. Thanks for the fix." 这说明该边界条件在初始实现时被遗漏了。

## 风险与影响

- **风险**：极低。改动量小，且当填充不存在时行为完全不变。不影响非均匀路径和其他 GPU 逻辑。
- **影响**：修复了 DeepSeek-V4 在 BCG 模式下启动崩溃，影响了所有启用 BCG 且请求远小于图桶的用户。已在 B200 和 B300 上验证修复。

## 关联脉络

本 PR 是 BCG 支持（PR #25195）的一个后续修复，解决了该功能引入的预填充计划缺陷。