<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title>DeepInfer - 标签 - 集合通信博客</title><link>https://hccl.club/tags/deepinfer/</link><description>DeepInfer - 标签 - 集合通信博客</description><generator>Hugo -- gohugo.io</generator><language>zh-CN</language><lastBuildDate>Mon, 09 Nov 2026 09:00:00 +0800</lastBuildDate><atom:link href="https://hccl.club/tags/deepinfer/" rel="self" type="application/rss+xml"/><item><title>重点特性总览</title><link>https://hccl.club/docs/inference-engines/deepinfer/00-overview/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/00-overview/</guid><description><![CDATA[<div class="fwdoc">
<style>
.fwdoc{--bg:#0b1020; --bg2:#0f1729; --panel:#141d33; --panel2:#1a2440;
  --border:#263352; --text:#dbe4f5; --muted:#8ea0c2;
  --accent:#4f8cff; --accent2:#22d3ee; --good:#34d399; --warn:#fbbf24; --bad:#f87171; --purple:#a78bfa;
  --code-bg:#0d1424; --radius:14px;}
.fwdoc *{box-sizing:border-box;margin:0;padding:0}
.fwdoc{background:linear-gradient(160deg,var(--bg) 0%,var(--bg2) 60%,#0a0f1e 100%);color:var(--text);
  font-family:"PingFang SC","Microsoft YaHei","Segoe UI",system-ui,sans-serif;line-height:1.75;}
.fwdoc{flex:1;min-width:0;padding:36px 48px 80px}
@media(max-width:960px){.fwdoc{padding:24px 18px 60px}}
.fwdoc .hero{position:relative;border-radius:var(--radius);overflow:hidden;padding:46px 44px;margin-bottom:34px;
  background:radial-gradient(1200px 400px at 15% -20%,rgba(79,140,255,.28),transparent 60%),
             radial-gradient(900px 380px at 95% 0%,rgba(167,139,250,.20),transparent 55%),
             linear-gradient(135deg,#16213e,#101a30);border:1px solid var(--border)}
.fwdoc .hero .crumb{font-size:12px;color:var(--accent2);letter-spacing:1px;margin-bottom:12px}
.fwdoc .hero h1{font-size:34px;color:#fff;font-weight:800;letter-spacing:.5px;margin-bottom:10px}
.fwdoc .hero p.desc{color:var(--muted);max-width:780px;font-size:15px}
.fwdoc .hero .tags{margin-top:18px;display:flex;gap:10px;flex-wrap:wrap}
.fwdoc .hero .tag{font-size:12px;padding:4px 14px;border-radius:999px;border:1px solid var(--border);
  background:rgba(79,140,255,.10);color:var(--accent2)}
.fwdoc .tag.good{border-color:rgba(52,211,153,.4);color:var(--good);background:rgba(52,211,153,.08)}
.fwdoc .tag.warn{border-color:rgba(251,191,36,.4);color:var(--warn);background:rgba(251,191,36,.08)}
.fwdoc section{margin-bottom:44px;scroll-margin-top:20px}
.fwdoc h2.sec{display:flex;align-items:center;gap:12px;font-size:23px;color:#fff;margin-bottom:6px;padding-bottom:10px;border-bottom:1px solid var(--border)}
.fwdoc h2.sec .num{display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:10px;flex-shrink:0;
  background:linear-gradient(135deg,var(--accent),var(--purple));color:#fff;font-size:15px;font-weight:800}
.fwdoc .lede{color:var(--muted);font-size:14px;margin-bottom:20px}
.fwdoc .grid{display:grid;gap:18px}
.fwdoc .grid.c2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}
.fwdoc .card{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:var(--radius);padding:22px 24px;transition:transform .3s,border-color .3s,box-shadow .3s}
.fwdoc .card:hover{transform:translateY(-3px);border-color:rgba(79,140,255,.55);box-shadow:0 12px 34px -14px rgba(79,140,255,.35)}
.fwdoc .card h3{font-size:16.5px;color:#fff;margin-bottom:8px;display:flex;align-items:center;gap:9px}
.fwdoc .card h3 .ico{width:26px;height:26px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;
  background:rgba(79,140,255,.16);font-size:14px;flex-shrink:0}
.fwdoc .card p{font-size:13.5px;color:var(--muted)}
.fwdoc .card p code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1.5px 7px;border-radius:6px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px}
.fwdoc .card .more{display:inline-block;margin-top:12px;font-size:13px;color:var(--accent2);text-decoration:none;font-weight:600}
.fwdoc .card .more:hover{text-decoration:underline}
.fwdoc .card .oneline{color:var(--warn);font-size:13.5px;margin-bottom:8px}
.fwdoc .card .paths{margin-top:10px;line-height:2}
.fwdoc .mini{height:86px;margin:12px -6px 4px;border-radius:10px;background:rgba(10,16,32,.55);overflow:hidden}
.fwdoc .mini svg{width:100%;height:100%;display:block}
.fwdoc ul.feat{list-style:none;margin-top:10px}
.fwdoc ul.feat li{padding:7px 0 7px 30px;position:relative;font-size:13.5px;color:var(--text);border-bottom:1px dashed rgba(38,51,82,.6)}
.fwdoc ul.feat li:last-child{border-bottom:none}
.fwdoc ul.feat li::before{content:"▸";position:absolute;left:8px;color:var(--accent);font-weight:700;animation:fw-blink 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
@keyframes fw-blink{0%,100%{opacity:.35}50%{opacity:1}}
.fwdoc .filepath{font-family:"JetBrains Mono",Consolas,monospace;font-size:11.5px;color:var(--accent2);
  background:rgba(34,211,238,.08);border:1px solid rgba(34,211,238,.25);border-radius:6px;padding:2px 10px;display:inline-block;margin:2px 4px 2px 0}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border)}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px}
.fwdoc table.tbl td{padding:10px 14px;border-top:1px solid var(--border);color:var(--text);vertical-align:top}
.fwdoc table.tbl tr{transition:background .2s}
.fwdoc table.tbl tr:nth-child(even) td{background:rgba(20,29,51,.5)}
.fwdoc table.tbl tr:hover td{background:rgba(79,140,255,.10)}
.fwdoc table.tbl td code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;font-family:Consolas,monospace;font-size:12px}
.fwdoc table.tbl a{color:var(--accent2)}
.fwdoc .full{color:var(--good);font-weight:700}
.fwdoc .half{color:var(--accent2)}
.fwdoc .reveal{opacity:0;transform:translateY(26px);transition:opacity .7s cubic-bezier(.2,.7,.3,1),transform .7s cubic-bezier(.2,.7,.3,1)}
.fwdoc .reveal.on{opacity:1;transform:none}
.fwdoc .reveal.d1{transition-delay:.12s}
.fwdoc .reveal.d2{transition-delay:.24s}
.fwdoc .reveal.d3{transition-delay:.36s}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:20px;margin:18px 0;position:relative;overflow:hidden}
.fwdoc .figure .cap{text-align:center;font-size:12.5px;color:var(--muted);margin-top:10px}
.fwdoc .figure svg{width:100%;height:auto;display:block}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-flow 1.2s linear infinite}
@keyframes fw-flow{to{stroke-dashoffset:-14}}
.fwdoc .pulse{animation:fw-pulse 2s ease-in-out infinite;transform-origin:center;transform-box:fill-box}
@keyframes fw-pulse{0%,100%{opacity:.45;transform:scale(1)}50%{opacity:1;transform:scale(1.06)}}
@keyframes fw-blinkdot{0%,100%{opacity:.3}50%{opacity:1}}
@keyframes fw-tilelit{0%,100%{opacity:.25}50%{opacity:1}}
@keyframes fw-growbar{from{width:0}to{width:100%}}
@keyframes fw-tokrun{0%{transform:translateX(-6px);opacity:0}15%{opacity:1}85%{opacity:1}100%{transform:translateX(160px);opacity:0}}
@keyframes fw-winmove{0%,100%{transform:translateX(0)}50%{transform:translateX(56px)}}
.fwdoc .station{animation:fw-stGlow 9.6s infinite;transform-box:fill-box;transform-origin:center}
@keyframes fw-stGlow{0%,4%{opacity:.55}6%,14%{opacity:1;transform:scale(1.07)}17%{transform:scale(1)}100%{opacity:.55}}
.fwdoc .note{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13px;color:var(--text);margin:16px 0}
.fwdoc .note b{color:#fff}
.fwdoc .pgnav{margin-top:60px;padding-top:20px;border-top:1px solid var(--border);color:#5a6b92;font-size:12px;
  display:flex;justify-content:space-between;flex-wrap:wrap;gap:10px}
.fwdoc .pgnav a{color:var(--accent2);text-decoration:none}
/* ===== 导入面板附加样式 ===== */
.fwdoc{border-radius:14px;margin:18px 0}
.fwdoc table.tbl{display:block;overflow-x:auto;max-width:100%}
@media (prefers-reduced-motion:reduce){
.fwdoc *,.fwdoc *::before,.fwdoc *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
.fwdoc .reveal{opacity:1!important;transform:none!important}
}

</style>

<!-- ============ 1 生命周期 ============ -->
  <section>
    <h2 class="sec"><span class="num">1</span>一次请求的生命周期</h2>
    <p class="lede">token 颗粒从左到右流经各站点,站点下方标注深入分析它的文档编号——DeepInfer 的一切设计都是为了让 GPU 前向与 CPU 调度永不互相等待。</p>
    <div class="figure reveal">
      <div style="font-size:11px;color:#5a6b92;letter-spacing:1px;text-transform:uppercase;margin-bottom:10px">ANIMATED · 请求全链路流水线</div>
      <svg viewBox="0 0 980 250" xmlns="http://www.w3.org/2000/svg">
        <line x1="40" y1="105" x2="940" y2="105" stroke="#263352" stroke-width="2"/>
        <line x1="40" y1="105" x2="940" y2="105" stroke="#4f8cff" stroke-width="2" class="flowline" opacity=".5"/>
        <g>
          <g class="station" style="animation-delay:0s"><rect x="28" y="72" width="100" height="52" rx="10" fill="#16233f" stroke="#4f8cff" stroke-width="1.6"/><text x="78" y="94" fill="#dbe4f5" font-size="13" text-anchor="middle">📥 接入</text><text x="78" y="112" fill="#8ea0c2" font-size="10" text-anchor="middle">⑤</text></g>
          <g class="station" style="animation-delay:1.2s"><rect x="148" y="72" width="100" height="52" rx="10" fill="#16233f" stroke="#4f8cff" stroke-width="1.6"/><text x="198" y="94" fill="#dbe4f5" font-size="13" text-anchor="middle">🧹 预处理</text><text x="198" y="112" fill="#8ea0c2" font-size="10" text-anchor="middle">⑦</text></g>
          <g class="station" style="animation-delay:2.4s"><rect x="268" y="72" width="100" height="52" rx="10" fill="#16233f" stroke="#a78bfa" stroke-width="1.6"/><text x="318" y="94" fill="#dbe4f5" font-size="13" text-anchor="middle">🎛️ ZOS 调度</text><text x="318" y="112" fill="#8ea0c2" font-size="10" text-anchor="middle">⑤</text></g>
          <g class="station" style="animation-delay:3.6s"><rect x="388" y="72" width="100" height="52" rx="10" fill="#16233f" stroke="#34d399" stroke-width="1.6"/><text x="438" y="94" fill="#dbe4f5" font-size="13" text-anchor="middle">🗄️ KV/重放</text><text x="438" y="112" fill="#8ea0c2" font-size="10" text-anchor="middle">④</text></g>
          <g class="station" style="animation-delay:4.8s"><rect x="508" y="72" width="120" height="52" rx="10" fill="#16233f" stroke="#fbbf24" stroke-width="1.6"/><text x="568" y="94" fill="#dbe4f5" font-size="13" text-anchor="middle">⚡ 并行前向</text><text x="568" y="112" fill="#8ea0c2" font-size="10" text-anchor="middle">①②⑧⑩</text></g>
          <g class="station" style="animation-delay:6s"><rect x="648" y="72" width="100" height="52" rx="10" fill="#16233f" stroke="#22d3ee" stroke-width="1.6"/><text x="698" y="94" fill="#dbe4f5" font-size="13" text-anchor="middle">🎲 采样</text><text x="698" y="112" fill="#8ea0c2" font-size="10" text-anchor="middle">⑥⑦</text></g>
          <g class="station" style="animation-delay:7.2s"><rect x="768" y="72" width="100" height="52" rx="10" fill="#16233f" stroke="#4f8cff" stroke-width="1.6"/><text x="818" y="94" fill="#dbe4f5" font-size="13" text-anchor="middle">🚀 验证接受</text><text x="818" y="112" fill="#8ea0c2" font-size="10" text-anchor="middle">③</text></g>
          <g class="station" style="animation-delay:8.4s"><rect x="888" y="72" width="60" height="52" rx="10" fill="#16233f" stroke="#34d399" stroke-width="1.6"/><text x="918" y="94" fill="#dbe4f5" font-size="13" text-anchor="middle">📤</text><text x="918" y="112" fill="#8ea0c2" font-size="10" text-anchor="middle">⑤</text></g>
        </g>
        <circle r="8" fill="#fbbf24" style="filter:drop-shadow(0 0 6px rgba(251,191,36,.8))">
          <animate attributeName="cx" values="78;918" dur="9.6s" repeatCount="indefinite"/>
          <animate attributeName="cy" values="105;105" dur="9.6s" repeatCount="indefinite"/>
        </circle>
        <circle r="5" fill="#22d3ee" opacity=".7">
          <animate attributeName="cx" values="78;918" dur="9.6s" begin=".6s" repeatCount="indefinite"/>
          <animate attributeName="cy" values="105;105" dur="9.6s" begin=".6s" repeatCount="indefinite"/>
        </circle>
        <text x="490" y="170" fill="#8ea0c2" font-size="12" text-anchor="middle">引擎步进循环:C++ Scheduler(CPU,gloo+SHM)→ 构建 input → forward(GPU)→ sample → 输出</text>
        <text x="490" y="192" fill="#5a6b92" font-size="11" text-anchor="middle">黄点 = 请求下行 · 青点 = token 回流 · 站点呼吸 = 当前处理阶段 · ZOS:step N 前向与 step N+1 调度重叠</text>
      </svg>
      <div class="cap">图 1-1 · 请求生命周期全景:各站点对应系列文档编号</div>
    </div>
  </section>

  <!-- ============ 2 引擎运行时 ============ -->
  <section>
    <h2 class="sec"><span class="num">2</span>引擎运行时三特性</h2>
    <p class="lede">优化内核、零开销调度与 SWA 有界重放,是 DeepInfer 一切性能故事的地基。</p>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🔥</span>① 优化内核与模型/采样运行时</h3>
        <div class="mini"><svg viewBox="0 0 320 86" xmlns="http://www.w3.org/2000/svg">
          <g>
            <rect x="16" y="14" width="26" height="20" rx="4" fill="#22d3ee" opacity=".25" style="animation:fw-tilelit 1.8s infinite"/>
            <rect x="46" y="14" width="26" height="20" rx="4" fill="#22d3ee" opacity=".25" style="animation:fw-tilelit 1.8s .3s infinite"/>
            <rect x="76" y="14" width="26" height="20" rx="4" fill="#4f8cff" opacity=".3" style="animation:fw-tilelit 1.8s .6s infinite"/>
            <rect x="106" y="14" width="26" height="20" rx="4" fill="#4f8cff" opacity=".3" style="animation:fw-tilelit 1.8s .9s infinite"/>
            <rect x="16" y="40" width="26" height="20" rx="4" fill="#4f8cff" opacity=".3" style="animation:fw-tilelit 1.8s 1.2s infinite"/>
            <rect x="46" y="40" width="26" height="20" rx="4" fill="#a78bfa" opacity=".3" style="animation:fw-tilelit 1.8s 1.5s infinite"/>
            <rect x="76" y="40" width="26" height="20" rx="4" fill="#a78bfa" opacity=".3" style="animation:fw-tilelit 1.8s .9s infinite"/>
            <rect x="106" y="40" width="26" height="20" rx="4" fill="#a78bfa" opacity=".3" style="animation:fw-tilelit 1.8s .3s infinite"/>
          </g>
          <text x="70" y="76" fill="#8ea0c2" font-size="10" text-anchor="middle">FP8 GEMM tiles</text>
          <line x1="150" y1="12" x2="150" y2="74" stroke="#263352"/>
          <rect x="170" y="24" width="120" height="12" rx="6" fill="#0d1424" stroke="#263352"/>
          <rect x="170" y="24" width="120" height="12" rx="6" fill="#34d399" opacity=".85" style="animation:fw-growbar 2.2s ease-in-out infinite alternate"/>
          <text x="230" y="56" fill="#8ea0c2" font-size="10" text-anchor="middle">SM 配额:计算 vs 通信</text>
        </svg></div>
        <p class="oneline">FlashMLA / DeepGEMM / DeepEP / DeepSelect 四大内核 + 28 个 TileLang 自研算子,FP8 双数据面把"算得快"做到极致。</p>
        <p>DeepInfer 把生产内核直接 vendor 进仓库:FlashMLA 负责 MLA/稀疏注意力,DeepGEMM 提供 FP8 分组 GEMM 与 SymmBuffer 对称内存,DeepEP-V2 承担 MoE/CP/Engram 通信,DeepSelect 加速采样;另有 store_kv_cache、schedule_mtp_varlen 等 TileLang 算子按平台分 cuda/asc 两套。通信内核与计算内核按 SM 配额共存,JIT 产物落盘缓存。</p>
        <ul class="feat">
          <li>双数据面 FP8:数值面与 scale factor 面分离流动;GPU int32 / NPU int16 SF</li>
          <li>SM 三分:32 CTA 给 NCCL、DeepEP 独立预算、其余给计算内核</li>
          <li>昇腾全套 vendor 变体:DeepEP-Ascend / DeepGEMM-Ascend + npu_ops 垫片</li>
        </ul>
        <div class="paths"><span class="filepath">deepinfer/model_executor/layers/tilelang_ops/</span><span class="filepath">layers/attention_backend.py</span><span class="filepath">vendor/</span></div>
        <a class="more" href="/docs/inference-engines/deepinfer/01-kernels/">深度解析 →</a>
      </div>

      <div class="card reveal d1">
        <h3><span class="ico">⚡</span>⑤ 异步调度:零开销批调度器(ZOS)</h3>
        <div class="mini"><svg viewBox="0 0 320 86" xmlns="http://www.w3.org/2000/svg">
          <text x="16" y="24" fill="#8ea0c2" font-size="10">CPU 调度</text>
          <text x="16" y="62" fill="#8ea0c2" font-size="10">GPU 计算</text>
          <rect x="90" y="12" width="46" height="14" rx="4" fill="#4f8cff" opacity=".9"><animate attributeName="x" values="90;250" dur="3.2s" repeatCount="indefinite"/></rect>
          <rect x="90" y="50" width="46" height="14" rx="4" fill="#34d399" opacity=".9"><animate attributeName="x" values="90;250" dur="3.2s" begin="0.9s" repeatCount="indefinite"/></rect>
          <rect x="160" y="12" width="46" height="14" rx="4" fill="#4f8cff" opacity=".55"><animate attributeName="x" values="160;300" dur="3.2s" begin="1.6s" repeatCount="indefinite"/></rect>
          <line x1="90" y1="32" x2="300" y2="32" stroke="#263352"/>
          <line x1="90" y1="70" x2="300" y2="70" stroke="#263352"/>
          <text x="195" y="84" fill="#8ea0c2" font-size="10" text-anchor="middle">step N 计算时,step N+1 已在调度</text>
        </svg></div>
        <p class="oneline">调度器通信全走 gloo+SHM 的 CPU 控制面,GPU 前向只等一个上一步的事件——decode 步 CPU 开销近零。</p>
        <p>driver 进程内联 Worker 直接函数调用,CP 其余 rank 为守护子进程;C++ Scheduler 用 1MiB×10 的 SHM 环形队列下发调度对象,CPU 控制面完全不进 device stream。每步 launch 即返回,<code>seqlens_q</code> 修正延迟一步,六类 CUDA Event 精细同步;CUDA Graph 直写共享 device 缓冲免拷贝。</p>
        <ul class="feat">
          <li><code>worker.py:182</code> 的 ZOS 分支决定 decode 步是否存 <code>prev_step_state</code></li>
          <li>GPU 侧唯一等待是上一步 <code>sample_end_evt</code>,通常已被 CPU 工作自然吸收</li>
          <li>README 标注默认启用;<code>DEEPINFER_ZERO_OVERHEAD_SCHEDULING</code> 可关</li>
        </ul>
        <div class="paths"><span class="filepath">engine/llm_engine.py</span><span class="filepath">worker/worker.py</span><span class="filepath">csrc/engine/scheduler.hpp</span><span class="filepath">distributed/shm_broadcast.py</span></div>
        <a class="more" href="/docs/inference-engines/deepinfer/05-async-scheduling/">深度解析 →</a>
      </div>

      <div class="card reveal">
        <h3><span class="ico">🪟</span>④ Decoder SWA 有界重放(YOCO Prefill 截断)</h3>
        <div class="mini"><svg viewBox="0 0 320 86" xmlns="http://www.w3.org/2000/svg">
          <rect x="22" y="24" width="200" height="26" rx="6" fill="#16233f" stroke="#263352"/>
          <rect x="22" y="24" width="130" height="26" rx="6" fill="#16233f" stroke="#263352" opacity=".55"/>
          <line x1="152" y1="18" x2="152" y2="58" stroke="#f87171" stroke-width="2" stroke-dasharray="4 4"/>
          <rect x="156" y="24" width="66" height="26" rx="6" fill="#22d3ee" opacity=".28" style="animation:fw-winmove 2.8s ease-in-out infinite"/>
          <text x="76" y="42" fill="#5a6b92" font-size="10" text-anchor="middle">clip(丢弃)</text>
          <text x="189" y="42" fill="#cfe0ff" font-size="10" text-anchor="middle">KEEP=140</text>
          <rect x="245" y="24" width="50" height="26" rx="6" fill="#16233f" stroke="#a78bfa" stroke-width="1.3"/>
          <text x="270" y="42" fill="#cfe0ff" font-size="9.5" text-anchor="middle">重放</text>
          <line x1="222" y1="37" x2="245" y2="37" stroke="#a78bfa" stroke-width="2"/>
          <text x="160" y="72" fill="#8ea0c2" font-size="10" text-anchor="middle">只重放尾部:SWA 窗口 + 回退余量</text>
        </svg></div>
        <p class="oneline">YOCO 解码器 prefill 只重放"SWA 窗口 + 回退余量"的有界尾部,V4.1 一行配置 KEEP_TOKENS=140。</p>
        <p><code>clip_prefix</code> 锚定序列末端的矩形存活区,可见域 = 滑窗 ∩ 矩形 ∩ <code>swa_valid_start</code> 三下界取 max;压缩 main/index KV 由 <code>consumer_full_hidden</code> 全量补写,SWA 走 ring buffer 先 load 后 store。consumer SWA 落在 dropped 区不落盘,重放是它唯一的重建路径。</p>
        <ul class="feat">
          <li>三种模式 off/mask/compact;推荐 <code>compact</code> + <code>DEEPINFER_YOCO_PREFILL_KEEP_TOKENS=140</code></li>
          <li>约束 KEEP ≥ window(128) + backtracking(6),Python/C++/等价性测试四处强制</li>
          <li>ring 长度 = W+B,与 DSpark 回退共享同一物理预留;yoco_equiv 双层防线</li>
        </ul>
        <div class="paths"><span class="filepath">v4_modules/yoco.py</span><span class="filepath">csrc/engine/input_metadata/prepare_tensor_input_v4.cpp</span><span class="filepath">deepinfer/environ.py</span></div>
        <a class="more" href="/docs/inference-engines/deepinfer/04-swa-replay/">深度解析 →</a>
      </div>
    </div>
  </section>

  <!-- ============ 3 并行与解码加速 ============ -->
  <section>
    <h2 class="sec"><span class="num">3</span>并行与解码加速二特性</h2>
    <p class="lede">体系结构(并行策略)与算法(DSpark 投机解码)两个维度同时压榨吞吐。</p>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🔀</span>② 并行策略:Attention DP / balanced CP + MoE EP + EPLB</h3>
        <div class="mini"><svg viewBox="0 0 320 86" xmlns="http://www.w3.org/2000/svg">
          <rect x="24" y="18" width="52" height="34" rx="7" fill="#16233f" stroke="#4f8cff" stroke-width="1.4"/>
          <rect x="96" y="18" width="52" height="34" rx="7" fill="#16233f" stroke="#a78bfa" stroke-width="1.4"/>
          <rect x="168" y="18" width="52" height="34" rx="7" fill="#16233f" stroke="#22d3ee" stroke-width="1.4"/>
          <rect x="240" y="18" width="52" height="34" rx="7" fill="#16233f" stroke="#34d399" stroke-width="1.4"/>
          <text x="50" y="39" fill="#dbe4f5" font-size="10" text-anchor="middle">DP0</text>
          <text x="122" y="39" fill="#dbe4f5" font-size="10" text-anchor="middle">DP1</text>
          <text x="194" y="39" fill="#dbe4f5" font-size="10" text-anchor="middle">DP2</text>
          <text x="266" y="39" fill="#dbe4f5" font-size="10" text-anchor="middle">DP3</text>
          <line x1="76" y1="35" x2="96" y2="35" stroke="#a78bfa" stroke-width="2" class="flowline"/>
          <line x1="148" y1="35" x2="168" y2="35" stroke="#22d3ee" stroke-width="2" class="flowline"/>
          <line x1="220" y1="35" x2="240" y2="35" stroke="#34d399" stroke-width="2" class="flowline"/>
          <circle r="4" fill="#fbbf24"><animateMotion dur="2.4s" repeatCount="indefinite" path="M76 35 L96 35 L148 35 L168 35 L220 35 L240 35"/></circle>
          <text x="160" y="72" fill="#8ea0c2" font-size="10" text-anchor="middle">token 经 DeepEP 路由到专家所在卡</text>
        </svg></div>
        <p class="oneline">注意力 DP 复制 + mirror-CP 均衡,MoE 交给 DeepEP dispatch/combine,EPLB 按零成本统计动态迁移专家权重。</p>
        <p>9 张 NCCL/HCCL 设备组(dp/cp/ep/ep_in_dp/enp/world/local)+ 3 张 gloo CPU 组。CP 用块对 <code>(r, 2cp-1-r)</code> 的 zigzag mirror,CPManager 会话式 all-gather 与 Q 投影重叠;MoE dispatch 时 kernel 通过 <code>cumulative_local_expert_recv_stats</code> 顺带累加专家计数——EPLB 统计零成本,两段贪心生成冗余副本布局后,P2P 迁移权重、下一 forward 即生效。</p>
        <ul class="feat">
          <li>dispatch/combine 事件重叠:<code>allocate_on_comm_stream</code> + <code>current_stream_wait</code></li>
          <li>NVLink 域内 mega-MoE 走 SymmBuffer 对称内存零拷贝 fast path</li>
          <li><code>DEEPINFER_EXPERT_COUNT_WINDOW_SIZE=100</code> 统计窗口;两段贪心(冗余副本 + 多步联合排布)</li>
        </ul>
        <div class="paths"><span class="filepath">parallel_utils/parallel_state.py</span><span class="filepath">userbuffer.py</span><span class="filepath">v4_modules/mlp.py</span><span class="filepath">eplb/</span></div>
        <a class="more" href="/docs/inference-engines/deepinfer/02-parallelism/">深度解析 →</a>
      </div>

      <div class="card reveal d1">
        <h3><span class="ico">🚀</span>③ DSpark 投机解码与置信度调度验证</h3>
        <div class="mini"><svg viewBox="0 0 320 86" xmlns="http://www.w3.org/2000/svg">
          <rect x="18" y="30" width="18" height="18" rx="4" fill="#4f8cff"/>
          <rect x="52" y="30" width="18" height="18" rx="4" fill="#22d3ee" opacity=".85"><animate attributeName="x" values="52;130;130;52" dur="3s" repeatCount="indefinite"/></rect>
          <rect x="52" y="30" width="18" height="18" rx="4" fill="#a78bfa" opacity=".85"><animate attributeName="x" values="52;96;96;52" dur="3s" repeatCount="indefinite"/></rect>
          <rect x="52" y="30" width="18" height="18" rx="4" fill="#34d399" opacity=".85"><animate attributeName="x" values="52;70;70;52" dur="3s" repeatCount="indefinite"/></rect>
          <text x="46" y="68" fill="#8ea0c2" font-size="10">target</text>
          <text x="128" y="68" fill="#8ea0c2" font-size="10">drafts</text>
          <rect x="170" y="22" width="130" height="16" rx="8" fill="#0d1424" stroke="#263352"/>
          <rect x="170" y="22" width="130" height="16" rx="8" fill="#fbbf24" opacity=".75" style="animation:fw-growbar 2.6s ease-in-out infinite alternate"/>
          <text x="235" y="56" fill="#8ea0c2" font-size="10" text-anchor="middle">置信度预算 total_q</text>
        </svg></div>
        <p class="oneline">MTP draft 一次起草多 token 并行验证,ConfidenceHead 置信度参与吞吐搜索、按预算发放——解码加速的核心。</p>
        <p>DFlash/NextN draft 模型共享主图 KV(<code>update_main_cache</code> 随主图执行),Markov 头 <code>sample_drafts</code> 逐步起草;验证用 <code>fused_sample</code> 做残差拒绝采样(前缀接受 + 拒绝位重采样),RNG 逐位置锚定。<code>MTPVarlen::schedule</code> 按累乘接受率与预算 <code>total_q</code> 搜索各请求验证长度,ZOS 下 GPU 修正 kernel 与 CPU 参考严格位一致。</p>
        <ul class="feat">
          <li><code>DEEPINFER_ENABLE_MTP_VARLEN=1</code> 启用;<code>DEEPINFER_USE_NEXTN_DECODE=5</code> draft 上限</li>
          <li>回退:KV 乐观推进 + <code>commit_processed_tokens</code> 按实际接受数回填</li>
          <li>DFlash 整段捕获进 CUDA Graph,与主图共享 memory pool</li>
        </ul>
        <div class="paths"><span class="filepath">models/mtp/</span><span class="filepath">layers/mtp_info_pool.py</span><span class="filepath">worker/dflash_cuda_graph_runner.py</span><span class="filepath">layers/tilelang_ops/schedule_mtp_varlen.py</span></div>
        <a class="more" href="/docs/inference-engines/deepinfer/03-dspark/">深度解析 →</a>
      </div>
    </div>
  </section>

  <!-- ============ 4 生成质量与输出 ============ -->
  <section>
    <h2 class="sec"><span class="num">4</span>生成质量与输出二特性</h2>
    <p class="lede">确定性(批次不变 + 确定性采样)与约束生成(结构化输出),决定了"输出可不可控、可不可复现"。</p>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🎯</span>⑥ 批次不变性推理 + 确定性采样</h3>
        <div class="mini"><svg viewBox="0 0 320 86" xmlns="http://www.w3.org/2000/svg">
          <rect x="30" y="16" width="90" height="20" rx="6" fill="#16233f" stroke="#4f8cff" stroke-width="1.3"/>
          <text x="75" y="30" fill="#dbe4f5" font-size="10" text-anchor="middle">batch=[R]</text>
          <rect x="30" y="50" width="90" height="20" rx="6" fill="#16233f" stroke="#a78bfa" stroke-width="1.3"/>
          <text x="75" y="64" fill="#dbe4f5" font-size="10" text-anchor="middle">batch=[R,A,B]</text>
          <path d="M120 26 C 170 26 190 38 240 38" fill="none" stroke="#4f8cff" stroke-width="1.8" class="flowline"/>
          <path d="M120 60 C 170 60 190 48 240 48" fill="none" stroke="#a78bfa" stroke-width="1.8" class="flowline"/>
          <rect x="244" y="30" width="56" height="26" rx="7" fill="#0d1424" stroke="#34d399" stroke-width="1.5" class="pulse"/>
          <text x="272" y="47" fill="#34d399" font-size="11" text-anchor="middle">同结果</text>
          <text x="160" y="80" fill="#8ea0c2" font-size="10" text-anchor="middle">不同 batch 组合 → 位级一致输出</text>
        </svg></div>
        <p class="oneline">四层机制让输出与 batch 组成无关,叠加逐位置 RNG 锚定后"相同输入 → 相同输出"(NVIDIA only)。</p>
        <p>浮点归约顺序、MoE 多次归约、GEMM 分块调度都会让结果随 batch 组合漂移。DeepInfer 用确定性 GEMM/注意力算法、MoE combine 单次归约(<code>allow_multiple_reduction=False</code>)、sync guard 与固定 RNG 流四层合围;采样侧 <code>seq_seed</code> 经 SplitMix64 + 两级定点 CDF 反演,完全避开浮点比较。</p>
        <ul class="feat">
          <li>确定性配方:<code>BATCH_INVARIANT=1</code> + <code>MTP_VARLEN=0</code> + 固定 <code>seq_seed</code></li>
          <li>EPLB 组合语义:重排时保证"相同 batch 序列 ⇒ 相同结果"</li>
          <li>golden teacher forcing 端到端验证,剔除采样随机性专测不变性</li>
        </ul>
        <div class="paths"><span class="filepath">worker/runtime_config.py</span><span class="filepath">layers/sampler.py</span><span class="filepath">tilelang_ops/random_sampling.py</span><span class="filepath">deepinfer/utils.py</span></div>
        <a class="more" href="/docs/inference-engines/deepinfer/06-batch-invariant/">深度解析 →</a>
      </div>

      <div class="card reveal d1">
        <h3><span class="ico">🧩</span>⑦ 结构化输出(regex / JSON Schema / EBNF)</h3>
        <div class="mini"><svg viewBox="0 0 320 86" xmlns="http://www.w3.org/2000/svg">
          <rect x="20" y="28" width="80" height="30" rx="7" fill="#16233f" stroke="#fbbf24" stroke-width="1.4"/>
          <text x="60" y="47" fill="#fbbf24" font-size="11" text-anchor="middle" font-family="monospace">{"a":…}</text>
          <line x1="100" y1="43" x2="140" y2="43" stroke="#fbbf24" stroke-width="2"/>
          <rect x="145" y="28" width="70" height="30" rx="7" fill="#16233f" stroke="#22d3ee" stroke-width="1.4"/>
          <text x="180" y="47" fill="#22d3ee" font-size="10" text-anchor="middle">xgrammar</text>
          <text x="180" y="76" fill="#8ea0c2" font-size="9.5" text-anchor="middle">异步编译</text>
          <rect x="230" y="14" width="16" height="16" rx="4" fill="#34d399"><animate attributeName="opacity" values="1;.2;1" dur="1.4s" repeatCount="indefinite"/></rect>
          <rect x="250" y="14" width="16" height="16" rx="4" fill="#34d399"><animate attributeName="opacity" values="1;.2;1" dur="1.4s" begin=".35s" repeatCount="indefinite"/></rect>
          <rect x="270" y="14" width="16" height="16" rx="4" fill="#f87171" opacity=".3"/>
          <rect x="230" y="36" width="16" height="16" rx="4" fill="#34d399"><animate attributeName="opacity" values="1;.2;1" dur="1.4s" begin=".7s" repeatCount="indefinite"/></rect>
          <rect x="250" y="36" width="16" height="16" rx="4" fill="#34d399"><animate attributeName="opacity" values="1;.2;1" dur="1.4s" begin="1.05s" repeatCount="indefinite"/></rect>
          <rect x="270" y="36" width="16" height="16" rx="4" fill="#34d399"><animate attributeName="opacity" values="1;.2;1" dur="1.4s" begin="1.4s" repeatCount="indefinite"/></rect>
          <text x="258" y="72" fill="#8ea0c2" font-size="9.5" text-anchor="middle">每步 token 掩码</text>
        </svg></div>
        <p class="oneline">regex / JSON Schema / EBNF 经 xgrammar 异步编译成词表掩码,每步在采样前把非法 token 拦在门外。</p>
        <p><code>so_args</code> 声明约束后,编译在线程池异步进行(20s 超时 + 10GiB 缓存 + kill switch),matcher 每步产出位掩码,经侧流 H2D 双 event 定序送 TileLang 掩码采样内核;支持与 DSpark 叠加:接受后填 mask[0]、draft 试接受填 mask[k+1]、回退即回滚。</p>
        <ul class="feat">
          <li><code>trigger_token_ids</code>(KMP)与 <code>bound_token_id</code> 词表校验</li>
          <li>golden tokens 与约束冲突直接拒绝("upstream invariant broken")</li>
          <li>用法示例:<code>examples/_structured_output.py</code> 三个对抗性 prompt</li>
        </ul>
        <div class="paths"><span class="filepath">deepinfer/structure_output/</span><span class="filepath">engine/llm_engine.py</span><span class="filepath">examples/_structured_output.py</span></div>
        <a class="more" href="/docs/inference-engines/deepinfer/07-structured-output/">深度解析 →</a>
      </div>
    </div>
  </section>

  <!-- ============ 5 通信专题 ============ -->
  <section>
    <h2 class="sec"><span class="num">5</span>分布式通信专题(⑧ – ⑩)</h2>
    <p class="lede">围绕"跨卡通信"这一推理引擎的命脉,从代码现状、演进历史与行为全景三个视角交叉分析。</p>
    <table class="tbl reveal">
      <tr><th style="width:170px">篇目</th><th>核心结论速览</th><th style="width:200px">代表动画</th></tr>
      <tr>
        <td><a href="/docs/inference-engines/deepinfer/08-nccl-usage/"><b>⑧ NCCL 使用场景全景</b></a></td>
        <td>从代码穷举 20+ 调用点:七张设备组 eager 预热、CP 张量/元数据双通道广播、DP 终止检测(ReduceOp.MAX)、EPLB 统计与 P2P 重排、图内 broadcast、decode perf 曲线;<code>ProcessGroupNCCL.Options</code> 限制 32 CTA;<code>nccl_memory</code> 按步采样 communicator 显存;NCCL 原生 env(NVLS/PXN/CUMEM/GIN)在 runtime_config.py 统一设置。</td>
        <td>SM 三分共存 / 调用点矩阵 / 通信路径决策树</td>
      </tr>
      <tr>
        <td><a href="/docs/inference-engines/deepinfer/09-nccl-pr-history/"><b>⑨ NCCL 相关 PR 合入历史全景图</b></a></td>
        <td>基于 GitHub API 拉取 <b style="color:#34d399">224 个 PR</b>,识别出 42 个通信相关(34 位贡献者):唯二合入 #157(DeepEP bump)与 #218(环境变量严格校验);NCCL GIN 硬依赖是社区最强痛点——开源 5 天内出现 3 条 Engram 替代路径(#99 NVLink / #246 LocalEngram / #200 UVA)+ 1 条 QP 调优(#248);ROCm 拆分栈(#201~#206)尝试整体替换通信库。</td>
        <td>时间线扫描 / 特性-问题象限气泡 / 每日柱状图生长</td>
      </tr>
      <tr>
        <td><a href="/docs/inference-engines/deepinfer/10-cross-card-comm/"><b>⑩ 跨卡通信行为与底层通信库</b></a></td>
        <td>穷举 22 类跨卡通信行为并映射到底层库:DeepEP-V2 独占 MoE dispatch/combine、Engram 单边 RDMA 读、CP BucketBuffer 会话式聚合;NCCL/HCCL 退居控制面与轻量数据面;EPLB 跨机走 <code>batch_isend_irecv</code>、单机走 symm_mem IPC;训练式 all-reduce 在推理中被"权重复制 + token 路由"彻底取代。</td>
        <td>四层通信栈 / token 路由分域动画 / NVLink-RDMA 域判定</td>
      </tr>
    </table>
  </section>

  <!-- ============ 6 协作矩阵 ============ -->
  <section>
    <h2 class="sec"><span class="num">6</span>特性 × 请求阶段协作矩阵</h2>
    <p class="lede">一张表看清:在一次请求的生命周期里,各特性分别在哪一站发挥作用(<span class="full">●</span> 主要参与,<span class="half">◐</span> 辅助参与)。</p>
    <table class="tbl reveal">
      <tr><th>特性</th><th>接入加载</th><th>预处理</th><th>调度组批</th><th>KV/重放</th><th>前向执行</th><th>采样/验证</th><th>输出</th></tr>
      <tr><td>① 优化内核</td><td><span class="half">◐</span> JIT 预热</td><td></td><td></td><td><span class="half">◐</span> KV 写入算子</td><td><span class="full">●</span> GEMM/MLA/Engram 内核</td><td><span class="half">◐</span> DeepSelect 采样</td><td></td></tr>
      <tr><td>② 并行策略</td><td><span class="half">◐</span> EPLB 权重迁移</td><td></td><td><span class="half">◐</span> DP 秩协调</td><td></td><td><span class="full">●</span> DP/CP/EP + dispatch/combine</td><td></td><td></td></tr>
      <tr><td>③ DSpark</td><td></td><td></td><td><span class="half">◐</span> 置信度预算</td><td><span class="half">◐</span> 回退记账</td><td><span class="full">●</span> draft + 并行验证</td><td><span class="full">●</span> 残差拒绝采样</td><td></td></tr>
      <tr><td>④ SWA 重放</td><td></td><td><span class="full">●</span> prefill 截断</td><td><span class="half">◐</span> Flops 估算</td><td><span class="full">●</span> 有界重放 / ring</td><td><span class="half">◐</span> 压缩 KV 补写</td><td></td><td></td></tr>
      <tr><td>⑤ 异步调度 ZOS</td><td><span class="full">●</span> driver-worker 架构</td><td></td><td><span class="full">●</span> C++ Scheduler / 一步延迟</td><td></td><td><span class="half">◐</span> CUDA Graph 直写输入</td><td></td><td><span class="full">●</span> 异步后处理</td></tr>
      <tr><td>⑥ 批次不变+确定性</td><td></td><td></td><td><span class="half">◐</span> 固定宽度验证</td><td></td><td><span class="full">●</span> 确定性算法/单次归约</td><td><span class="full">●</span> seq_seed / 定点 CDF</td><td></td></tr>
      <tr><td>⑦ 结构化输出</td><td></td><td><span class="full">●</span> 异步编译</td><td></td><td></td><td></td><td><span class="full">●</span> 词表位掩码</td><td><span class="full">●</span> fullmatch/EOS 校验</td></tr>
      <tr><td>⑧ NCCL 使用</td><td><span class="full">●</span> 设备组 eager 预热</td><td></td><td><span class="half">◐</span> 引擎同步(MAX)</td><td></td><td><span class="half">◐</span> 图内 broadcast</td><td><span class="half">◐</span> 图内元数据广播</td><td></td></tr>
      <tr><td>⑩ 跨卡通信栈</td><td><span class="half">◐</span> SHM 权重分发</td><td></td><td><span class="half">◐</span> gloo 控制面</td><td><span class="half">◐</span> Engram RDMA 读</td><td><span class="full">●</span> DeepEP dispatch/combine + CP 聚合</td><td></td><td></td></tr>
    </table>
    <div class="note">注:⑨ <b>NCCL 相关 PR 合入历史</b>为演进视角专题,不参与单次请求生命周期,故不在矩阵中;它解释的是上表各行为"如何长成今天这样"。</div>
  </section>

  <div class="pgnav">
    <span>DeepInfer 深度解析系列 · 第 00 篇 导读 · 由 ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/deepinfer/">← 返回总览</a> · <a href="/docs/inference-engines/deepinfer/01-kernels/">下一篇:① 优化内核与运行时 →</a></span>
  </div>
<script>
// 滚动显现动画
var io=new IntersectionObserver(function(es){es.forEach(function(e){if(e.isIntersecting){e.target.classList.add('on');io.unobserve(e.target)}})},{threshold:.12});
document.querySelectorAll('.reveal').forEach(function(el){io.observe(el)});
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>优化内核与运行时</title><link>https://hccl.club/docs/inference-engines/deepinfer/01-kernels/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/01-kernels/</guid><description><![CDATA[<div class="fwdoc">
<style>
.fwdoc{--bg:#0b1020; --bg2:#0f1729; --panel:#141d33; --panel2:#1a2440;
  --border:#263352; --text:#dbe4f5; --muted:#8ea0c2;
  --accent:#4f8cff; --accent2:#22d3ee; --good:#34d399; --warn:#fbbf24; --bad:#f87171; --purple:#a78bfa;
  --code-bg:#0d1424; --radius:14px;
  --serif:"Noto Serif SC","Songti SC",serif;}
.fwdoc *{box-sizing:border-box;margin:0;padding:0}
.fwdoc{background:linear-gradient(160deg,var(--bg) 0%,var(--bg2) 60%,#0a0f1e 100%);color:var(--text);
  font-family:"PingFang SC","Microsoft YaHei","Segoe UI",system-ui,sans-serif;line-height:1.75;}
.fwdoc{flex:1;min-width:0;padding:36px 48px 80px}
@media(max-width:960px){.fwdoc{padding:24px 18px 60px}}
.fwdoc .hero{position:relative;border-radius:var(--radius);overflow:hidden;padding:46px 44px;margin-bottom:34px;
  background:radial-gradient(1200px 400px at 15% -20%,rgba(79,140,255,.28),transparent 60%),
             radial-gradient(900px 380px at 95% 0%,rgba(167,139,250,.20),transparent 55%),
             linear-gradient(135deg,#16213e,#101a30);border:1px solid var(--border)}
.fwdoc .hero .crumb{font-size:12px;color:var(--accent2);letter-spacing:1px;margin-bottom:12px}
.fwdoc .hero h1{font-size:34px;color:#fff;font-weight:800;letter-spacing:.5px;margin-bottom:10px}
.fwdoc .hero p.desc{color:var(--muted);max-width:820px;font-size:15px}
.fwdoc .hero .tags{margin-top:18px;display:flex;gap:10px;flex-wrap:wrap}
.fwdoc .hero .tag{font-size:12px;padding:4px 14px;border-radius:999px;border:1px solid var(--border);
  background:rgba(79,140,255,.10);color:var(--accent2)}
.fwdoc .tag.good{border-color:rgba(52,211,153,.4);color:var(--good);background:rgba(52,211,153,.08)}
.fwdoc .tag.warn{border-color:rgba(251,191,36,.4);color:var(--warn);background:rgba(251,191,36,.08)}
.fwdoc section{margin-bottom:44px;scroll-margin-top:20px}
.fwdoc h2.sec{display:flex;align-items:center;gap:12px;font-size:23px;color:#fff;margin-bottom:6px;padding-bottom:10px;border-bottom:1px solid var(--border)}
.fwdoc h2.sec .num{display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:10px;flex-shrink:0;
  background:linear-gradient(135deg,var(--accent),var(--purple));color:#fff;font-size:15px;font-weight:800}
.fwdoc .lede{color:var(--muted);font-size:14px;margin-bottom:20px}
.fwdoc .grid{display:grid;gap:18px}
.fwdoc .grid.c2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}
.fwdoc .grid.c3{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}
.fwdoc .card{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:var(--radius);padding:22px 24px;transition:transform .3s,border-color .3s,box-shadow .3s}
.fwdoc .card:hover{transform:translateY(-3px);border-color:rgba(79,140,255,.55);box-shadow:0 12px 34px -14px rgba(79,140,255,.35)}
.fwdoc .card h3{font-size:16.5px;color:#fff;margin-bottom:8px;display:flex;align-items:center;gap:9px}
.fwdoc .card h3 .ico{width:26px;height:26px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;
  background:rgba(79,140,255,.16);font-size:14px;flex-shrink:0}
.fwdoc .card p{font-size:13.5px;color:var(--muted)}
.fwdoc .card p code,.fwdoc .inline-code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1.5px 7px;border-radius:6px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px}
.fwdoc ul.feat{list-style:none}
.fwdoc ul.feat li{padding:9px 0 9px 30px;position:relative;font-size:14px;color:var(--text);border-bottom:1px dashed rgba(38,51,82,.6)}
.fwdoc ul.feat li:last-child{border-bottom:none}
.fwdoc ul.feat li::before{content:"▸";position:absolute;left:8px;color:var(--accent);font-weight:700;animation:fw-blink 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
@keyframes fw-blink{0%,100%{opacity:.35}50%{opacity:1}}
.fwdoc pre.code{background:var(--code-bg);border:1px solid var(--border);border-radius:12px;padding:18px 20px;
  overflow-x:auto;font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px;line-height:1.65;margin:14px 0;position:relative}
.fwdoc pre.code::before{content:"● ● ●";display:block;color:#3a4a70;font-size:10px;letter-spacing:3px;margin-bottom:10px}
.fwdoc pre.code .k{color:#c792ea}
.fwdoc pre.code .s{color:#89ddff}
.fwdoc pre.code .c{color:#5d7294;font-style:italic}
.fwdoc pre.code .f{color:#82aaff}
.fwdoc pre.code .n{color:#f78c6c}
.fwdoc pre.code .h{color:#ffcb6b}
.fwdoc .filepath{font-family:"JetBrains Mono",Consolas,monospace;font-size:11.5px;color:var(--accent2);
  background:rgba(34,211,238,.08);border:1px solid rgba(34,211,238,.25);border-radius:6px;padding:2px 10px;display:inline-block;margin-bottom:4px}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border)}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px}
.fwdoc table.tbl td{padding:10px 14px;border-top:1px solid var(--border);color:var(--text);vertical-align:top}
.fwdoc table.tbl tr{transition:background .2s}
.fwdoc table.tbl tr:nth-child(even) td{background:rgba(20,29,51,.5)}
.fwdoc table.tbl tr:hover td{background:rgba(79,140,255,.10)}
.fwdoc table.tbl td code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;font-family:Consolas,monospace;font-size:12px}
.fwdoc .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px}
.fwdoc .badge.merged{background:rgba(52,211,153,.15);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.open{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.closed{background:rgba(248,113,113,.13);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.nccl{background:rgba(251,191,36,.12);color:var(--warn);border:1px solid rgba(251,191,36,.4)}
.fwdoc .badge.hccl{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .badge.deepep{background:rgba(34,211,238,.12);color:var(--accent2);border:1px solid rgba(34,211,238,.4)}
.fwdoc .reveal{opacity:0;transform:translateY(26px);transition:opacity .7s cubic-bezier(.2,.7,.3,1),transform .7s cubic-bezier(.2,.7,.3,1)}
.fwdoc .reveal.on{opacity:1;transform:none}
.fwdoc .reveal.d1{transition-delay:.12s}
.fwdoc .reveal.d2{transition-delay:.24s}
.fwdoc .reveal.d3{transition-delay:.36s}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:20px;margin:18px 0;position:relative;overflow:hidden}
.fwdoc .figure .cap{text-align:center;font-size:12.5px;color:var(--muted);margin-top:10px}
.fwdoc .figure svg{width:100%;height:auto;display:block}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-flow 1.2s linear infinite}
@keyframes fw-flow{to{stroke-dashoffset:-14}}
.fwdoc .pulse{animation:fw-pulse 2s ease-in-out infinite;transform-origin:center}
@keyframes fw-pulse{0%,100%{opacity:.45;transform:scale(1)}50%{opacity:1;transform:scale(1.06)}}
.fwdoc .node-gpu{fill:#16233f;stroke:#4f8cff;stroke-width:1.6;rx:10}
.fwdoc .node-gpu-title{fill:#dbe4f5;font-size:13px;font-weight:700}
.fwdoc .token-dot{fill:#22d3ee}
.fwdoc .barrow{filter:drop-shadow(0 0 6px rgba(34,211,238,.7))}
.fwdoc .attn-tile{fill:#1b2a4a;stroke:#4f8cff;stroke-width:1.2;animation:fw-tileOn 3.6s ease-in-out infinite}
@keyframes fw-tileOn{0%,100%{fill-opacity:.30}50%{fill-opacity:1}}
.fwdoc .kvsel{fill:rgba(52,211,153,.22);stroke:#34d399;stroke-width:1.4;animation:fw-pulse 2.2s ease-in-out infinite}
.fwdoc .gemm-tile{fill:#16233f;stroke:#22d3ee;stroke-width:1.2;animation:fw-tileOn 2.8s ease-in-out infinite}
.fwdoc .sm{fill:#16233f;stroke:#33507e;stroke-width:1}
.fwdoc .sm-plain{animation:fw-smBreath 4.5s ease-in-out infinite}
@keyframes fw-smBreath{0%,100%{fill:#16233f}40%,70%{fill:#12405f}}
.fwdoc .sm-comm{animation:fw-commSwap 4.5s ease-in-out infinite}
@keyframes fw-commSwap{0%,26%{fill:#4f8cff;fill-opacity:.85}38%,72%{fill:#a78bfa;fill-opacity:.95}84%,100%{fill:#4f8cff;fill-opacity:.85}}
.fwdoc .phase-tag{font-size:11px;fill:#8ea0c2;font-family:"JetBrains Mono",Consolas,monospace;animation:fw-pulse 4.5s ease-in-out infinite}
.fwdoc .figure .pulse,.fwdoc .kvsel,.fwdoc .phase-tag{transform-box:fill-box;transform-origin:center}
.fwdoc .figlabel{fill:#8ea0c2;font-size:11.5px;font-family:"JetBrains Mono",Consolas,monospace}
.fwdoc .figtitle{fill:#dbe4f5;font-size:13px;font-weight:700}
.fwdoc .timeline{position:relative;padding-left:34px}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .tl-item{position:relative;margin-bottom:20px}
.fwdoc .tl-item::before{content:"";position:absolute;left:-30px;top:7px;width:12px;height:12px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.18);animation:fw-pulse 2.4s infinite}
.fwdoc .tl-item .tl-date{font-size:11.5px;color:var(--accent2);letter-spacing:.5px}
.fwdoc .tl-item .tl-body{font-size:13.5px;color:var(--text);margin-top:3px}
.fwdoc .note{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13px;color:var(--text);margin:16px 0}
.fwdoc .note.warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .note.good{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .note b{color:#fff}
.fwdoc .pgnav{margin-top:60px;padding-top:20px;border-top:1px solid var(--border);color:#5a6b92;font-size:12px;
  display:flex;justify-content:space-between;flex-wrap:wrap;gap:10px}
.fwdoc .pgnav a{color:var(--accent2);text-decoration:none}
/* ===== 导入面板附加样式 ===== */
.fwdoc{border-radius:14px;margin:18px 0}
.fwdoc table.tbl{display:block;overflow-x:auto;max-width:100%}
@media (prefers-reduced-motion:reduce){
.fwdoc *,.fwdoc *::before,.fwdoc *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
.fwdoc .reveal{opacity:1!important;transform:none!important}
}

</style>

<!-- ================= 1. 内核生态总览 ================= -->
  <section id="s1">
    <h2 class="sec"><span class="num">1</span>内核生态总览:三层体系</h2>
    <p class="lede">DeepInfer 不直接手写 CUDA,而是把高性能内核拆成三层:vendor 子模块提供「重炮」算子,tile_kernels 提供量化/MoE/Engram 等通用 TileLang 内核,自研 tilelang_ops 填补模型专属的调度、采样与数据搬运空白。</p>

    <div class="grid c3">
      <div class="card reveal">
        <h3><span class="ico">🧩</span>第一层:vendor 四大件</h3>
        <p>以 git submodule 固定在 <code>vendor/</code> 下:<code>FlashMLA</code>(MLA 注意力)、<code>DeepGEMM</code>(FP8/FP4 GEMM)、<code>DeepEP</code>(V2 通信)、<code>DeepSelect</code>(top-k),昇腾侧对应 <code>DeepEP-Ascend</code> / <code>DeepGEMM-Ascend</code>。由 <code>scripts/build_vendor.sh</code> 统一按平台构建并以同名 Python 包(<code>flash_mla</code> / <code>deep_gemm</code> / <code>deep_ep</code> / <code>deep_select</code>)安装。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">⚡</span>第二层:tile_kernels 库</h3>
        <p>上游 TileLang 内核库,提供 <code>quant.per_token_cast</code>(FP8/FP4 逐 token 量化)、<code>quant.swiglu_forward_and_per_token_cast</code>(激活+量化融合)、<code>moe.moe_topk_gate</code>(MoE 路由门)、<code>engram.fused_weight / engram_gate_fwd</code>(n-gram 门控)等,并承载全局 <code>set_num_sms</code> / <code>set_pdl</code> / <code>use_deterministic_algorithms</code> 开关。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🛠</span>第三层:自研 tilelang_ops</h3>
        <p><code>deepinfer/model_executor/layers/tilelang_ops/</code> 下 30+ 个 <code>*_tl</code> 算子工厂,按 <code>cuda/</code> 与 <code>asc/</code> 双后端组织,由 <code>ops.py</code> 在运行时按平台动态重导出——模型代码只调 <code>ops.xxx_tl</code>,平台选择只发生在一处。</p>
      </div>
    </div>

    <div class="note reveal">
      <b>构建管线:</b><span class="filepath">scripts/build_vendor.sh:14-21</span> 按 <code>DEEPINFER_ACCELERATOR</code> 选择构建目标 —— nvidia 平台构建 <code>DeepSelect FlashMLA DeepEP DeepGEMM</code>,ascend 平台换成 <code>DeepEP-Ascend DeepGEMM-Ascend</code>,但安装后的 Python 包名完全一致;DeepSelect / FlashMLA 通过 <code>DEEP_SELECT_BUILD_TARGET_PLATFORM</code> / <code>FLASH_MLA_BUILD_TARGET_PLATFORM</code> 环境变量指定目标平台(scripts/build_vendor.sh:30-31)。这保证了模型层 import 路径与平台无关。
    </div>

    <pre class="code reveal"><span class="c"># scripts/build_vendor.sh(节选)—— 平台差异被收敛在构建期</span>
nvidia)
  BUILD_TARGET=CUDA
  PACKAGES=(DeepSelect FlashMLA DeepEP DeepGEMM)
  INSTALL=(deep_select flash_mla deep_ep deep_gemm) ;;
ascend)
  BUILD_TARGET=ASCEND
  PACKAGES=(DeepSelect FlashMLA DeepEP-Ascend DeepGEMM-Ascend)
  INSTALL=(deep_select flash_mla deep_ep deep_gemm) ;;</pre>
  </section>

  <!-- ================= 2. FlashMLA ================= -->
  <section id="s2">
    <h2 class="sec"><span class="num">2</span>FlashMLA:MLA 稀疏注意力内核</h2>
    <p class="lede">FlashMLA 是 DeepSeek 开源的 MLA/MQA 注意力内核家族,DeepInfer 用它承担 DeepSeek-V4.1-Flash 全部 prefill/decode 主注意力与 DFlash 草稿注意力,天然支持 paged FP8 KV cache、稀疏 top-k 索引、attention sink 与「SWA cache + 压缩 CA cache」双缓存拼接。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🎯</span>核心 API(attention_backend.py:2)</h3>
        <p>
          <code>flash_mla_sparse_fwd</code> —— prefill 稀疏注意力;<br>
          <code>flash_mla_with_kvcache</code> —— decode paged KV 注意力;<br>
          <code>fused_norm_rope_attn_rope_cast</code> —— 融合「Q norm + RoPE + 注意力 + 输出 RoPE + FP8 量化」的超级内核(prefill/decode 双入口);<br>
          <code>FlashMLASchedMeta</code> —— tile scheduler 元数据;<br>
          <code>permute_q_b_proj / permute_wv_proj</code> —— 为融合内核重排权重布局。
        </p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">📐</span>头数约束与补齐</h3>
        <p>FlashMLA 只接受 64/128 个 query head(<code>FLASH_MLA_HEAD_CHOICES</code>,attention_backend.py:5)。DeepInfer 在 <code>_pad_attention_heads</code>(attention_backend.py:8-23)中把不足的头数补零到最近的支持值,注意力结束后再裁剪回原头数,超限则直接抛错——保证小头数模型也能复用同一内核。</p>
      </div>
    </div>

    <table class="tbl reveal">
      <tr><th>场景</th><th>DeepInfer 封装</th><th>FlashMLA 入口</th><th>关键参数</th><th>代码位置</th></tr>
      <tr>
        <td>Prefill 稀疏注意力</td>
        <td><code>prefill_attn_varlen_sparse</code></td>
        <td><code>flash_mla_sparse_fwd</code></td>
        <td><code>index_topk</code> 稀疏索引、可选 <code>attn_sink</code> / <code>index_length</code></td>
        <td>attention_backend.py:26 / :64</td>
      </tr>
      <tr>
        <td>Decode MQA 稀疏注意力</td>
        <td><code>decode_mla_mqa_sparse</code></td>
        <td><code>flash_mla_with_kvcache</code></td>
        <td><code>tile_scheduler_metadata=sched_meta</code>、<code>is_fp8_kvcache=True</code>、<code>causal=False</code>、<code>extra_k_cache</code>(SWA+CA 双缓存)、<code>enable_batch_invariant</code></td>
        <td>attention_backend.py:77 / :125-142</td>
      </tr>
      <tr>
        <td>融合 norm+rope+attn+rope+cast</td>
        <td><code>_fused_norm_rope_cast_kwargs</code></td>
        <td><code>fused_norm_rope_attn_rope_cast.prefill / .decode</code></td>
        <td>输出直接是逐 32 通道量化的 (fp8, sf) 元组,供 <code>fp8_einsum</code> 消费</td>
        <td>attention_backend.py:51 / :108;attn.py:174-189</td>
      </tr>
      <tr>
        <td>权重重排(加载期)</td>
        <td><code>_permute_q_b_proj_for_fused</code> / <code>_init_wv_o_proj</code></td>
        <td><code>permute_q_b_proj</code> / <code>permute_wv_proj</code></td>
        <td>把 q_b / Wv 权重与 SF 一次性排成融合内核要求的布局</td>
        <td>attn.py:111-120 / :142-147</td>
      </tr>
    </table>

    <div class="note reveal">
      <b>启用门控:</b>融合注意力内核仅在 <code>num_heads ∈ (64,128)</code> 且 <code>PLATFORM.is_gpu</code> 时启用;batch-invariant 模式下的 dense packed-KV 解码会退回非融合路径(attn.py:87-92)。decode 使用的 <code>sched_meta</code> 按 <code>压缩率_hasPackedKV_useSWA_topk</code> 组成的 <code>sched_meta_key</code> 缓存在 <code>InputMetadataV4.flash_mla_sched_meta_dict</code> 中(attn.py:241 / :663),DFlash 草稿注意力使用专用键 <code>"DFlash"</code>(attn.py:999)。调度元数据本身由自研 TileLang 算子 <code>prepare_v4_decode_metadata_tl</code> 在 GPU 上生成(见 §6)。
    </div>

    <div class="figure reveal">
      <svg viewBox="0 0 960 400" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="arr1" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto">
            <polygon points="0 0, 8 3.5, 0 7" fill="#4f8cff"/>
          </marker>
        </defs>
        <text x="480" y="26" text-anchor="middle" class="figtitle">FlashMLA decode:稀疏索引 → 分块注意力 → FP8 输出(decode_mla_mqa_sparse,attention_backend.py:77)</text>

        <!-- Q tiles -->
        <rect class="node-gpu" x="30" y="90" width="150" height="70" rx="10"/>
        <text class="node-gpu-title" x="105" y="118" text-anchor="middle">Q tiles</text>
        <text class="figlabel" x="105" y="138" text-anchor="middle">total_q × 64/128 heads</text>

        <!-- sched meta -->
        <circle class="pulse" cx="120" cy="235" r="16" fill="none" stroke="#22d3ee" stroke-width="2"/>
        <text class="figlabel" x="120" y="278" text-anchor="middle">FlashMLASchedMeta</text>
        <text class="figlabel" x="120" y="293" text-anchor="middle">(tile_scheduler_metadata)</text>

        <!-- KV cache grid -->
        <rect class="node-gpu" x="255" y="70" width="260" height="180" rx="10"/>
        <text class="figlabel" x="385" y="92" text-anchor="middle">paged FP8 KV cache [num_blocks, block_size, 1, bytes/token]</text>
        <g>
          <rect x="275" y="105" width="42" height="26" class="kvsel"/>
          <rect x="323" y="105" width="42" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="371" y="105" width="42" height="26" class="kvsel" style="animation-delay:.5s"/>
          <rect x="419" y="105" width="42" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="467" y="105" width="30" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="275" y="140" width="42" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="323" y="140" width="42" height="26" class="kvsel" style="animation-delay:1s"/>
          <rect x="371" y="140" width="42" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="419" y="140" width="42" height="26" class="kvsel" style="animation-delay:1.4s"/>
          <rect x="467" y="140" width="30" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="275" y="175" width="42" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="323" y="175" width="42" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="371" y="175" width="42" height="26" class="kvsel" style="animation-delay:.8s"/>
          <rect x="419" y="175" width="42" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="467" y="175" width="30" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="275" y="210" width="42" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="323" y="210" width="42" height="26" class="kvsel" style="animation-delay:1.7s"/>
          <rect x="371" y="210" width="42" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="419" y="210" width="42" height="26" fill="#16233f" stroke="#33507e"/>
          <rect x="467" y="210" width="30" height="26" fill="#16233f" stroke="#33507e"/>
        </g>
        <text class="figlabel" x="385" y="282" text-anchor="middle" fill="#34d399">绿色脉冲块 = index_topk 选中的稀疏 KV(is_fp8_kvcache=True)</text>

        <!-- attention tiles -->
        <rect class="node-gpu" x="570" y="80" width="190" height="160" rx="10"/>
        <text class="figlabel" x="665" y="100" text-anchor="middle">attention tile 网格(M×N 分块)</text>
        <g>
          <rect class="attn-tile" x="592" y="112" width="46" height="34" style="animation-delay:0s"/>
          <rect class="attn-tile" x="642" y="112" width="46" height="34" style="animation-delay:.3s"/>
          <rect class="attn-tile" x="692" y="112" width="46" height="34" style="animation-delay:.6s"/>
          <rect class="attn-tile" x="592" y="152" width="46" height="34" style="animation-delay:.9s"/>
          <rect class="attn-tile" x="642" y="152" width="46" height="34" style="animation-delay:1.2s"/>
          <rect class="attn-tile" x="692" y="152" width="46" height="34" style="animation-delay:1.5s"/>
          <rect class="attn-tile" x="592" y="192" width="46" height="34" style="animation-delay:1.8s"/>
          <rect class="attn-tile" x="642" y="192" width="46" height="34" style="animation-delay:2.1s"/>
          <rect class="attn-tile" x="692" y="192" width="46" height="34" style="animation-delay:2.4s"/>
        </g>

        <!-- output -->
        <rect class="node-gpu" x="810" y="115" width="120" height="90" rx="10" style="stroke:#34d399"/>
        <text class="node-gpu-title" x="870" y="148" text-anchor="middle">输出</text>
        <text class="figlabel" x="870" y="168" text-anchor="middle">bf16 或 (fp8, sf)</text>
        <text class="figlabel" x="870" y="183" text-anchor="middle">+ lse</text>

        <!-- flows -->
        <line class="flowline" x1="180" y1="125" x2="562" y2="125" stroke="#4f8cff" stroke-width="2" marker-end="url(#arr1)"/>
        <line class="flowline" x1="515" y1="180" x2="562" y2="180" stroke="#34d399" stroke-width="2" marker-end="url(#arr1)"/>
        <line class="flowline" x1="760" y1="160" x2="800" y2="160" stroke="#4f8cff" stroke-width="2" marker-end="url(#arr1)"/>
        <line class="flowline" x1="136" y1="219" x2="592" y2="219" stroke="#22d3ee" stroke-width="1.6" marker-end="url(#arr1)" opacity=".8"/>

        <!-- moving dots -->
        <circle r="5" class="token-dot barrow">
          <animateMotion dur="2.6s" repeatCount="indefinite" path="M185,125 L558,125"/>
        </circle>
        <circle r="4.5" class="token-dot barrow" style="fill:#34d399">
          <animateMotion dur="2.2s" begin="0.4s" repeatCount="indefinite" path="M520,180 L558,180 L585,150"/>
        </circle>
        <circle r="5" class="token-dot barrow" style="fill:#a78bfa">
          <animateMotion dur="2.8s" begin="0.9s" repeatCount="indefinite" path="M765,160 L798,160"/>
        </circle>
        <circle r="3.6" class="token-dot barrow" style="fill:#fbbf24">
          <animateMotion dur="3.4s" begin="0.2s" repeatCount="indefinite" path="M140,219 C300,255 480,250 588,222"/>
        </circle>

        <!-- bottom note -->
        <text class="figlabel" x="480" y="345" text-anchor="middle">attn_sink(fp32)沿 head 维广播;enable_batch_invariant 控制确定性归约 —— attention_backend.py:125-142</text>
        <text class="figlabel" x="480" y="363" text-anchor="middle" fill="#fbbf24">黄色数据包 = FlashMLASchedMeta 驱动的 tile 静态调度,无需 CPU 参与负载均衡</text>
      </svg>
      <div class="cap">图 2-1 · FlashMLA 稀疏 decode 注意力:Q 分块与被 top-k 选中的 KV 块在 tile scheduler 的静态编排下逐块点亮,输出可直接以 (fp8, sf) 形式交给 DeepGEMM einsum</div>
    </div>
  </section>

  <!-- ================= 3. DeepGEMM ================= -->
  <section id="s3">
    <h2 class="sec"><span class="num">3</span>DeepGEMM:FP8/FP4 GEMM 与索引器内核</h2>
    <p class="lede">DeepGEMM 承担模型中所有密集/分组矩阵乘:线性层 FP8 GEMM、注意力 Wv 投影 einsum、MoE 分组 GEMM、mega-MoE 单内核融合,以及稀疏索引器的 MQA logits——顺带管理 SF 布局变换、MK 对齐、SM 数与确定性算法等全局状态。</p>

    <table class="tbl reveal">
      <tr><th>API</th><th>作用</th><th>典型调用点</th><th>代码位置</th></tr>
      <tr><td><code>fp8_fp4_gemm_nt</code></td><td>FP8/FP4 密集 GEMM(recipe=(1,1,32))</td><td><code>ReplicatedLinear.apply_weight_fp8</code> —— 所有 Q/KV/o 投影线性层</td><td>linear.py:165</td></tr>
      <tr><td><code>bf16_gemm_nt</code></td><td>BF16 密集 GEMM</td><td><code>apply_weight_bf16</code></td><td>linear.py:33 / :135</td></tr>
      <tr><td><code>fp8_einsum</code></td><td>einsum 形式的分组 GEMM(<code>"bhr,hdr-&gt;bhd"</code>)</td><td>注意力 Wv 投影:context(fp8,sf)× Wv 权重,可输出 FP8</td><td>attn.py:215-221</td></tr>
      <tr><td><code>m_grouped_fp8_fp4_gemm_nt_contiguous</code></td><td>MoE 专家分组 GEMM(contiguous 布局 + psum)</td><td>routed experts 的 gate_up / down 投影</td><td>mlp.py:119-128</td></tr>
      <tr><td><code>m_grouped_bf16_gemm_nt_contiguous</code></td><td>BF16 分组 GEMM</td><td>BF16 MoE 路径</td><td>mlp.py:130-137</td></tr>
      <tr><td><code>fp8_fp4_mega_moe / bf16_mega_moe</code></td><td>mega-MoE:路由+两组 GEMM+激活+combine 单内核</td><td>NVLink 域内 MoE(<code>use_mega_moe</code>)</td><td>mlp.py:255 / :549-559</td></tr>
      <tr><td><code>fp8_fp4_mqa_logits</code> 系列(含 <code>sparse</code> / <code>paged</code> 变体)</td><td>稀疏索引器 <code>relu(q@k)·weights</code> logits</td><td><code>MQA</code> 索引器打分</td><td>index_attn.py:299 / :317 / :434 / :447</td></tr>
      <tr><td><code>get_*_mqa_logits_metadata</code></td><td>MQA logits 的调度元数据</td><td>prefill/decode 索引器</td><td>index_attn.py:273 / :392 / :410</td></tr>
      <tr><td><code>transform_sf_into_required_layout</code></td><td>把 HF 块状 SF 重排为 DeepGEMM 要求的 TMA 对齐布局</td><td>权重加载(Wv、MoE、线性层)</td><td>linear.py:70-76 / attn.py:134-141 / mlp.py:73-81</td></tr>
      <tr><td><code>transform_weights_for_mega_moe</code></td><td>权重重排为 mega-MoE 布局</td><td><code>_convert_mega_moe_weight</code></td><td>mlp.py:93-106</td></tr>
      <tr><td><code>get/set_mk_alignment_for_contiguous_layout</code></td><td>分组 GEMM 的 M 维对齐(expert alignment)</td><td>DeepEP dispatch 的 <code>expert_alignment</code> 参数;同时同步 <code>tile_kernels.set_token_alignment</code></td><td>mlp.py:250-252 / :477</td></tr>
      <tr><td><code>SymmBuffer</code></td><td>NVLink 对称缓冲:topk/x/x_sf 共享存储,支撑 mega-MoE</td><td><code>userbuffer.allocate_sym_buffer</code>(首个 spec 持有后备存储,后续 spec 复用视图)</td><td>userbuffer.py:183-225 / mlp.py:305</td></tr>
      <tr><td><code>locality_domain.get_balanced_sm_locality_domains</code></td><td>SM 亲和域探测(首次调用会同步)</td><td>在 guarded forward 与 CUDA graph 捕获之前预热,避免捕获期同步</td><td>userbuffer.py:216-220</td></tr>
      <tr><td><code>get_num_sms / set_num_sms</code></td><td>DeepGEMM 可用 SM 数管理</td><td><code>limit_num_sms</code> 上下文管理器</td><td>userbuffer.py:44-51</td></tr>
      <tr><td><code>get_tma_aligned_size</code></td><td>TMA 对齐的 stride 计算</td><td>einsum 输出 SF 的列主序布局</td><td>attn.py:208</td></tr>
    </table>

    <div class="note good reveal">
      <b>FP8 量化配方统一:</b>激活逐 token 量化由 <code>tile_kernels.quant.per_token_cast</code> 完成,固定参数 <code>fmt=e4m3, num_per_channels=32, round_sf=True, use_packed_ue8m0=True, use_tma_aligned_col_major_sf=True</code>(linear.py:13-24 的 <code>get_fp8_cast_params</code>)。注意力 context 的再量化在 attn.py:200,FP4 权重的运行期重打包在 mlp.py:61-69(仅支持 FP4-QAT checkpoint,断言低两位为零)。
    </div>

    <div class="figure reveal">
      <svg viewBox="0 0 960 390" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="arr2" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto">
            <polygon points="0 0, 8 3.5, 0 7" fill="#22d3ee"/>
          </marker>
        </defs>
        <text x="480" y="26" text-anchor="middle" class="figtitle">FP8 GEMM 数据流:激活量化 → SF 布局变换 → 分块矩阵乘(linear.py:165 / mlp.py:119)</text>

        <!-- activation path -->
        <rect class="node-gpu" x="26" y="70" width="120" height="64" rx="10"/>
        <text class="node-gpu-title" x="86" y="96" text-anchor="middle">bf16 激活</text>
        <text class="figlabel" x="86" y="115" text-anchor="middle">[M, K]</text>

        <rect class="node-gpu" x="196" y="56" width="150" height="92" rx="10" style="stroke:#fbbf24"/>
        <text class="node-gpu-title" x="271" y="84" text-anchor="middle">per_token_cast</text>
        <text class="figlabel" x="271" y="103" text-anchor="middle">tile_kernels.quant</text>
        <text class="figlabel" x="271" y="119" text-anchor="middle">e4m3 · 32ch · ue8m0</text>
        <circle class="pulse" cx="271" cy="136" r="5" fill="#fbbf24"/>

        <!-- fp8 + sf pair -->
        <rect class="node-gpu" x="396" y="42" width="120" height="48" rx="10" style="stroke:#22d3ee"/>
        <text class="node-gpu-title" x="456" y="62" text-anchor="middle" style="font-size:12px">fp8 e4m3</text>
        <text class="figlabel" x="456" y="79" text-anchor="middle">[M, K]</text>
        <rect class="node-gpu" x="396" y="112" width="120" height="48" rx="10" style="stroke:#a78bfa"/>
        <text class="node-gpu-title" x="456" y="132" text-anchor="middle" style="font-size:12px">SF(ue8m0)</text>
        <text class="figlabel" x="456" y="149" text-anchor="middle">int32(GPU)/int16(NPU)</text>

        <!-- GEMM core -->
        <rect class="node-gpu" x="580" y="52" width="210" height="150" rx="10"/>
        <text class="figlabel" x="685" y="74" text-anchor="middle">DeepGEMM 分块累加(TMA + tensor core)</text>
        <g>
          <rect class="gemm-tile" x="604" y="88" width="40" height="30" style="animation-delay:0s"/>
          <rect class="gemm-tile" x="648" y="88" width="40" height="30" style="animation-delay:.35s"/>
          <rect class="gemm-tile" x="692" y="88" width="40" height="30" style="animation-delay:.7s"/>
          <rect class="gemm-tile" x="736" y="88" width="40" height="30" style="animation-delay:1.05s"/>
          <rect class="gemm-tile" x="604" y="126" width="40" height="30" style="animation-delay:1.4s"/>
          <rect class="gemm-tile" x="648" y="126" width="40" height="30" style="animation-delay:1.75s"/>
          <rect class="gemm-tile" x="692" y="126" width="40" height="30" style="animation-delay:2.1s"/>
          <rect class="gemm-tile" x="736" y="126" width="40" height="30" style="animation-delay:2.45s"/>
          <rect class="gemm-tile" x="604" y="164" width="40" height="30" style="animation-delay:.9s"/>
          <rect class="gemm-tile" x="648" y="164" width="40" height="30" style="animation-delay:1.3s"/>
          <rect class="gemm-tile" x="692" y="164" width="40" height="30" style="animation-delay:1.7s"/>
          <rect class="gemm-tile" x="736" y="164" width="40" height="30" style="animation-delay:2.2s"/>
        </g>

        <!-- output -->
        <rect class="node-gpu" x="840" y="105" width="100" height="70" rx="10" style="stroke:#34d399"/>
        <text class="node-gpu-title" x="890" y="132" text-anchor="middle">bf16 输出</text>
        <text class="figlabel" x="890" y="151" text-anchor="middle">[M, N]</text>

        <!-- weight path -->
        <rect class="node-gpu" x="26" y="255" width="150" height="64" rx="10"/>
        <text class="node-gpu-title" x="101" y="281" text-anchor="middle">FP8/FP4 权重</text>
        <text class="figlabel" x="101" y="300" text-anchor="middle">+ HF 块状 SF</text>

        <rect class="node-gpu" x="236" y="243" width="230" height="88" rx="10" style="stroke:#a78bfa"/>
        <text class="node-gpu-title" x="351" y="270" text-anchor="middle">transform_sf_into_required_layout</text>
        <text class="figlabel" x="351" y="289" text-anchor="middle">重排为 TMA 列主序 packed 布局</text>
        <text class="figlabel" x="351" y="305" text-anchor="middle">recipe=(1, 32, 32) / (1,1,32)</text>

        <line class="flowline" x1="146" y1="287" x2="232" y2="287" stroke="#a78bfa" stroke-width="2" marker-end="url(#arr2)"/>
        <line class="flowline" x1="466" y1="287" x2="575" y2="215" stroke="#a78bfa" stroke-width="2" marker-end="url(#arr2)"/>

        <!-- flows -->
        <line class="flowline" x1="146" y1="102" x2="192" y2="102" stroke="#22d3ee" stroke-width="2" marker-end="url(#arr2)"/>
        <line class="flowline" x1="346" y1="66" x2="392" y2="66" stroke="#22d3ee" stroke-width="2" marker-end="url(#arr2)"/>
        <line class="flowline" x1="346" y1="136" x2="392" y2="136" stroke="#a78bfa" stroke-width="2" marker-end="url(#arr2)"/>
        <line class="flowline" x1="516" y1="66" x2="576" y2="90" stroke="#22d3ee" stroke-width="2" marker-end="url(#arr2)"/>
        <line class="flowline" x1="516" y1="136" x2="576" y2="140" stroke="#a78bfa" stroke-width="2" marker-end="url(#arr2)"/>
        <line class="flowline" x1="790" y1="127" x2="836" y2="140" stroke="#34d399" stroke-width="2" marker-end="url(#arr2)"/>

        <!-- moving dots -->
        <circle r="5" class="token-dot barrow">
          <animateMotion dur="2.4s" repeatCount="indefinite" path="M150,102 L188,102"/>
        </circle>
        <circle r="5" class="token-dot barrow">
          <animateMotion dur="2.6s" begin=".3s" repeatCount="indefinite" path="M350,66 L388,66 L514,66 L572,92"/>
        </circle>
        <circle r="4.5" class="token-dot barrow" style="fill:#a78bfa">
          <animateMotion dur="3s" begin=".6s" repeatCount="indefinite" path="M350,136 L388,136 L514,138 L572,142"/>
        </circle>
        <circle r="4.5" class="token-dot barrow" style="fill:#fbbf24">
          <animateMotion dur="3.6s" begin=".2s" repeatCount="indefinite" path="M152,287 C400,340 520,300 580,220"/>
        </circle>
        <circle r="5" class="token-dot barrow" style="fill:#34d399">
          <animateMotion dur="2.2s" begin="1s" repeatCount="indefinite" path="M794,130 L832,142"/>
        </circle>

        <!-- variant chips -->
        <g>
          <rect x="560" y="255" width="170" height="26" rx="13" fill="rgba(79,140,255,.12)" stroke="rgba(79,140,255,.4)"/>
          <text class="figlabel" x="645" y="272" text-anchor="middle" fill="#4f8cff">fp8_fp4_gemm_nt(线性层)</text>
          <rect x="560" y="290" width="170" height="26" rx="13" fill="rgba(34,211,238,.10)" stroke="rgba(34,211,238,.35)"/>
          <text class="figlabel" x="645" y="307" text-anchor="middle" fill="#22d3ee">fp8_einsum(注意力 Wv)</text>
          <rect x="745" y="255" width="185" height="26" rx="13" fill="rgba(167,139,250,.10)" stroke="rgba(167,139,250,.35)"/>
          <text class="figlabel" x="837" y="272" text-anchor="middle" fill="#a78bfa">m_grouped_*_gemm(MoE 专家)</text>
          <rect x="745" y="290" width="185" height="26" rx="13" fill="rgba(52,211,153,.10)" stroke="rgba(52,211,153,.35)"/>
          <text class="figlabel" x="837" y="307" text-anchor="middle" fill="#34d399">mega_moe / mqa_logits(索引器)</text>
        </g>
        <text class="figlabel" x="480" y="360" text-anchor="middle">紫色通道 = scale factor(SF)数据面:激活 SF 与权重 SF 在进入 tensor core 前分别完成布局对齐</text>
      </svg>
      <div class="cap">图 3-1 · FP8 GEMM 双数据面:数值面(fp8 e4m3)与缩放面(ue8m0 SF)分离流动,在 DeepGEMM 分块内核中汇合累加</div>
    </div>
  </section>

  <!-- ================= 4. DeepEP ================= -->
  <section id="s4">
    <h2 class="sec"><span class="num">4</span>DeepEP V2:EP / CP / Engram 三类通信缓冲</h2>
    <p class="lede">DeepInfer 把 DeepEP V2 的三种 buffer 统一收口在 <code>_UserBufferManager</code>(单例 <code>userbuffer</code>):EPBuffer 服务 MoE dispatch/combine,BucketBuffer 服务 CP all-gather,EngramBuffer 服务 n-gram 嵌入的跨 rank 哈希取数——全部由 RDMA 直达,与计算流异步。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🔀</span>EPBuffer(MoE dispatch/combine)</h3>
        <p><code>allocate_ep</code> 以 <code>allow_hybrid_mode=True</code>、可选 <code>use_fp8_dispatch</code> 创建(userbuffer.py:63-95);batch-invariant + 专家重排时关闭 <code>allow_multiple_reduction</code> 以保证归约顺序确定(userbuffer.py:79)。dispatch 调用带 <code>defer_epilogue / do_expand / use_tma_aligned_col_major_sf</code>,并以 <code>expert_alignment=deep_gemm.get_mk_alignment_for_contiguous_layout()</code> 让收到的 token 布局直接满足分组 GEMM(mlp.py:469-489);combine 为高吞吐分块归约(mlp.py:501-511)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧲</span>CPManager(BucketBuffer all-gather)</h3>
        <p>上下文并行用 <code>deep_ep.BucketBuffer</code> 的 session 化 all-gather:先 <code>get_inplace_tensor</code> 在 buffer 内取得本 rank 连续分片,发送后 wait 回调把各 rank 分片按 token 轴拼接(cp.py:9-45)。注意力层把它用于「压缩器输入 all-gather 与 Q 投影重叠」(attn.py:782-785)以及 YoCo 全量 KV 镜像 gather(attn.py:943-944)。缓冲尺寸由 <code>get_num_rdma_alignment / get_num_allocation_alignment</code> 对齐(userbuffer.py:108-110)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">📚</span>EngramBuffer(n-gram 嵌入)</h3>
        <p>按 hash 把 n-gram 嵌入表分片到各 rank:<code>allocate_engram</code> 用 <code>get_storage_size_hint / get_theoretical_config</code> 推导 GPU 字节数与 QP 配置(userbuffer.py:127-181);<code>write</code> 把 CPU 权重以 CUDA 视图直接写入缓冲(engram.py:210),<code>fetch</code> 返回各层的取数 hook(engram.py:215-218)。注释明确:EP 走 NVLink 时 Engram 保持默认 sl3,sl2 留给 KV cache 流量隔离(userbuffer.py:155)。</p>
      </div>
      <div class="card reveal">
        <h3><span class="ico">🧮</span>SymmBuffer(DeepGEMM 对称缓冲)</h3>
        <p>mega-MoE 路径的 NVLink 对称缓冲:topk_idx / topk_weights / x / x_sf 共享存储,首个分配的 spec 拥有后备存储,后续 spec 作为缓存视图复用(userbuffer.py:183-225,mlp.py:305)。创建前预热 <code>locality_domain.get_balanced_sm_locality_domains</code>,避免 DeepGEMM 首次探测 SM 亲和在 CUDA graph 捕获期引发同步(userbuffer.py:214-220)。</p>
      </div>
    </div>

    <div class="note reveal">
      <b>与 NCCL 的分工:</b>DeepEP 承担 token 级高频小消息(dispatch/combine、CP all-gather、Engram fetch);NCCL 只用于集合通信的其它路径,且其 SM 占用被 <code>DEEPINFER_NCCL_NUM_SMS</code>(默认 32)钉死(platform.py:80-83 将其同时设为 <code>max_ctas/min_ctas</code>)。EP 相关 env 由 runtime_config.py:33 设置 <code>EP_AVOID_RECORD_STREAM=1</code>。跨卡通信全景详见本系列第 ⑩ 篇。
    </div>
  </section>

  <!-- ================= 5. DeepSelect ================= -->
  <section id="s5">
    <h2 class="sec"><span class="num">5</span>DeepSelect:高性能 top-k 内核</h2>
    <p class="lede">DeepSelect 提供 GPU 上的 fused top-k,在 DeepInfer 中服务于两个完全不同的负载:采样器强制 top-k(需要返回值)与稀疏索引器的候选块选择(只要索引)。</p>

    <table class="tbl reveal">
      <tr><th>调用方</th><th>用法</th><th>要点</th><th>代码位置</th></tr>
      <tr>
        <td>采样器(force top-k)</td>
        <td><code>topk(logits, force_topk, False, indices_type=torch.int32)</code></td>
        <td><code>DEEPINFER_SAMPLER_FORCE_TOPK &gt; 0</code> 时先把词表裁剪到 top-k 空间再做温度/top-p 与 reject 采样对齐</td>
        <td>sampler_utils.py:4 / :68 / :167</td>
      </tr>
      <tr>
        <td>稀疏索引器候选块</td>
        <td><code>topk(block_scores, topk_blocks, sorted=False, end=valid_blocks, ..., return_value=False)</code></td>
        <td>只取索引(<code>return_value=False</code>),支持 <code>end</code> 有效长度与 OOB 填充 -1,输出直接写入 <code>cross_layer_runtime.block_candidate_idxs</code></td>
        <td>index_attn.py:12 / :216-226(另见 :361 / :494)</td>
      </tr>
      <tr>
        <td>NPU 垫片</td>
        <td><code>npu_ops/deep_select.py::topk</code></td>
        <td>采样器场景(需要返回值)暂回退 <code>torch.topk</code>;索引器场景走真内核</td>
        <td>npu_ops/deep_select.py:21-27</td>
      </tr>
    </table>

    <div class="note warn reveal">
      <b>平台垫片机制:</b><code>deepinfer/npu_ops/__init__.py:3-11</code> 用 <code>patch_imports</code> 在 NPU 平台把 <code>deep_select.interface.topk</code> 与 <code>flash_attn.cute.interface._flash_attn_fwd</code> 替换为本地实现——模型代码无需感知平台(<code>from deep_select.interface import topk</code> 的 import 位置不变)。ViT 注意力同样以 <code>torch_npu.npu_fusion_attention</code> 兜底(npu_ops/vit_attn.py:9-31)。
    </div>
  </section>

  <!-- ================= 6. TileLang 自研算子 ================= -->
  <section id="s6">
    <h2 class="sec"><span class="num">6</span>TileLang 自定义算子全景</h2>
    <p class="lede"><code>deepinfer/model_executor/layers/tilelang_ops/</code> 是 DeepInfer 的自研内核层:<code>cuda/</code> 与 <code>asc/</code> 两个目录实现同一组 <code>*_tl</code> 算子工厂,顶层模块是对模型暴露的稳定接口(内含正确性测试与 PyTorch 参考实现)。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🧭</span>后端分发器 ops.py</h3>
        <p>接口模块统一 <code>from ...tilelang_ops import ops</code> 后调用 <code>ops.xxx_tl</code>。分发器按 <code>PLATFORM.tilelang_ops_backend</code>(GPU=<code>"cuda"</code>,platform.py:57;NPU=<code>"asc"</code>,platform.py:88)导入对应子包,把所有以 <code>_tl</code> 结尾的符号重导出到 <code>ops</code> 命名空间,并检查符号冲突(ops.py:15-22)。缺失内核通过 <code>__getattr__</code> 抛 <code>KernelUnavailableError</code>,测试框架据此跳过。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧬</span>双后端同构</h3>
        <p>两套后端的算子清单几乎完全一致(例如 <code>fused_norm_rope_hadamard_cast_store_kvcache_tl</code> 在 cuda/fused_transform.py:17 与 asc/fused_transform.py:739 各有一份实现),差异只在实现语言:cuda 后端用 <code>tilelang.language</code> 的线程/Fragment 模型,asc 后端大量使用 <code>tilelang.ascend.language.simd</code> 的 128-lane 向量寄存器原语(见 §6.3 kv_quant)。</p>
      </div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:26px 0 4px">6.1 算子清单(接口 → 双后端实现)</h3>
    <table class="tbl reveal">
      <tr><th>接口 / 算子工厂</th><th>平台</th><th>功能</th><th>cuda 实现位置</th></tr>
      <tr><td><code>store_kv_cache_tl</code></td><td>GPU+NPU</td><td>paged KV cache 写入:BF16 直存,或量化为 FP8 e4m3 / FP4 e2m1 并写 ue8m0/e4m3/fp32 SF;<code>slot_mapping=-1</code> 跳过</td><td>cuda/store_kv_cache.py:27</td></tr>
      <tr><td><code>fused_norm_rope_hadamard_cast_store_kvcache_tl</code></td><td>GPU+NPU</td><td>单内核融合 RMSNorm → RoPE → Hadamard → FP8/FP4 量化 → 写 KV cache,支持 norm/transform/cast_back 三档 bf16 输出</td><td>cuda/fused_transform.py:17(asc:739)</td></tr>
      <tr><td><code>random_sampling_tl</code></td><td>GPU+NPU</td><td>两级定点加权采样:行折叠为 BD 个 lane 累加 → 一次 64-bit 均匀数选 lane → 精确列定位</td><td>cuda/random_sampling.py:207</td></tr>
      <tr><td><code>fused_sample_tl</code></td><td>GPU+NPU</td><td>采样器主内核:temperature / top-p / top-k / log-softmax / 采样 / reject sampling 一体化</td><td>cuda/fused_sample.py</td></tr>
      <tr><td><code>prepare_verification_metadata_tl</code> 等 6 个</td><td>GPU+NPU</td><td>投机解码验证:元数据准备、采样参数展开、接受结果、map_lookup、draft top-k 重映射、验证收尾</td><td>cuda/sampler.py</td></tr>
      <tr><td><code>store_mtp_info_tl</code></td><td>GPU+NPU</td><td>MTP 信息池写入(nextn 步的 logits/confidence)</td><td>cuda/store_mtp_info.py(调用 mtp_info_pool.py:68)</td></tr>
      <tr><td><code>prepare_cp_mirror_tl</code> / <code>yoco_cp_boundary_fused_tl</code></td><td>GPU+NPU</td><td>CP 镜像布局:前缀扫描 + 输出并行 scatter(YoCo 边界变体),两段 kernel 用 PDL 串联</td><td>cuda/prepare_cp_mirror.py:16 / :179</td></tr>
      <tr><td><code>prepare_v4_decode_metadata_tl</code> + <code>copy_block_tables_tl</code></td><td>GPU+NPU</td><td>decode 全量元数据:positions、SWA/CA slot 映射、klen、压缩比 ratio 分桶输出、block table 展开</td><td>cuda/prepare_decode_metadata.py(wrapper prepare_v4_decode_metadata.py:10)</td></tr>
      <tr><td><code>convert_kv_index_tl</code></td><td>GPU+NPU</td><td>topk token 索引 → paged cache 物理 slot(block_table 换算)</td><td>cuda/flash_mla_utils.py:13</td></tr>
      <tr><td><code>gather_tl</code></td><td>GPU+NPU</td><td>按行索引 gather,越界索引行置零;支持 strided 输入</td><td>cuda/gather.py(wrapper gather.py:24)</td></tr>
      <tr><td><code>kv_index_cat_tl</code></td><td>GPU+NPU</td><td>SWA 滑窗索引与压缩 CA 索引拼接(带缓存段偏移)</td><td>cuda/kv_index_cat.py(调用 attn.py:607)</td></tr>
      <tr><td><code>load_paged_kv_cache_tl</code></td><td>GPU+NPU</td><td>按 load_segments 把 paged cache 段加载为连续 prefill KV</td><td>cuda/load_paged_kv_cache.py(wrapper load_paged_kv_cache.py:28)</td></tr>
      <tr><td><code>load_state_to_cache_tl</code> / <code>select_state_slice_tl</code></td><td>GPU+NPU</td><td>SWA 有界重放:状态槽写入 cache / 按序列选取状态切片</td><td>cuda/state_cache.py(wrapper state_cache.py:48 / :12)</td></tr>
      <tr><td><code>expand_swa_index_tl</code></td><td>GPU+NPU</td><td>SWA 滑窗索引由 pivot 展开为稠密索引</td><td>cuda/swa_index.py(调用 input_metadata.py:341)</td></tr>
      <tr><td><code>compress_and_update_state_prefill_tl / _decode_tl</code></td><td>GPU+NPU</td><td>压缩 KV 生成 + 压缩状态更新(ZOS 路径),wrapper 打开 fast-math</td><td>cuda/compress.py(wrapper compress.py:20 / :74)</td></tr>      <tr><td><code>candidate_block_max_tl</code> / <code>get_candidate_compact_lens_tl</code> / <code>restore_candidate_indices_inplace_tl</code></td><td>GPU+NPU</td><td>稀疏索引候选块打分(block max)、紧凑长度、索引还原</td><td>cuda/candidate_blocks.py</td></tr>
      <tr><td><code>compute_seqlens_k_zos_tl</code></td><td>GPU+NPU</td><td>ZOS 解码的 seqlens_k 计算</td><td>cuda/compute_seqlens_k_zos.py(调用 worker.py:221)</td></tr>
      <tr><td><code>gather_input_ids_zos_tl</code> / <code>gather_engram_tokens_zos_tl</code></td><td>GPU+NPU</td><td>ZOS 输入按索引 gather(token ids 与 engram token)</td><td>cuda/gather_input_ids_zos.py 等(调用 prepare_tensor_input_zos.py:235 / :258)</td></tr>
      <tr><td><code>confidence_head_fused_tl</code> / <code>dflash_input_store_tl</code></td><td>GPU+NPU</td><td>DFlash 置信头(双 GEMV + sigmoid,logit 钳制 ±60)/ 草稿输入按 hc_mult 求和写入</td><td>cuda/dflash.py:12 / :82</td></tr>
      <tr><td><code>copy_dflash_decode_input_tl</code></td><td>GPU+NPU</td><td>DFlash decode 输入复制(driver inputs 可选)</td><td>cuda/dflash_copy.py</td></tr>
      <tr><td><code>compute_seqlens_q_by_confidence_rates_tl</code></td><td>GPU+NPU</td><td>MTP 变长调度:置信率累乘 + 并行 rank 计数选取 top 预算 token</td><td>cuda/schedule_mtp_varlen.py:14</td></tr>
      <tr><td><code>replace_input_embeds_tl</code> / <code>rgb_pad_to_patches_tl</code> / <code>batch_downsample_tl</code></td><td>GPU+NPU</td><td>多模态:图像 token 嵌入替换 / RGB→归一化 patch 中心填充(禁 FMA 保证与 CPU 参考逐 bit 一致)/ 空间下采样</td><td>cuda/image_embed_ops.py:12 / :65 / :198</td></tr>
      <tr><td><code>norm_tl</code></td><td>GPU+NPU</td><td>RMSNorm(与 fused_transform 共享调度启发式)</td><td>cuda/norm.py</td></tr>
      <tr><td><code>apply_token_bitmask_by_step_inplace_tl</code></td><td>GPU+NPU</td><td>结构化输出:按投机步就地施加词表 bitmask</td><td>cuda/structure_output.py(调用 structure_output/mask.py:33)</td></tr>
      <tr><td><code>sum_smaller_probs_tl</code></td><td>GPU+NPU</td><td>采样统计:被接受 token 之外的较小概率质量和</td><td>cuda/sum_smaller_probs.py(wrapper sum_smaller_probs.py:10;调用 llm_engine.py:750)</td></tr>
      <tr><td><code>get_fused_dflash_get_input_tl</code> / <code>load_kv_index_tl</code></td><td>GPU+NPU</td><td>DFlash 输入融合准备 / KV 索引加载</td><td>cuda/get_kv_index.py</td></tr>
      <tr><td><code>detect_outlier_and_abort_tl</code></td><td><span class="badge open">仅 GPU</span></td><td>激活值离群检测并中止(数值哨兵)</td><td>cuda/outlier_detection.py</td></tr>
      <tr><td>kv_quant 宏族(<code>make_kv_scale_impl</code> / <code>make_kv_quant_impl</code>)</td><td><span class="badge hccl">仅 NPU</span></td><td>昇腾 SIMD 寄存器级 BF16→FP8/FP4 KV 量化:group16/32、ue8m0/e4m3、倒数 LUT、sticky-bit FP4 打包</td><td>asc/kv_quant.py:48 / :97</td></tr>
      <tr><td><code>rstd_1ulp</code> 宏</td><td><span class="badge hccl">仅 NPU</span></td><td>1-ULP 精度 rsqrt(供 asc norm 使用)</td><td>asc/rstd_1ulp.py</td></tr>
      <tr><td><code>_state_cache_copy_tl</code></td><td><span class="badge hccl">仅 NPU</span></td><td>昇腾状态 cache 拷贝变体</td><td>asc/state_cache.py</td></tr>
    </table>

    <h3 style="color:#fff;font-size:17px;margin:26px 0 4px">6.2 重点算子剖析</h3>

    <div class="card reveal" style="margin-bottom:18px">
      <h3><span class="ico">💾</span>store_kv_cache:格式驱动的 paged 写入</h3>
      <p>单一入口按 <code>KVCacheFormat</code> 特化:BF16 布局走 256 线程纯拷贝;FP8/FP4 布局在寄存器内完成 absmax 归约 → ue8m0 指数编码(<code>_amax_to_ue8m0_scales</code> 宏,cuda/store_kv_cache.py:10)→ 量化写值 + 写 SF,FP4 还要处理 value/scale 双 stride 与 32B 对齐断言。内核以 <code>T.pdl_sync()</code> 开场,以正确消费依赖启动(<code>slot_mapping</code> 可能由上游 kernel 产出,cuda/store_kv_cache.py:99-102)。NPU 路径在 wrapper 中单独分支:直接以 <code>[num_blocks, block_size, num_elements]</code> 视图调用(tilelang_ops/store_kv_cache.py:61-63),而参考实现里的 <code>_slot_scatter</code> 显式绕开昇腾 IndexPutV2 的 32 位偏移回绕 bug(tilelang_ops/store_kv_cache.py:81-92)。模型侧调用:SWA prefill 存储在 attn.py:855,DFlash 草稿 KV 在 attn.py:976-991。</p>
    </div>

    <div class="card reveal" style="margin-bottom:18px">
      <h3><span class="ico">🌀</span>fused_transform:五合一投影后处理</h3>
      <p><code>fused_norm_rope_hadamard_cast_store_kvcache_tl</code>(cuda/fused_transform.py:17)把「RMSNorm → RoPE(NEOX/交错可选,支持共轭)→ Hadamard 蝶形变换(仅 head_dim=128)→ FP8/FP4 量化 → 写 paged cache」压缩成一个 kernel。其线程调度启发式显式权衡四个目标:最大化向量化宽度、最小化 padding、最大化 occupancy、最大化每线程元素数(cuda/fused_transform.py:92-100 注释);RoPE 阶段用自定义 <code>Fragment</code> 布局保证行不跨 warp,只需 <code>sync_warp</code>(cuda/fused_transform.py:144-150)。模型侧调用遍布注意力:Q norm+RoPE(attn.py:161)、SWA KV 准备(attn.py:433)、DFlash 主 cache 更新(attn.py:946-961)、草稿 KV(attn.py:976-991)、压缩器 KV(compress.py:148)与索引器 K(index_attn.py:146 / :167)。</p>
    </div>

    <div class="card reveal" style="margin-bottom:18px">
      <h3><span class="ico">🎲</span>random_sampling + fused_sample:确定性与分布保证</h3>
      <p><code>random_sampling_tl</code>(cuda/random_sampling.py:207)每行一个 CTA:先把概率行折叠成 BD 个定点 lane 和(vocab≥8192 时 BD=2048,threads=256),一次拒绝采样式 64-bit 均匀数选出 lane,再对长度 <code>n_chunks</code> 的算术序列做精确二分(cuda/random_sampling.py:208-214)。uint64 定点编码直接从 f32 尾数/指数位构造,保证 <code>floor(x·2^scale_bits)</code> 精确(cuda/random_sampling.py:38-50)。<code>fused_sample</code>(接口 fused_sample.py:18,内核调用 :94-118)在此基础上融合 temperature/top-p/top-k/log-softmax 与 reject sampling——draft 分布加 <code>DRAFT_PROB_PENALTY=5e-5</code> 防止残余权重全零(common.py:53,数学推导见 common.py:3-19 的注释块),并以 <code>_MTP_SEED_OFFSET</code> 区分 draft/target 随机流(fused_sample.py:15)。</p>
    </div>

    <div class="card reveal" style="margin-bottom:18px">
      <h3><span class="ico">🪞</span>prepare_cp_mirror:前缀扫描 + PDL 串联的输出并行 scatter</h3>
      <p>上下文并行的镜像布局要求把「每序列长度 → 各压缩比下的前缀和 → 正/反向索引」一次算完。<code>prepare_cp_mirror_tl</code>(cuda/prepare_cp_mirror.py:16)用第一段 kernel 逐行做 chunked <code>T.cumsum</code> 前缀扫描,第二段 kernel 以「输出并行 scatter」填充索引——长序列可以占多个 block 而不是在一个序列 block 内串行;两段之间不靠全局同步,而是依赖启动(PDL)让第二段 <code>T.pdl_sync()</code> 等待前缀行写完(cuda/prepare_cp_mirror.py:162-173)。调用点:input_metadata.py:185 与 YoCo 边界 yoco.py:143。</p>
    </div>

    <div class="card reveal" style="margin-bottom:18px">
      <h3><span class="ico">📶</span>schedule_mtp_varlen 与 dflash:投机解码的数据面算子</h3>
      <p><code>compute_seqlens_q_by_confidence_rates_tl</code>(cuda/schedule_mtp_varlen.py:14)决定 MTP 变长解码每序列的 query 长度:第一阶段对每序列做置信率累乘,第二阶段用 <code>T.alloc_reducer</code> 的全复制 reducer 做并行 rank 计数(高置信优先、平局按平坦索引),统计进入 top 预算的步数(cuda/schedule_mtp_varlen.py:39-70)。<code>confidence_head_fused_tl</code>(cuda/dflash.py:12)是双 GEMV + sigmoid 的置信头,logit 除以温度后钳制到 ±60 再压缩;<code>dflash_input_store_tl</code>(cuda/dflash.py:82)把 hc_mult 个隐藏态求平均写入草稿输入。</p>
    </div>

    <div class="card reveal">
      <h3><span class="ico">🧱</span>asc/kv_quant:昇腾 SIMD 的寄存器级量化</h3>
      <p>NPU 后端没有 warp shuffle 原语,<code>asc/kv_quant.py</code> 改用 128-lane 向量寄存器:<code>make_kv_scale_impl</code>(asc/kv_quant.py:48)以查表法构造 e4m3 尺度的精确 FP32 倒数(表 <code>_RECIPROCAL_BITS</code> 由 <code>RNE(8/(8+m))</code> 预计算,asc/kv_quant.py:28),保证「量化所用的尺度 = cache 中存储的尺度」;<code>make_kv_quant_impl</code>(asc/kv_quant.py:97)消费两个 fp32 寄存器(128 个 BF16),完成 group16/32 的 <code>vcgmax</code> 组归约、稀疏 group32 尺度布局折叠,以及 sticky-bit FP4 打包——截断低位加粘滞位而非二次舍入,避免 FP4 中点附近的双舍入并保住精确平局(asc/kv_quant.py:170-194)。</p>
    </div>
  </section>

  <!-- ================= 7. SM 资源管理 ================= -->
  <section id="s7">
    <h2 class="sec"><span class="num">7</span>内核调度与 SM 资源管理</h2>
    <p class="lede">在同一颗 GPU 上,DeepEP 通信内核、DeepGEMM/TileKernels 计算内核与 NCCL 会争抢 SM。DeepInfer 的答案是一把「配额手术刀」:通信 SM 数显式配额 + 计算库 SM 上限动态下调 + PDL 消除 kernel 间空隙。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">⚖️</span>limit_num_sms 上下文管理器</h3>
        <p>进入时记录 <code>deep_gemm.get_num_sms()</code>,把 <code>tile_kernels</code> 与 <code>deep_gemm</code> 的可用 SM 同时下调 <code>prev - num_sms</code>,退出时恢复(userbuffer.py:39-51)。唯一生产调用点在 MoE combine 之前的 shared experts 前向:此时 dispatch/combine 通信内核占用通信 SM,共享专家计算被限制在剩余 SM 上,避免与通信争抢(mlp.py:602,<code>enabled=PLATFORM.is_gpu</code>)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧮</span>通信 SM 配额的自动推导</h3>
        <p>当 <code>DEEPINFER_USERBUFFER_COMM_SMS</code> 未设置(=0)时,DeepInfer 用 <code>EPBuffer.get_theoretical_num_sms(num_experts, num_topk)</code> 取理论通信 SM 数,再与 <code>device_num_sms - min(32, device_num_sms // 4)</code> 取小——即无论何时至少保留 <code>min(32, SM/4)</code> 个 SM 给计算,结果写回 env 供 dispatch/combine 复用(userbuffer.py:86-90)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🚀</span>PDL:程序化依赖启动</h3>
        <p>worker 启动时对 GPU 打开 <code>deep_gemm.set_pdl(True)</code> 与 <code>tile_kernels.set_pdl(True)</code>(runtime_config.py:64-66)。自研算子普遍以 <code>T.pdl_sync()</code> 声明依赖边界(store_kv_cache cuda:102、random_sampling cuda:240、prepare_cp_mirror cuda:131/:165、dflash cuda:58、convert_kv_index cuda:28、fused_transform cuda:255),让相邻 kernel 的 prologue 与上一 kernel 的 epilogue 重叠,消除 launch 间隙。</p>
      </div>
      <div class="card reveal">
        <h3><span class="ico">🔒</span>确定性算法开关</h3>
        <p>batch-invariant 模式或 NPU 平台下,统一打开 <code>deep_gemm.use_deterministic_algorithms(True)</code> 与 <code>tile_kernels.use_deterministic_algorithms(True)</code>(runtime_config.py:67-69);FlashMLA decode 也接受 <code>enable_batch_invariant</code>(attention_backend.py:141)。NPU 侧另有断言:batch invariant 尚未完整支持(runtime_config.py:61-63)。</p>
      </div>
    </div>

    <pre class="code reveal"><span class="filepath">deepinfer/model_executor/parallel_utils/userbuffer.py:39-51</span>
<span class="k">@contextmanager</span>
<span class="k">def</span> <span class="f">limit_num_sms</span>(num_sms: <span class="n">int</span>, enabled: <span class="n">bool</span> = <span class="k">True</span>) -&gt; <span class="n">Generator</span>[<span class="k">None</span>]:
    <span class="k">if not</span> enabled:
        <span class="k">yield</span>; <span class="k">return</span>
    prev_sms = deep_gemm.<span class="f">get_num_sms</span>()
    tile_kernels.<span class="f">set_num_sms</span>(prev_sms - num_sms)   <span class="c"># 计算库让出通信配额</span>
    deep_gemm.<span class="f">set_num_sms</span>(prev_sms - num_sms)
    <span class="k">try</span>:
        <span class="k">yield</span>
    <span class="k">finally</span>:                                     <span class="c"># 退出恢复,计算内核重新占满 SM</span>
        tile_kernels.<span class="f">set_num_sms</span>(prev_sms)
        deep_gemm.<span class="f">set_num_sms</span>(prev_sms)</pre>

    <div class="figure reveal">
      <svg viewBox="0 0 960 430" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="arr3" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto">
            <polygon points="0 0, 8 3.5, 0 7" fill="#a78bfa"/>
          </marker>
          <marker id="arr3b" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto">
            <polygon points="0 0, 8 3.5, 0 7" fill="#22d3ee"/>
          </marker>
        </defs>
        <text x="480" y="26" text-anchor="middle" class="figtitle">SM 竞争与配额分配:DeepEP 通信内核 vs DeepGEMM / TileKernels 计算内核</text>

        <!-- GPU box -->
        <rect class="node-gpu" x="40" y="46" width="880" height="210" rx="12" style="stroke-width:2"/>
        <text class="node-gpu-title" x="70" y="72">GPU(SM100)· SM 网格</text>
        <text class="figlabel" x="70" y="238">蓝色 = 计算内核(DeepGEMM / TileKernels / FlashMLA)</text>
        <text class="figlabel" x="620" y="238" fill="#a78bfa">紫色 = DeepEP dispatch / combine 通信内核</text>

        <!-- SM grid: 20 cols x 5 rows -->
        <g>
          <!-- comm SMs: first 4 columns -->
          <rect class="sm sm-comm" x="62"  y="88" width="34" height="24"/>
          <rect class="sm sm-comm" x="100" y="88" width="34" height="24" style="animation-delay:.15s"/>
          <rect class="sm sm-comm" x="138" y="88" width="34" height="24" style="animation-delay:.3s"/>
          <rect class="sm sm-comm" x="176" y="88" width="34" height="24" style="animation-delay:.45s"/>
          <rect class="sm sm-comm" x="62"  y="116" width="34" height="24" style="animation-delay:.6s"/>
          <rect class="sm sm-comm" x="100" y="116" width="34" height="24" style="animation-delay:.75s"/>
          <rect class="sm sm-comm" x="138" y="116" width="34" height="24" style="animation-delay:.9s"/>
          <rect class="sm sm-comm" x="176" y="116" width="34" height="24" style="animation-delay:1.05s"/>
          <rect class="sm sm-comm" x="62"  y="144" width="34" height="24" style="animation-delay:1.2s"/>
          <rect class="sm sm-comm" x="100" y="144" width="34" height="24" style="animation-delay:1.35s"/>
          <rect class="sm sm-comm" x="138" y="144" width="34" height="24" style="animation-delay:1.5s"/>
          <rect class="sm sm-comm" x="176" y="144" width="34" height="24" style="animation-delay:1.65s"/>
          <rect class="sm sm-comm" x="62"  y="172" width="34" height="24" style="animation-delay:1.8s"/>
          <rect class="sm sm-comm" x="100" y="172" width="34" height="24" style="animation-delay:1.95s"/>
          <rect class="sm sm-comm" x="138" y="172" width="34" height="24" style="animation-delay:2.1s"/>
          <rect class="sm sm-comm" x="176" y="172" width="34" height="24" style="animation-delay:2.25s"/>
          <rect class="sm sm-comm" x="62"  y="200" width="34" height="24" style="animation-delay:.4s"/>
          <rect class="sm sm-comm" x="100" y="200" width="34" height="24" style="animation-delay:.8s"/>
          <rect class="sm sm-comm" x="138" y="200" width="34" height="24" style="animation-delay:1.2s"/>
          <rect class="sm sm-comm" x="176" y="200" width="34" height="24" style="animation-delay:1.6s"/>
          <!-- compute SMs -->
          <g class="sm-plain-group">
            <rect class="sm sm-plain" x="230" y="88"  width="34" height="24" style="animation-delay:0s"/>
            <rect class="sm sm-plain" x="268" y="88"  width="34" height="24" style="animation-delay:.1s"/>
            <rect class="sm sm-plain" x="306" y="88"  width="34" height="24" style="animation-delay:.2s"/>
            <rect class="sm sm-plain" x="344" y="88"  width="34" height="24" style="animation-delay:.3s"/>
            <rect class="sm sm-plain" x="382" y="88"  width="34" height="24" style="animation-delay:.4s"/>
            <rect class="sm sm-plain" x="420" y="88"  width="34" height="24" style="animation-delay:.5s"/>
            <rect class="sm sm-plain" x="458" y="88"  width="34" height="24" style="animation-delay:.6s"/>
            <rect class="sm sm-plain" x="496" y="88"  width="34" height="24" style="animation-delay:.7s"/>
            <rect class="sm sm-plain" x="534" y="88"  width="34" height="24" style="animation-delay:.8s"/>
            <rect class="sm sm-plain" x="572" y="88"  width="34" height="24" style="animation-delay:.9s"/>
            <rect class="sm sm-plain" x="610" y="88"  width="34" height="24" style="animation-delay:1.0s"/>
            <rect class="sm sm-plain" x="648" y="88"  width="34" height="24" style="animation-delay:1.1s"/>
            <rect class="sm sm-plain" x="686" y="88"  width="34" height="24" style="animation-delay:1.2s"/>
            <rect class="sm sm-plain" x="724" y="88"  width="34" height="24" style="animation-delay:1.3s"/>
            <rect class="sm sm-plain" x="762" y="88"  width="34" height="24" style="animation-delay:1.4s"/>
            <rect class="sm sm-plain" x="800" y="88"  width="34" height="24" style="animation-delay:1.5s"/>
            <rect class="sm sm-plain" x="838" y="88"  width="34" height="24" style="animation-delay:1.6s"/>
            <rect class="sm sm-plain" x="230" y="116" width="34" height="24" style="animation-delay:.25s"/>
            <rect class="sm sm-plain" x="268" y="116" width="34" height="24" style="animation-delay:.35s"/>
            <rect class="sm sm-plain" x="306" y="116" width="34" height="24" style="animation-delay:.45s"/>
            <rect class="sm sm-plain" x="344" y="116" width="34" height="24" style="animation-delay:.55s"/>
            <rect class="sm sm-plain" x="382" y="116" width="34" height="24" style="animation-delay:.65s"/>
            <rect class="sm sm-plain" x="420" y="116" width="34" height="24" style="animation-delay:.75s"/>
            <rect class="sm sm-plain" x="458" y="116" width="34" height="24" style="animation-delay:.85s"/>
            <rect class="sm sm-plain" x="496" y="116" width="34" height="24" style="animation-delay:.95s"/>
            <rect class="sm sm-plain" x="534" y="116" width="34" height="24" style="animation-delay:1.05s"/>
            <rect class="sm sm-plain" x="572" y="116" width="34" height="24" style="animation-delay:1.15s"/>
            <rect class="sm sm-plain" x="610" y="116" width="34" height="24" style="animation-delay:1.25s"/>
            <rect class="sm sm-plain" x="648" y="116" width="34" height="24" style="animation-delay:1.35s"/>
            <rect class="sm sm-plain" x="686" y="116" width="34" height="24" style="animation-delay:1.45s"/>
            <rect class="sm sm-plain" x="724" y="116" width="34" height="24" style="animation-delay:1.55s"/>
            <rect class="sm sm-plain" x="762" y="116" width="34" height="24" style="animation-delay:1.65s"/>
            <rect class="sm sm-plain" x="800" y="116" width="34" height="24" style="animation-delay:1.75s"/>
            <rect class="sm sm-plain" x="838" y="116" width="34" height="24" style="animation-delay:1.85s"/>
            <rect class="sm sm-plain" x="230" y="144" width="34" height="24" style="animation-delay:.5s"/>
            <rect class="sm sm-plain" x="268" y="144" width="34" height="24" style="animation-delay:.6s"/>
            <rect class="sm sm-plain" x="306" y="144" width="34" height="24" style="animation-delay:.7s"/>
            <rect class="sm sm-plain" x="344" y="144" width="34" height="24" style="animation-delay:.8s"/>
            <rect class="sm sm-plain" x="382" y="144" width="34" height="24" style="animation-delay:.9s"/>
            <rect class="sm sm-plain" x="420" y="144" width="34" height="24" style="animation-delay:1.0s"/>
            <rect class="sm sm-plain" x="458" y="144" width="34" height="24" style="animation-delay:1.1s"/>
            <rect class="sm sm-plain" x="496" y="144" width="34" height="24" style="animation-delay:1.2s"/>
            <rect class="sm sm-plain" x="534" y="144" width="34" height="24" style="animation-delay:1.3s"/>
            <rect class="sm sm-plain" x="572" y="144" width="34" height="24" style="animation-delay:1.4s"/>
            <rect class="sm sm-plain" x="610" y="144" width="34" height="24" style="animation-delay:1.5s"/>
            <rect class="sm sm-plain" x="648" y="144" width="34" height="24" style="animation-delay:1.6s"/>
            <rect class="sm sm-plain" x="686" y="144" width="34" height="24" style="animation-delay:1.7s"/>
            <rect class="sm sm-plain" x="724" y="144" width="34" height="24" style="animation-delay:1.8s"/>
            <rect class="sm sm-plain" x="762" y="144" width="34" height="24" style="animation-delay:1.9s"/>
            <rect class="sm sm-plain" x="800" y="144" width="34" height="24" style="animation-delay:2.0s"/>
            <rect class="sm sm-plain" x="838" y="144" width="34" height="24" style="animation-delay:2.1s"/>
            <rect class="sm sm-plain" x="230" y="172" width="34" height="24" style="animation-delay:.15s"/>
            <rect class="sm sm-plain" x="268" y="172" width="34" height="24" style="animation-delay:.3s"/>
            <rect class="sm sm-plain" x="306" y="172" width="34" height="24" style="animation-delay:.45s"/>
            <rect class="sm sm-plain" x="344" y="172" width="34" height="24" style="animation-delay:.6s"/>
            <rect class="sm sm-plain" x="382" y="172" width="34" height="24" style="animation-delay:.75s"/>
            <rect class="sm sm-plain" x="420" y="172" width="34" height="24" style="animation-delay:.9s"/>
            <rect class="sm sm-plain" x="458" y="172" width="34" height="24" style="animation-delay:1.05s"/>
            <rect class="sm sm-plain" x="496" y="172" width="34" height="24" style="animation-delay:1.2s"/>
            <rect class="sm sm-plain" x="534" y="172" width="34" height="24" style="animation-delay:1.35s"/>
            <rect class="sm sm-plain" x="572" y="172" width="34" height="24" style="animation-delay:1.5s"/>
            <rect class="sm sm-plain" x="610" y="172" width="34" height="24" style="animation-delay:1.65s"/>
            <rect class="sm sm-plain" x="648" y="172" width="34" height="24" style="animation-delay:1.8s"/>
            <rect class="sm sm-plain" x="686" y="172" width="34" height="24" style="animation-delay:1.95s"/>
            <rect class="sm sm-plain" x="724" y="172" width="34" height="24" style="animation-delay:2.1s"/>
            <rect class="sm sm-plain" x="762" y="172" width="34" height="24" style="animation-delay:2.25s"/>
            <rect class="sm sm-plain" x="800" y="172" width="34" height="24" style="animation-delay:2.4s"/>
            <rect class="sm sm-plain" x="838" y="172" width="34" height="24" style="animation-delay:2.55s"/>
            <rect class="sm sm-plain" x="230" y="200" width="34" height="24" style="animation-delay:.7s"/>
            <rect class="sm sm-plain" x="268" y="200" width="34" height="24" style="animation-delay:.85s"/>
            <rect class="sm sm-plain" x="306" y="200" width="34" height="24" style="animation-delay:1.0s"/>
            <rect class="sm sm-plain" x="344" y="200" width="34" height="24" style="animation-delay:1.15s"/>
            <rect class="sm sm-plain" x="382" y="200" width="34" height="24" style="animation-delay:1.3s"/>
            <rect class="sm sm-plain" x="420" y="200" width="34" height="24" style="animation-delay:1.45s"/>
            <rect class="sm sm-plain" x="458" y="200" width="34" height="24" style="animation-delay:1.6s"/>
            <rect class="sm sm-plain" x="496" y="200" width="34" height="24" style="animation-delay:1.75s"/>
            <rect class="sm sm-plain" x="534" y="200" width="34" height="24" style="animation-delay:1.9s"/>
            <rect class="sm sm-plain" x="572" y="200" width="34" height="24" style="animation-delay:2.05s"/>
            <rect class="sm sm-plain" x="610" y="200" width="34" height="24" style="animation-delay:2.2s"/>
            <rect class="sm sm-plain" x="648" y="200" width="34" height="24" style="animation-delay:2.35s"/>
            <rect class="sm sm-plain" x="686" y="200" width="34" height="24" style="animation-delay:2.5s"/>
            <rect class="sm sm-plain" x="724" y="200" width="34" height="24" style="animation-delay:2.65s"/>
            <rect class="sm sm-plain" x="762" y="200" width="34" height="24" style="animation-delay:2.8s"/>
            <rect class="sm sm-plain" x="800" y="200" width="34" height="24" style="animation-delay:2.95s"/>
            <rect class="sm sm-plain" x="838" y="200" width="34" height="24" style="animation-delay:3.1s"/>
          </g>
        </g>
        <text class="phase-tag" x="120" y="80" text-anchor="middle" fill="#a78bfa">DEEPINFER_USERBUFFER_COMM_SMS</text>

        <!-- phase timeline -->
        <g>
          <text class="phase-tag" x="150" y="292" text-anchor="middle">Phase 1 · 纯计算(limit_num_sms 外)</text>
          <text class="phase-tag" x="480" y="292" text-anchor="middle" style="animation-delay:1.5s">Phase 2 · dispatch/combine:通信 SM 点亮,计算库 SM 上限下调</text>
          <text class="phase-tag" x="830" y="292" text-anchor="middle" style="animation-delay:3s">Phase 3 · 退出恢复:计算重新占满</text>
          <line class="flowline" x1="40" y1="305" x2="920" y2="305" stroke="#4f8cff" stroke-width="2"/>
        </g>

        <!-- two lanes -->
        <g>
          <rect class="node-gpu" x="40" y="330" width="420" height="34" rx="8" style="stroke:#a78bfa"/>
          <text class="figlabel" x="250" y="351" text-anchor="middle" fill="#a78bfa">DeepEP dispatch / combine lane(num_sms=DEEPINFER_USERBUFFER_COMM_SMS,mlp.py:471/:504)</text>
          <circle r="5" class="token-dot barrow" style="fill:#a78bfa">
            <animateMotion dur="2.6s" repeatCount="indefinite" path="M50,347 L450,347"/>
          </circle>
          <circle r="4" class="token-dot barrow" style="fill:#a78bfa">
            <animateMotion dur="2.6s" begin="1.3s" repeatCount="indefinite" path="M50,347 L450,347"/>
          </circle>
        </g>
        <g>
          <rect class="node-gpu" x="500" y="330" width="420" height="34" rx="8" style="stroke:#22d3ee"/>
          <text class="figlabel" x="710" y="351" text-anchor="middle" fill="#22d3ee">计算 lane:set_num_sms(prev - num_sms) → shared_forward(mlp.py:602)</text>
          <circle r="5" class="token-dot barrow">
            <animateMotion dur="3.2s" begin=".4s" repeatCount="indefinite" path="M510,347 L910,347"/>
          </circle>
          <circle r="4" class="token-dot barrow">
            <animateMotion dur="3.2s" begin="2s" repeatCount="indefinite" path="M510,347 L910,347"/>
          </circle>
        </g>

        <!-- arrows from GPU to lanes -->
        <line class="flowline" x1="140" y1="258" x2="220" y2="326" stroke="#a78bfa" stroke-width="1.6" marker-end="url(#arr3)"/>
        <line class="flowline" x1="600" y1="258" x2="720" y2="326" stroke="#22d3ee" stroke-width="1.6" marker-end="url(#arr3b)"/>

        <text class="figlabel" x="480" y="400" text-anchor="middle">NCCL 侧另有独立配额:DEEPINFER_NCCL_NUM_SMS(默认 32)同时设为 ProcessGroupNCCL 的 max_ctas/min_ctas(platform.py:80-83)</text>
        <text class="figlabel" x="480" y="418" text-anchor="middle" fill="#fbbf24">自动推导:min(理论通信 SM, 设备 SM − min(32, SM/4)) —— 无论如何都给计算留下保底(userbuffer.py:86-90)</text>
      </svg>
      <div class="cap">图 7-1 · SM 配额动画:左列 SM 在通信相位周期性点亮为 DeepEP 所用,其余 SM 呼吸为计算态;limit_num_sms 让计算库的 SM 上限同步收缩/恢复,避免超订</div>
    </div>
  </section>

  <!-- ================= 8. JIT 缓存 ================= -->
  <section id="s8">
    <h2 class="sec"><span class="num">8</span>JIT 编译缓存与预热目录</h2>
    <p class="lede">TileLang / DeepGEMM / DeepEP 都是 JIT 编译库,首次运行要生成 CUDA/Ascend kernel。DeepInfer 用一个根目录统一下沉三类缓存,并把镜像内预热目录串在查找路径上,使 miss 的 kernel 编译到第一个目录。</p>

    <pre class="code reveal"><span class="filepath">deepinfer/worker/runtime_config.py:42-51</span>
<span class="c"># JIT kernel 缓存:根目录由 DEEPINFER_JIT_CACHE_DIR 指定,tilelang / deep_gemm / deep_ep 各用其下</span>
<span class="c"># 的子目录;镜像内的预热目录附在其后,deep_gemm / deep_ep 会依次查找、把 miss 编译到第一个目录。</span>
<span class="c"># 未设置根目录时不改写这三个库的默认缓存行为。</span>
jit_cache_root = envs.DEEPINFER_JIT_CACHE_DIR
<span class="k">if</span> jit_cache_root:
    warmup_suffix = <span class="s">""</span>.<span class="f">join</span>(<span class="s">f":{jit_cache_root}/{name}"</span> <span class="k">for</span> name <span class="k">in</span> _JIT_WARMUP_DIRS)
    os.environ[<span class="s">"TILELANG_CACHE_DIR"</span>]    = <span class="s">f"{jit_cache_root}/tilelang"</span>
    os.environ[<span class="s">"DG_JIT_CACHE_DIR"</span>]      = <span class="s">f"{jit_cache_root}/deep_gemm{warmup_suffix}"</span>
    os.environ[<span class="s">"EP_JIT_CACHE_DIR"</span>]       = <span class="s">f"{jit_cache_root}/deep_ep{warmup_suffix}"</span></pre>

    <ul class="feat reveal">
      <li>预热目录固定为 <code>test_warmup</code> 与 <code>history_warmup</code>(<code>_JIT_WARMUP_DIRS</code>,runtime_config.py:10),以冒号分隔追加在 DeepGEMM / DeepEP 的缓存路径之后——命中即免编译,miss 则写入主目录。</li>
      <li>仅设置 <code>DEEPINFER_JIT_CACHE_DIR</code> 一个变量(environ.py:112),三库目录名不可配;未设置时保持各库默认行为,便于本地开发。</li>
      <li>NPU 侧另有 <code>TILELANG_DEFAULT_TARGET=ascend</code> 的 setdefault(platform.py:120-128):因为 <code>transfer_to_npu</code> 会让 <code>torch.cuda.is_available()</code> 在 NPU 主机上返回 True,TileLang 的自动探测会把内核编成 CUDA,必须显式钉死目标(仍允许外部 <code>TILELANG_DEFAULT_TARGET</code> 覆盖)。</li>
      <li>worker 环境的其余内核相关 env:<code>EP_AVOID_RECORD_STREAM=1</code>、GPU 侧 <code>NCCL_NO_CACHE</code> / <code>NCCL_PXN_DISABLE=1</code> / <code>NCCL_CUMEM_ENABLE=1</code> / <code>NCCL_GIN_ERROR_QUERY_SEC=432000</code>(runtime_config.py:33-40)。</li>
    </ul>
  </section>

  <!-- ================= 9. 双平台映射 ================= -->
  <section id="s9">
    <h2 class="sec"><span class="num">9</span>NVIDIA / 昇腾双平台内核映射</h2>
    <p class="lede">DeepInfer 用「同一 Python 接口 + 双后端实现 + 少量垫片」覆盖 SM100 GPU 与昇腾 950 NPU:构建期选择 vendor 变体,运行期由 Platform 对象决定 TileLang 后端、SF 类型与分布式后端。</p>

    <table class="tbl reveal">
      <tr><th>维度</th><th>NVIDIA GPU(SM100)</th><th>华为昇腾 950 NPU</th><th>代码位置</th></tr>
      <tr><td>vendor 通信/GEMM</td><td><code>DeepEP</code> / <code>DeepGEMM</code></td><td><code>DeepEP-Ascend</code> / <code>DeepGEMM-Ascend</code>(Python 包名相同)</td><td>scripts/build_vendor.sh:14-21</td></tr>
      <tr><td>TileLang 算子后端</td><td><code>tilelang_ops_backend = "cuda"</code></td><td><code>tilelang_ops_backend = "asc"</code></td><td>platform.py:57 / :88</td></tr>
      <tr><td>TileLang 编译目标</td><td>CUDA(默认探测)</td><td><code>TILELANG_DEFAULT_TARGET=ascend</code>(setdefault)</td><td>platform.py:128</td></tr>
      <tr><td>FP8 SF 类型</td><td><code>torch.int32</code>(4 个 ue8m0 打包)</td><td><code>torch.int16</code>(2 个 ue8m0 打包)</td><td>platform.py:63 / :138;engram.py:27-32</td></tr>
      <tr><td>分布式后端</td><td>NCCL(<code>max_ctas/min_ctas=DEEPINFER_NCCL_NUM_SMS</code>)</td><td>HCCL(<code>HCCL_BUFFSIZE=16</code>、超时/端口 env、<code>PYTORCH_NPU_ALLOC_CONF=expandable_segments:True</code>)</td><td>platform.py:58/:80-83 与 :89/:105-115</td></tr>
      <tr><td>KV 量化原语</td><td>FP8/FP4 量化内嵌于 <code>store_kv_cache_tl</code> / <code>fused_transform</code>(warp shuffle 归约)</td><td>独立的 <code>asc/kv_quant.py</code> SIMD 宏族(group16/32、倒数 LUT、sticky-bit FP4)+ <code>rstd_1ulp</code></td><td>cuda/store_kv_cache.py:10;asc/kv_quant.py:48/:97</td></tr>
      <tr><td>融合注意力内核</td><td><code>fused_norm_rope_attn_rope_cast</code> 可用(需 heads∈{64,128})</td><td>该融合路径关闭(<code>PLATFORM.is_gpu</code> 条件),走 TileLang 变换 + FlashMLA 常规入口</td><td>attn.py:87-92</td></tr>
      <tr><td>SM 配额管理</td><td><code>limit_num_sms</code> 生效</td><td>显式禁用(<code>enabled=PLATFORM.is_gpu</code>)</td><td>mlp.py:602;userbuffer.py:40-42</td></tr>
      <tr><td>mega-MoE</td><td>NVLink 域内启用</td><td>仅 <code>fp8xfp4</code> 组合启用</td><td>mlp.py:184-188</td></tr>
      <tr><td>top-k / ViT 注意力</td><td>DeepSelect / flash_attn 原生</td><td><code>npu_ops</code> 垫片:采样 top-k 回退 torch、索引器用真内核;ViT 用 <code>npu_fusion_attention</code></td><td>npu_ops/__init__.py:3-11;npu_ops/deep_select.py:21-27;npu_ops/vit_attn.py:9-31</td></tr>
      <tr><td>scatter 垫片</td><td>直接 index_put</td><td><code>_slot_scatter</code> 以平铺一维视图绕开 IndexPutV2 的 32 位偏移回绕</td><td>tilelang_ops/store_kv_cache.py:81-92</td></tr>
      <tr><td>host 内存 pin</td><td><code>cudaHostRegister</code></td><td><code>aclrtHostRegisterV2(ACL_HOST_REG_PINNED)</code>(ctypes 解析 libascendcl.so,重注册 507910 静默)</td><td>platform.py:65-73 / :195-207</td></tr>
      <tr><td>Engram 存储</td><td>CPU RDMA 存储(可强制 GPU)</td><td>默认强制 GPU 存储(<code>DEEPINFER_ENGRAM_FORCE_GPU_STORAGE</code> 在 ascend 下为真)</td><td>environ.py:154;userbuffer.py:148</td></tr>
      <tr><td>确定性算法</td><td>batch-invariant 时开启</td><td>始终开启(防 CI 数值不稳定),且断言不支持 batch-invariant</td><td>runtime_config.py:61-63 / :67-69</td></tr>
    </table>

    <div class="note reveal">
      <b>环境一致性门禁:</b>NPU 平台要求 <code>CUDA_VISIBLE_DEVICES</code> 与 <code>ASCEND_RT_VISIBLE_DEVICES</code> 一致(未设前者时自动沿用后者并告警),并借助 <code>torch_npu.contrib.transfer_to_npu</code> 把 <code>torch.cuda.*</code> 映射到 <code>torch.npu.*</code>,让 cuda 风格代码读取 <code>.cuda_stream</code> 时拿到底层 NPU 流(platform.py:91-137)。
    </div>
  </section>

  <!-- ================= 10. 配置项 ================= -->
  <section id="s10">
    <h2 class="sec"><span class="num">10</span>配置项参考</h2>
    <p class="lede">与内核运行时直接相关的环境变量(定义集中在 deepinfer/environ.py,除非注明派生)。</p>
    <table class="tbl reveal">
      <tr><th>环境变量</th><th>默认</th><th>作用</th><th>定义 / 生效位置</th></tr>
      <tr><td><code>DEEPINFER_JIT_CACHE_DIR</code></td><td>未设置</td><td>JIT 缓存根目录;设置后派生 <code>TILELANG_CACHE_DIR</code> / <code>DG_JIT_CACHE_DIR</code> / <code>EP_JIT_CACHE_DIR</code> 及 <code>test_warmup</code>/<code>history_warmup</code> 预热路径</td><td>environ.py:112;runtime_config.py:45-51</td></tr>
      <tr><td><code>DEEPINFER_USERBUFFER_COMM_SMS</code></td><td>0(自动推导)</td><td>DeepEP dispatch/combine 的通信 SM 数;0 时按理论值与设备 SM 减保底取小并写回</td><td>environ.py:116;userbuffer.py:86-90;mlp.py:471/:504</td></tr>
      <tr><td><code>DEEPINFER_NCCL_NUM_SMS</code></td><td>32</td><td>NCCL 通信内核 SM 配额(同时设为 max_ctas 与 min_ctas)</td><td>environ.py:115;platform.py:80-83</td></tr>
      <tr><td><code>DEEPINFER_COMPUTE_SUM_SMALLER_PROBS</code></td><td>0</td><td>开启采样统计内核 <code>sum_smaller_probs</code>(接受 token 外的较小概率和)</td><td>environ.py:111;sampler.py:104;llm_engine.py:750</td></tr>
      <tr><td><code>DEEPINFER_SAMPLER_FORCE_TOPK</code></td><td>0</td><td>采样前把 logits 裁剪到 top-k 空间(DeepSelect topk)</td><td>environ.py:157;sampler_utils.py:68/:167</td></tr>
      <tr><td><code>DEEPINFER_BATCH_INVARIANT</code></td><td>0</td><td>批次不变模式:开启 DeepGEMM/TileKernels 确定性算法、FlashMLA <code>enable_batch_invariant</code>、限制 EP 多次归约</td><td>environ.py:204;runtime_config.py:67-69;userbuffer.py:79</td></tr>
      <tr><td><code>DEEPINFER_EXPERT_REARRANGEMENT_STEP_INTERVAL</code></td><td>0</td><td>专家重排间隔;与 batch-invariant 同时开启时禁用 <code>allow_multiple_reduction</code></td><td>environ.py:123;userbuffer.py:79</td></tr>
      <tr><td><code>DEEPINFER_ENGRAM_FORCE_GPU_STORAGE</code></td><td>ascend 平台为真</td><td>EngramBuffer 强制 GPU RDMA 存储</td><td>environ.py:154;userbuffer.py:148</td></tr>
      <tr><td><code>DEEPINFER_DISABLE_SYNC_GUARD</code></td><td>0</td><td>debug 用:关闭 forward/sampling launch 期的 CPU-GPU 同步守卫</td><td>environ.py:205</td></tr>
      <tr><td><code>TILELANG_CACHE_DIR</code></td><td>派生</td><td>TileLang JIT 缓存(= 根目录/tilelang)</td><td>runtime_config.py:49</td></tr>
      <tr><td><code>DG_JIT_CACHE_DIR</code></td><td>派生</td><td>DeepGEMM JIT 缓存(= 根目录/deep_gemm + 预热目录)</td><td>runtime_config.py:50</td></tr>
      <tr><td><code>EP_JIT_CACHE_DIR</code></td><td>派生</td><td>DeepEP JIT 缓存(= 根目录/deep_ep + 预热目录)</td><td>runtime_config.py:51</td></tr>
      <tr><td><code>TILELANG_DEFAULT_TARGET</code></td><td>NPU 平台 setdefault 为 <code>ascend</code></td><td>钉死 TileLang 编译目标,防止 NPU 主机上被误探测为 CUDA</td><td>platform.py:128</td></tr>
      <tr><td><code>EP_AVOID_RECORD_STREAM</code></td><td>worker 强制 1</td><td>DeepEP 缓冲避免 record stream,配合显式生命周期管理</td><td>runtime_config.py:33</td></tr>
      <tr><td><code>DEEPINFER_FUSED_SAMPLE_STRESS_TEST</code></td><td>1</td><td>(测试)fused_sample 拒绝采样分布压测的轮数倍率</td><td>fused_sample.py:530</td></tr>
    </table>
  </section>

  <!-- ================= 11. 总结 ================= -->
  <section id="s11">
    <h2 class="sec"><span class="num">11</span>总结</h2>
    <p class="lede">「优化内核与模型/采样运行时」是 DeepInfer 性能叙事的地基,可以浓缩为四条设计决策。</p>
    <div class="timeline reveal">
      <div class="tl-item">
        <div class="tl-date">决策一 · 复用 DeepSeek 内核栈,自研只做缺口</div>
        <div class="tl-body">重计算交给 vendor 四大件(FlashMLA/DeepGEMM/DeepEP/DeepSelect)与 tile_kernels;自研 tilelang_ops 的 30+ 算子几乎全是「调度元数据、数据搬运、采样统计」这类 glue 计算——它们才是框架真正的差异化成本所在,且每个都带 PyTorch 参考实现与逐 bit 级测试(如 rgb_pad_to_patches 禁 FMA 对齐 CPU 参考,cuda/image_embed_ops.py:60-63)。</div>
      </div>
      <div class="tl-item">
        <div class="tl-date">决策二 · 一处分发,双端同构</div>
        <div class="tl-body">平台差异被压缩到三个点:构建期的 vendor 变体选择、运行期的 <code>PLATFORM.tilelang_ops_backend</code>(ops.py:15-22)与 <code>fp8_sf_type</code>(GPU int32 / NPU int16,platform.py:63/:138)。接口层(如 <code>store_kv_cache</code>、<code>fused_sample</code>)在两个后端之间自由迁移,npu_ops 只保留极少量垫片。</div>
      </div>
      <div class="tl-item">
        <div class="tl-date">决策三 · SM 是显式预算,不是隐式争抢</div>
        <div class="tl-body">DeepEP 通信 SM、NCCL SM、计算库 SM 上限三者都有显式配额与自动推导(userbuffer.py:86-90、platform.py:80-83、mlp.py:602),PDL(runtime_config.py:64-66)再吃掉 kernel 间空隙——这让「通信与计算重叠」从运气变成合约。</div>
      </div>
      <div class="tl-item">
        <div class="tl-date">决策四 · 部署友好优先</div>
        <div class="tl-body">统一 JIT 缓存根目录 + 镜像内预热目录(runtime_config.py:42-51)让多机冷启动不必重复编译;确定性算法开关(runtime_config.py:67-69)与 batch-invariant 特性(系列第 ⑥ 篇)共享同一套底层机制,保证数值可复现。</div>
      </div>
    </div>
    <div class="note good reveal">
      <b>延伸阅读:</b>这些内核如何被并行策略编排见第 ② 篇(DP/CP/EP+EPLB);投机解码(DSpark/DFlash/MTP)对采样与调度算子的依赖见第 ③ 篇;SWA 有界重放对 state cache 算子的使用见第 ④ 篇;通信内核的跨卡行为详见第 ⑧-⑩ 篇。
    </div>
  </section>

  <div class="pgnav">
    <span>DeepInfer 代码分析系列 · 由 ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/deepinfer/">← 返回系列总览</a></span>
  </div>
<script>
// 滚动显现动画
const io=new IntersectionObserver(es=>{es.forEach(e=>{if(e.isIntersecting){e.target.classList.add('on');io.unobserve(e.target)}})},{threshold:.12});
document.querySelectorAll('.reveal').forEach(el=>io.observe(el));
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>DeepInfer 深度解析</title><link>https://hccl.club/docs/inference-engines/deepinfer/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/</guid><description>&lt;p>DeepInfer 是支撑 DeepSeek 大规模生产服务的高性能推理框架,本系列从源码出发,逐一拆解其八大重点特性,并穷尽分析 NCCL 使用场景、PR 合入历史与全部跨卡通信行为。&lt;/p></description></item><item><title>并行策略:DP / CP / EP + EPLB</title><link>https://hccl.club/docs/inference-engines/deepinfer/02-parallelism/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/02-parallelism/</guid><description><![CDATA[<div class="fwdoc">
<style>
.fwdoc{--bg:#0b1020; --bg2:#0f1729; --panel:#141d33; --panel2:#1a2440;
  --border:#263352; --text:#dbe4f5; --muted:#8ea0c2;
  --accent:#4f8cff; --accent2:#22d3ee; --good:#34d399; --warn:#fbbf24; --bad:#f87171; --purple:#a78bfa;
  --code-bg:#0d1424; --radius:14px;
  --serif:"Noto Serif SC","Songti SC",serif;}
.fwdoc *{box-sizing:border-box;margin:0;padding:0}
.fwdoc{background:linear-gradient(160deg,var(--bg) 0%,var(--bg2) 60%,#0a0f1e 100%);color:var(--text);
  font-family:"PingFang SC","Microsoft YaHei","Segoe UI",system-ui,sans-serif;line-height:1.75;}
.fwdoc{flex:1;min-width:0;padding:36px 48px 80px}
@media(max-width:960px){.fwdoc{padding:24px 18px 60px}}
.fwdoc .hero{position:relative;border-radius:var(--radius);overflow:hidden;padding:46px 44px;margin-bottom:34px;
  background:radial-gradient(1200px 400px at 15% -20%,rgba(79,140,255,.28),transparent 60%),
             radial-gradient(900px 380px at 95% 0%,rgba(167,139,250,.20),transparent 55%),
             linear-gradient(135deg,#16213e,#101a30);border:1px solid var(--border)}
.fwdoc .hero .crumb{font-size:12px;color:var(--accent2);letter-spacing:1px;margin-bottom:12px}
.fwdoc .hero h1{font-size:34px;color:#fff;font-weight:800;letter-spacing:.5px;margin-bottom:10px}
.fwdoc .hero p.desc{color:var(--muted);max-width:760px;font-size:15px}
.fwdoc .hero .tags{margin-top:18px;display:flex;gap:10px;flex-wrap:wrap}
.fwdoc .hero .tag{font-size:12px;padding:4px 14px;border-radius:999px;border:1px solid var(--border);
  background:rgba(79,140,255,.10);color:var(--accent2)}
.fwdoc .tag.good{border-color:rgba(52,211,153,.4);color:var(--good);background:rgba(52,211,153,.08)}
.fwdoc .tag.warn{border-color:rgba(251,191,36,.4);color:var(--warn);background:rgba(251,191,36,.08)}
.fwdoc section{margin-bottom:44px;scroll-margin-top:20px}
.fwdoc h2.sec{display:flex;align-items:center;gap:12px;font-size:23px;color:#fff;margin-bottom:6px;padding-bottom:10px;border-bottom:1px solid var(--border)}
.fwdoc h2.sec .num{display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:10px;flex-shrink:0;
  background:linear-gradient(135deg,var(--accent),var(--purple));color:#fff;font-size:15px;font-weight:800}
.fwdoc .lede{color:var(--muted);font-size:14px;margin-bottom:20px}
.fwdoc .grid{display:grid;gap:18px}
.fwdoc .grid.c2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}
.fwdoc .grid.c3{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}
.fwdoc .card{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:var(--radius);padding:22px 24px;transition:transform .3s,border-color .3s,box-shadow .3s}
.fwdoc .card:hover{transform:translateY(-3px);border-color:rgba(79,140,255,.55);box-shadow:0 12px 34px -14px rgba(79,140,255,.35)}
.fwdoc .card h3{font-size:16.5px;color:#fff;margin-bottom:8px;display:flex;align-items:center;gap:9px}
.fwdoc .card h3 .ico{width:26px;height:26px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;
  background:rgba(79,140,255,.16);font-size:14px;flex-shrink:0}
.fwdoc .card p{font-size:13.5px;color:var(--muted)}
.fwdoc .card p code,.fwdoc .inline-code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1.5px 7px;border-radius:6px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px}
.fwdoc ul.feat{list-style:none}
.fwdoc ul.feat li{padding:9px 0 9px 30px;position:relative;font-size:14px;color:var(--text);border-bottom:1px dashed rgba(38,51,82,.6)}
.fwdoc ul.feat li:last-child{border-bottom:none}
.fwdoc ul.feat li::before{content:"▸";position:absolute;left:8px;color:var(--accent);font-weight:700;animation:fw-blink 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
@keyframes fw-blink{0%,100%{opacity:.35}50%{opacity:1}}
.fwdoc pre.code{background:var(--code-bg);border:1px solid var(--border);border-radius:12px;padding:18px 20px;
  overflow-x:auto;font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px;line-height:1.65;margin:14px 0;position:relative}
.fwdoc pre.code::before{content:"● ● ●";display:block;color:#3a4a70;font-size:10px;letter-spacing:3px;margin-bottom:10px}
.fwdoc pre.code .k{color:#c792ea}
.fwdoc pre.code .s{color:#89ddff}
.fwdoc pre.code .c{color:#5d7294;font-style:italic}
.fwdoc pre.code .f{color:#82aaff}
.fwdoc pre.code .n{color:#f78c6c}
.fwdoc pre.code .h{color:#ffcb6b}
.fwdoc .filepath{font-family:"JetBrains Mono",Consolas,monospace;font-size:11.5px;color:var(--accent2);
  background:rgba(34,211,238,.08);border:1px solid rgba(34,211,238,.25);border-radius:6px;padding:2px 10px;display:inline-block;margin-bottom:4px}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border)}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px}
.fwdoc table.tbl td{padding:10px 14px;border-top:1px solid var(--border);color:var(--text);vertical-align:top}
.fwdoc table.tbl tr{transition:background .2s}
.fwdoc table.tbl tr:nth-child(even) td{background:rgba(20,29,51,.5)}
.fwdoc table.tbl tr:hover td{background:rgba(79,140,255,.10)}
.fwdoc table.tbl td code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;font-family:Consolas,monospace;font-size:12px}
.fwdoc .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px}
.fwdoc .badge.merged{background:rgba(52,211,153,.15);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.open{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.closed{background:rgba(248,113,113,.13);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.nccl{background:rgba(251,191,36,.12);color:var(--warn);border:1px solid rgba(251,191,36,.4)}
.fwdoc .badge.hccl{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .badge.deepep{background:rgba(34,211,238,.12);color:var(--accent2);border:1px solid rgba(34,211,238,.4)}
.fwdoc .reveal{opacity:0;transform:translateY(26px);transition:opacity .7s cubic-bezier(.2,.7,.3,1),transform .7s cubic-bezier(.2,.7,.3,1)}
.fwdoc .reveal.on{opacity:1;transform:none}
.fwdoc .reveal.d1{transition-delay:.12s}
.fwdoc .reveal.d2{transition-delay:.24s}
.fwdoc .reveal.d3{transition-delay:.36s}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:20px;margin:18px 0;position:relative;overflow:hidden}
.fwdoc .figure .cap{text-align:center;font-size:12.5px;color:var(--muted);margin-top:10px}
.fwdoc .figure svg{width:100%;height:auto;display:block}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-flow 1.2s linear infinite}
@keyframes fw-flow{to{stroke-dashoffset:-14}}
.fwdoc .pulse{animation:fw-pulse 2s ease-in-out infinite;transform-origin:center}
@keyframes fw-pulse{0%,100%{opacity:.45;transform:scale(1)}50%{opacity:1;transform:scale(1.06)}}
.fwdoc .node-gpu{fill:#16233f;stroke:#4f8cff;stroke-width:1.6;rx:10}
.fwdoc .node-gpu-title{fill:#dbe4f5;font-size:13px;font-weight:700}
.fwdoc .token-dot{fill:#22d3ee}
.fwdoc .barrow{filter:drop-shadow(0 0 6px rgba(34,211,238,.7))}
.fwdoc .timeline{position:relative;padding-left:34px}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .tl-item{position:relative;margin-bottom:20px}
.fwdoc .tl-item::before{content:"";position:absolute;left:-30px;top:7px;width:12px;height:12px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.18);animation:fw-pulse 2.4s infinite}
.fwdoc .tl-item .tl-date{font-size:11.5px;color:var(--accent2);letter-spacing:.5px}
.fwdoc .tl-item .tl-body{font-size:13.5px;color:var(--text);margin-top:3px}
.fwdoc .note{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13px;color:var(--text);margin:16px 0}
.fwdoc .note.warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .note.good{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .note b{color:#fff}
.fwdoc .pgnav{margin-top:60px;padding-top:20px;border-top:1px solid var(--border);color:#5a6b92;font-size:12px;
  display:flex;justify-content:space-between;flex-wrap:wrap;gap:10px}
.fwdoc .pgnav a{color:var(--accent2);text-decoration:none}
/* ===== 导入面板附加样式 ===== */
.fwdoc{border-radius:14px;margin:18px 0}
.fwdoc table.tbl{display:block;overflow-x:auto;max-width:100%}
@media (prefers-reduced-motion:reduce){
.fwdoc *,.fwdoc *::before,.fwdoc *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
.fwdoc .reveal{opacity:1!important;transform:none!important}
}

</style>

<!-- ============================================================ 1 概述 ============================================================ -->
  <section id="sec1">
    <h2 class="sec"><span class="num">1</span>总览:四个并行维度如何组合</h2>
    <p class="lede">DeepInfer 没有使用传统的 Tensor Parallel(TP)。注意力权重全部为 <code>ReplicatedLinear</code> 复制,序列维与专家维才是切分轴:DP 切请求、CP 切 prefill 序列、EP 切专家、ENP 切 Engram 词法表条目。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🧭</span>DP · Data Parallel(数据并行)</h3>
        <p>每个 DP rank 独立持有完整的一份非专家权重(注意力、shared expert、gate、lm_head),服务不同请求。DP 组经 einops 重排后是<b>跨 cp 位置配对</b>的(见第 2 章),组内仅在<b>控制面</b>通信(如 <code>broadcast_tensor_dict</code> / shm 广播),数据面几乎零通信 —— 这正是「Attention DP」的含义:注意力完全不切分权重。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">📜</span>CP · Context Parallel(上下文并行)</h3>
        <p>仅作用于 <b>prefill</b>:同一请求的序列按 <b>mirror(交错 zigzag)</b> 方式均分到 CP 组各 rank,均衡 SWA 窗口与压缩 KV 的计算量;每层通过 DeepEP <code>BucketBuffer</code> 会话式 all-gather 聚合 KV 侧张量(第 3 章)。decode 阶段 CP 组退化为恒等(<code>attn.py:766</code> 仅 <code>is_prompt</code> 时启用)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🧩</span>EP · Expert Parallel(专家并行)</h3>
        <p>routed expert 权重按 <code>num_physical_experts // ep_size</code> 均分到 EP 组各 rank;token 由 DeepEP-V2 <code>EPBuffer</code> 按 top-k 路由 dispatch 到专家所在卡、计算后 combine 归还(第 4 章)。EP 组刻意组织成<b>连续 rank 段</b>,优先落在单机 NVLink 域内(<code>parallel_state.py:105-106</code>)。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">🗂</span>ENP · Engram Parallel + EPLB</h3>
        <p>ENP 为 Engram(压缩 tokenizer 的稀疏 n-gram 表)单独开辟的进程组,<code>EngramBuffer</code> 经 RDMA QP 交换条目。EPLB 则是 EP 的运行时负载均衡层:持续统计每专家 token 数,周期性重算「logical → physical」放置并用 P2P 把权重搬到新卡(第 5 章)。</p>
      </div>
    </div>

    <h3 style="color:#fff;margin:26px 0 10px;font-size:17px">维度间的代数关系</h3>
    <div class="filepath">deepinfer/config.py:150-182 · ParallelConfig</div>
    <pre class="code"><span class="k">class</span> <span class="f">ParallelConfig</span>:
    <span class="k">def</span> <span class="f">__init__</span>(self, data_parallel_size, context_parallel_size, expert_parallel_size,
                 engram_parallel_size, engine_rank, engine_group_rank, ...):
        <span class="k">if</span> data_parallel_size == <span class="n">0</span>:
            <span class="c"># 未显式指定 DP 时,由 EP 与 CP 推导:dp = max(1, ep // cp)</span>
            data_parallel_size = <span class="f">max</span>(<span class="n">1</span>, expert_parallel_size // context_parallel_size)
        ...
        self.model_parallel_size = self.context_parallel_size          <span class="c"># "TP" 槽位实际被 CP 占用</span>
        self.engram_parallel_size = engram_parallel_size <span class="k">or</span> (self.model_parallel_size * data_parallel_size)
        self.world_size = <span class="f">max</span>(self.model_parallel_size * data_parallel_size, self.engram_parallel_size)
    <span class="k">def</span> <span class="f">_verify_args</span>(self):
        <span class="k">assert</span> (self.model_parallel_size * self.data_parallel_size) % self.expert_parallel_size == <span class="n">0</span>
        <span class="k">assert</span> self.world_size % (self.model_parallel_size * self.data_parallel_size) == <span class="n">0</span>
        <span class="k">assert</span> self.world_size % self.engram_parallel_size == <span class="n">0</span></pre>

    <table class="tbl">
      <tr><th>约束 / 默认</th><th>含义</th><th>代码位置</th></tr>
      <tr><td><code>dp = max(1, ep // cp)</code></td><td>DP 未指定时自动推导,保证 <code>dp*cp = ep</code> 时 EP 组恰好覆盖一个「DP 副本 × CP 组」的全体 rank</td><td><code>config.py:161-162</code></td></tr>
      <tr><td><code>world = max(dp*cp, enp)</code></td><td>Engram 组可以比模型主体更大(独立进程组、独立 rank 空间起点)</td><td><code>config.py:173</code></td></tr>
      <tr><td><code>rank = engine_rank * cp_size + cp_rank</code></td><td>每个 engine(如 NORMAL / COMPLETION 引擎)派出 <code>cp_size</code> 个进程,全局 rank 由此拼接</td><td><code>worker/base.py:329</code></td></tr>
      <tr><td><code>max_num_prefilling_tokens //= cp_size</code></td><td>CP 组内每 rank 只需承载 1/cp 的 prefill token,上界随切分收缩</td><td><code>model_loader.py:120</code></td></tr>
    </table>

    <div class="note good">
      <b>一句话总结组合方式:</b>以「引擎 → DP 副本 → CP 组 → EP 段」为骨架组织全部 rank;注意力在 DP/CP 两维上复制或镜像切分、权重永不切开;MoE 在 EP 段内切专家,并由 EPLB 在运行时把「热」专家搬去空闲的卡。TP 被 CP 取代是 V4.1-Flash 结构(MLA 低秩 + 压缩 KV + YOCO 共享)下的自然选择 —— 低秩投影本就不值得横向切。
    </div>
  </section>

  <!-- ============================================================ 2 进程组拓扑 ============================================================ -->
  <section id="sec2">
    <h2 class="sec"><span class="num">2</span>进程组拓扑:ParallelProcessGroup 与 rank 重排</h2>
    <p class="lede">一切通信的坐标系。DeepInfer 用一个进程内的单例 <code>PG</code> 持有全部 8 类进程组(GPU 组 + gloo CPU 组),组的划分完全由 einops <code>rearrange</code> 模式串决定,可读性极强。</p>

    <div class="figure reveal">
      <svg viewBox="0 0 980 660" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="arrP" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto"><path d="M0,0 L8,3.5 L0,7 Z" fill="#a78bfa"/></marker>
          <marker id="arrB" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto"><path d="M0,0 L8,3.5 L0,7 Z" fill="#4f8cff"/></marker>
          <marker id="arrC" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto"><path d="M0,0 L8,3.5 L0,7 Z" fill="#22d3ee"/></marker>
        </defs>
        <text x="490" y="30" text-anchor="middle" fill="#dbe4f5" font-size="16" font-weight="700">示例拓扑:world = 8(2 机 × 4 卡),dp=2 · cp=2 · ep=4 · enp=8</text>

        <!-- ENP: 全世界 (黄) -->
        <rect x="30" y="52" width="920" height="430" rx="16" fill="rgba(251,191,36,0.04)" stroke="#fbbf24" stroke-width="2" stroke-dasharray="10 8"/>
        <text x="52" y="80" fill="#fbbf24" font-size="13" font-weight="700">ENP 组 (enp=8):[0..7] 全体 —— EngramBuffer RDMA 域</text>

        <!-- Node A: EP 组 [0,1,2,3] -->
        <rect x="60" y="100" width="410" height="350" rx="14" fill="rgba(167,139,250,0.06)" stroke="#a78bfa" stroke-width="2.2"/>
        <text x="80" y="128" fill="#a78bfa" font-size="13.5" font-weight="700">节点 A · EP 组 [0,1,2,3](连续 rank 段,NVLink 域)</text>
        <!-- Node B -->
        <rect x="510" y="100" width="410" height="350" rx="14" fill="rgba(167,139,250,0.06)" stroke="#a78bfa" stroke-width="2.2"/>
        <text x="530" y="128" fill="#a78bfa" font-size="13.5" font-weight="700">节点 B · EP 组 [4,5,6,7]</text>

        <!-- GPUs Node A: (r0,d0,c0)=0 (r0,d0,c1)=1 (r0,d1,c0)=2 (r0,d1,c1)=3 -->
        <g>
          <rect class="node-gpu" x="95"  y="160" width="150" height="104" rx="10"/>
          <rect class="node-gpu" x="285" y="160" width="150" height="104" rx="10"/>
          <rect class="node-gpu" x="95"  y="300" width="150" height="104" rx="10"/>
          <rect class="node-gpu" x="285" y="300" width="150" height="104" rx="10"/>
          <text class="node-gpu-title" x="170" y="192" text-anchor="middle">rank 0</text>
          <text class="node-gpu-title" x="360" y="192" text-anchor="middle">rank 1</text>
          <text class="node-gpu-title" x="170" y="332" text-anchor="middle">rank 2</text>
          <text class="node-gpu-title" x="360" y="332" text-anchor="middle">rank 3</text>
          <text x="170" y="214" text-anchor="middle" fill="#8ea0c2" font-size="11">d0·c0</text>
          <text x="360" y="214" text-anchor="middle" fill="#8ea0c2" font-size="11">d0·c1</text>
          <text x="170" y="354" text-anchor="middle" fill="#8ea0c2" font-size="11">d1·c0</text>
          <text x="360" y="354" text-anchor="middle" fill="#8ea0c2" font-size="11">d1·c1</text>
          <circle cx="170" cy="238" r="7" fill="#22d3ee" class="pulse"/>
          <circle cx="360" cy="238" r="7" fill="#22d3ee" class="pulse" style="animation-delay:.5s"/>
          <circle cx="170" cy="378" r="7" fill="#22d3ee" class="pulse" style="animation-delay:1s"/>
          <circle cx="360" cy="378" r="7" fill="#22d3ee" class="pulse" style="animation-delay:1.5s"/>
        </g>
        <!-- GPUs Node B -->
        <g>
          <rect class="node-gpu" x="545" y="160" width="150" height="104" rx="10"/>
          <rect class="node-gpu" x="735" y="160" width="150" height="104" rx="10"/>
          <rect class="node-gpu" x="545" y="300" width="150" height="104" rx="10"/>
          <rect class="node-gpu" x="735" y="300" width="150" height="104" rx="10"/>
          <text class="node-gpu-title" x="620" y="192" text-anchor="middle">rank 4</text>
          <text class="node-gpu-title" x="810" y="192" text-anchor="middle">rank 5</text>
          <text class="node-gpu-title" x="620" y="332" text-anchor="middle">rank 6</text>
          <text class="node-gpu-title" x="810" y="332" text-anchor="middle">rank 7</text>
          <text x="620" y="214" text-anchor="middle" fill="#8ea0c2" font-size="11">d0·c0</text>
          <text x="810" y="214" text-anchor="middle" fill="#8ea0c2" font-size="11">d0·c1</text>
          <text x="620" y="354" text-anchor="middle" fill="#8ea0c2" font-size="11">d1·c0</text>
          <text x="810" y="354" text-anchor="middle" fill="#8ea0c2" font-size="11">d1·c1</text>
          <circle cx="620" cy="238" r="7" fill="#22d3ee" class="pulse" style="animation-delay:.25s"/>
          <circle cx="810" cy="238" r="7" fill="#22d3ee" class="pulse" style="animation-delay:.75s"/>
          <circle cx="620" cy="378" r="7" fill="#22d3ee" class="pulse" style="animation-delay:1.25s"/>
          <circle cx="810" cy="378" r="7" fill="#22d3ee" class="pulse" style="animation-delay:1.75s"/>
        </g>

        <!-- CP 组 (青): [0,1] [2,3] [4,5] [6,7] 横向连线 -->
        <g stroke="#22d3ee" stroke-width="2.4" fill="none">
          <line x1="245" y1="212" x2="285" y2="212" class="flowline" marker-end="url(#arrC)"/>
          <line x1="245" y1="352" x2="285" y2="352" class="flowline" marker-end="url(#arrC)"/>
          <line x1="695" y1="212" x2="735" y2="212" class="flowline" marker-end="url(#arrC)"/>
          <line x1="695" y1="352" x2="735" y2="352" class="flowline" marker-end="url(#arrC)"/>
        </g>
        <text x="265" y="200" text-anchor="middle" fill="#22d3ee" font-size="10.5">CP</text>
        <text x="715" y="200" text-anchor="middle" fill="#22d3ee" font-size="10.5">CP</text>

        <!-- DP 组 (蓝): [0,2] [1,3] [4,6] [5,7] 纵向连线 -->
        <g stroke="#4f8cff" stroke-width="2.4" fill="none">
          <line x1="170" y1="264" x2="170" y2="300" class="flowline" marker-end="url(#arrB)"/>
          <line x1="360" y1="264" x2="360" y2="300" class="flowline" marker-end="url(#arrB)"/>
          <line x1="620" y1="264" x2="620" y2="300" class="flowline" marker-end="url(#arrB)"/>
          <line x1="810" y1="264" x2="810" y2="300" class="flowline" marker-end="url(#arrB)"/>
        </g>
        <text x="150" y="288" fill="#4f8cff" font-size="10.5">DP</text>
        <text x="800" y="288" fill="#4f8cff" font-size="10.5">DP</text>

        <!-- world 组:节点间两条链路 -->
        <g stroke="#34d399" stroke-width="2" fill="none" opacity=".85">
          <path d="M470,240 C490,240 490,240 510,240" class="flowline"/>
          <path d="M470,380 C490,380 490,380 510,380" class="flowline"/>
        </g>
        <text x="490" y="228" text-anchor="middle" fill="#34d399" font-size="10.5">world/RDMA</text>

        <!-- 图例 + 数据包动画 -->
        <g font-size="12.5">
          <rect x="60" y="512" width="900" height="120" rx="12" fill="rgba(13,20,36,.9)" stroke="#263352"/>
          <text x="85" y="543" fill="#22d3ee">━ CP 组(gloo+NCCL/HCCL,shm MessageQueue):prefill 序列镜像切分</text>
          <text x="85" y="568" fill="#4f8cff">━ DP 组:同 cp 位置的 rank 配对([0,2][1,3][4,6][5,7]),注意力复制权重</text>
          <text x="85" y="593" fill="#a78bfa">▢ EP 组:连续 rank 段(<sup>0-3</sup>/<sub>4-7</sub>),DeepEP dispatch/combine + EPLB 重排</text>
          <text x="85" y="618" fill="#fbbf24">▢ ENP 组:全体 rank,EngramBuffer RDMA;ep_size==world 时 EP 复用 world 组</text>
        </g>
        <circle r="6" fill="#22d3ee" class="barrow"><animateMotion dur="2.2s" repeatCount="indefinite" path="M245,212 L285,212"/></circle>
        <circle r="6" fill="#22d3ee" class="barrow"><animateMotion dur="2.2s" begin="1.1s" repeatCount="indefinite" path="M285,212 L245,212"/></circle>
        <circle r="6" fill="#4f8cff" class="barrow"><animateMotion dur="2.6s" repeatCount="indefinite" path="M170,264 L170,300"/></circle>
        <circle r="6" fill="#4f8cff" class="barrow"><animateMotion dur="2.6s" begin="1.3s" repeatCount="indefinite" path="M620,300 L620,264"/></circle>
        <circle r="5.5" fill="#a78bfa" class="barrow"><animateMotion dur="3.6s" repeatCount="indefinite" path="M360,460 C520,520 460,560 620,460"/></circle>
        <circle r="5.5" fill="#fbbf24" class="barrow"><animateMotion dur="4.4s" repeatCount="indefinite" path="M170,80 C400,40 580,44 810,80"/></circle>
      </svg>
      <div class="cap">图 2-1 · 进程组拓扑动画。青色流动线 = CP 组内 BucketBuffer all-gather;蓝色 = DP 组(跨 CP 位置配对);紫色数据包在 EP 组间流动(DeepEP dispatch);黄色沿 ENP/world 边界巡游(RDMA)。<code>parallel_state.py:70-126</code></div>
    </div>

    <h3 style="color:#fff;margin:26px 0 10px;font-size:17px">rearrange 模式串:组的精确定义</h3>
    <div class="filepath">deepinfer/model_executor/parallel_utils/parallel_state.py:70-126 · create_process_groups</div>
    <pre class="code"><span class="k">def</span> <span class="f">create_process_groups</span>(self, *, tag, dp_size, ep_size=<span class="n">1</span>, cp_size=<span class="n">1</span>, enp_size=<span class="n">1</span>):
    ranks = torch.arange(<span class="f">max</span>(enp_size, dp_size * cp_size))
    backend = PLATFORM.distributed_backend          <span class="c"># GPU→nccl, NPU→hccl (platform.py:58/89)</span>
    options = PLATFORM.get_distributed_options()    <span class="c"># NCCL: max/min_ctas = DEEPINFER_NCCL_NUM_SMS(32)</span>

    self.world = _split_group([ranks.tolist()], backend=backend, ...)          <span class="c"># 全体</span>
    self.local = _split_group(ranks.unsqueeze(-<span class="n">1</span>).tolist(), ...)             <span class="c"># 每个 rank 自己一组</span>

    <span class="c"># DP 组:重排后按行分组 —— 同一 (replica, cp位置) 的 rank 互为 DP 对等体</span>
    dp_ranks = <span class="f">rearrange</span>(ranks, <span class="s">"(replica dp cp) -> (replica cp) dp"</span>, dp=dp_size, cp=cp_size)
    self.dp = _split_group(dp_ranks.tolist(), ...)
    self.cpu_dp_group = _split_group(dp_ranks.tolist(), backend=<span class="s">"gloo"</span>)

    <span class="c"># CP 组:相邻 cp_size 个 rank 一组(连续段)</span>
    cp_ranks = <span class="f">rearrange</span>(ranks, <span class="s">"(dp cp) -> dp cp"</span>, cp=cp_size)
    self.cp = _split_group(cp_ranks.tolist(), ...)
    self.cpu_cp_group = _split_group(cp_ranks.tolist(), backend=<span class="s">"gloo"</span>)

    <span class="c"># EP 组:连续 ep_size 段;ep==world 时直接复用 world 组</span>
    <span class="k">if</span> ep_size == ranks.numel():
        self.ep = self.world
    <span class="k">else</span>:
        ep_ranks = <span class="f">rearrange</span>(ranks, <span class="s">"(edp ep) -> edp ep"</span>, ep=ep_size)
        self.ep = _split_group(ep_ranks.tolist(), ...)

    enp_ranks = <span class="f">rearrange</span>(ranks, <span class="s">"(replica enp) -> replica enp"</span>, enp=enp_size)
    self.enp = _split_group(enp_ranks.tolist(), ...)

    ep_in_dp_ranks = <span class="f">rearrange</span>(ranks, <span class="s">"(edp ep_in_dp) -> edp ep_in_dp"</span>, ep_in_dp=ep_size)
    self.ep_in_dp = self.local <span class="k">if</span> ep_size == <span class="n">1</span> <span class="k">else</span> _split_group(ep_in_dp_ranks.tolist(), ...)
    self.cpu_ep_in_dp = _split_group(ep_in_dp_ranks.tolist(), backend=<span class="s">"gloo"</span>)

    <span class="k">if</span> cp_size &gt; <span class="n">1</span>:   <span class="c"># CP 组内 shm 广播通道:1 MiB × 10 槽</span>
        self.mq = MessageQueue.create_from_process_group(self.cpu_cp_group, <span class="n">1</span> &lt;&lt; <span class="n">20</span>, <span class="n">10</span>)
    self.init_device_groups()</pre>

    <table class="tbl">
      <tr><th>组</th><th>rearrange 模式</th><th>划分规则(dp=2,cp=2,ep=4,enp=8 实例)</th><th>主要用途</th></tr>
      <tr><td><code>world</code></td><td>全体一行</td><td>[0..7]</td><td>全局 rank 空间、<code>dist.get_rank()</code></td></tr>
      <tr><td><code>local</code></td><td>每 rank 一组</td><td>[0][1]…[7]</td><td>单 rank 占位;<code>ep_size==1</code> 时充当 <code>ep_in_dp</code></td></tr>
      <tr><td><code>dp</code></td><td><code>(replica dp cp) -&gt; (replica cp) dp</code></td><td>[0,2] [1,3] [4,6] [5,7]</td><td>Attention DP:请求级复制</td></tr>
      <tr><td><code>cp</code></td><td><code>(dp cp) -&gt; dp cp</code></td><td>[0,1] [2,3] [4,5] [6,7]</td><td>prefill mirror-CP + BucketBuffer all-gather</td></tr>
      <tr><td><code>ep</code></td><td><code>(edp ep) -&gt; edp ep</code></td><td>[0,1,2,3] [4,5,6,7]</td><td>DeepEP dispatch/combine、EPLB all_reduce/重排</td></tr>
      <tr><td><code>ep_in_dp</code></td><td><code>(edp ep_in_dp) -&gt; edp ep_in_dp</code></td><td>同 EP(基于 dp*cp 空间)</td><td>DP 副本内部的 EP 视图(gloo 镜像 <code>cpu_ep_in_dp</code>)</td></tr>
      <tr><td><code>enp</code></td><td><code>(replica enp) -&gt; replica enp</code></td><td>[0..7]</td><td>EngramBuffer 稀疏条目交换</td></tr>
      <tr><td><code>cpu_dp / cpu_cp / cpu_ep_in_dp</code></td><td>同上,backend=<code>"gloo"</code></td><td>—</td><td>CPU 侧控制面:shm 广播、EPLB 同步、超时看护</td></tr>
    </table>

    <h3 style="color:#fff;margin:26px 0 10px;font-size:17px">gloo 兜底与 eager 建链</h3>
    <p style="font-size:14px;color:var(--muted)">worker 启动时<b>默认 PG 用 gloo</b> 而非 NCCL/HCCL(<code>worker/base.py:335</code>),设备后端只在子组上启用。这带来一个隐患:PyTorch 的子组是 lazy 初始化的,不跑一次 collective 就不会真正建立 communicator。DeepInfer 的对策是 <code>init_device_groups</code> 对每个唯一的 NCCL/HCCL 子组做一次 <b>eager all_reduce</b>:</p>
    <div class="filepath">deepinfer/model_executor/parallel_utils/parallel_state.py:173-187 · init_device_groups</div>
    <pre class="code"><span class="k">def</span> <span class="f">init_device_groups</span>(self):
    <span class="s">"""默认 PG 改为 CPU(gloo) 后端后,NCCL/HCCL 子组失去 eager/split 初始化,全部 lazy:
    必须先跑一次 collective 才会真正建 comm。
    单 rank 组也不能跳过:engram deep_ep 经 backend._comm_ptr() 复用这里建出的 comm,
    空指针会直接段错误。"""</span>
    seen = <span class="f">set</span>()
    <span class="k">for</span> value <span class="k">in</span> self.__dict__.values():
        <span class="k">try</span>:
            <span class="k">if</span> <span class="k">not</span> <span class="f">isinstance</span>(value, ProcessGroup) <span class="k">or</span> dist.get_backend(value) <span class="k">not in</span> (<span class="s">"nccl"</span>, <span class="s">"hccl"</span>):
                <span class="k">continue</span>
        <span class="k">except</span> Exception:
            <span class="k">continue</span>
        <span class="k">if</span> <span class="f">id</span>(value) <span class="k">not in</span> seen:
            seen.add(<span class="f">id</span>(value))
            dist.all_reduce(torch.zeros(<span class="n">1</span>).cuda(), group=value)   <span class="c"># 强制建链</span></pre>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🛰</span>NVLink 域判定:is_within_nvl_domain</h3>
        <p>决定 EP 组能否走「单机 fast path」的关键谓词(<code>parallel_state.py:130-134</code>):NPU 平台恒真;GPU 上用 <code>deep_ep.get_physical_domain_size(group)[1]</code> 判定组是否落在物理 NVLink 域内。它同时控制 <b>mega-MoE 单内核路径</b>(<code>mlp.py:187</code>)与 <b>EPLB intra-node IPC shuffle</b>(<code>eplb/__init__.py:200</code>)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧹</span>shm 广播通道与清理</h3>
        <p>CP 组创建 <code>MessageQueue</code>(1 MiB × 10 槽,<code>parallel_state.py:123-124</code>)用于 <code>cp_broadcast_object</code>;进程退出前必须显式 <code>cleanup_shm_broadcast()</code> 关闭并 unlink 共享内存,否则 resource_tracker 会报泄漏(<code>parallel_state.py:161-169</code>)。</p>
      </div>
    </div>

    <h3 style="color:#fff;margin:26px 0 10px;font-size:17px">从硬件到进程:deep_cluster 的角色</h3>
    <p style="font-size:14px;color:var(--muted)">进程组之下是硬件发现层 <code>deep_cluster/</code>:它统一 NVIDIA(<code>CUDA_VISIBLE_DEVICES</code>)与昇腾(<code>ASCEND_RT_VISIBLE_DEVICES</code>)的差异(<code>device.py:37-43</code>),并提供按 rank 分配设备的 <code>assign_visible_devices</code> —— 设备数必须能被 <code>devices_per_rank</code> 整除,按 <code>rank % (count // devices_per_rank)</code> 轮转分组(<code>device.py:108-126</code>)。worker 再据 <code>CUDA_VISIBLE_DEVICES</code> 与 NUMA 拓扑(<code>device.py:129-136</code> 的 <code>device_numa_node</code>)把进程绑定到 GPU 所在的 NUMA 节点,避免 H2D 拷贝跨 socket(<code>worker/base.py:347-358</code> <code>_bind_numa</code>)。</p>

    <div class="note">
      <b>初始化时序(worker/base.py:313-345):</b>① <code>dist.init_process_group(backend="gloo", rank=engine_rank*cp_size+cp_rank)</code> → ② <code>init_parallel_groups(dp, ep, cp, enp)</code>(<code>parallel_state.py:196-230</code>,日志逐项打印 DP/CP/EP/ENP rank,默认 tag 的组直接注入全局单例 <code>PG</code>)→ ③ <code>init_device_groups</code> eager 建链 → ④ 模型加载后 <code>allocate_userbuffer</code> 建立 DeepEP/DeepGEMM 缓冲。
    </div>
  </section>

  <!-- ============================================================ 3 Attention DP / balanced CP ============================================================ -->
  <section id="sec3">
    <h2 class="sec"><span class="num">3</span>Attention DP / balanced CP:注意力为什么不切、怎么切</h2>
    <p class="lede">V4.1-Flash 的注意力 = MLA 低秩 Q/KV 投影 + 压缩 KV(Compressor)+ 稀疏索引器(MQAIndexer)+ YOCO 跨层共享。DeepInfer 对它的并行策略是:权重一个不切(全 DP 复制),prefill 序列用 mirror-CP 交错切分。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📎</span>为什么用 DP:低秩结构不值得切</h3>
        <p>看容器就知道(<code>mla_attn.py</code>):<code>Wq</code>/<code>Wkv</code> 是 <code>ColumnParallelLora</code> 的 A→norm→B 低秩链(26-60 行),<code>Wv</code>、<code>out_proj</code>、<code>Wgate</code>、indexer 全是 <code>ReplicatedLinear</code>(如 228、282 行)。这些投影的 K 维是 <code>q_lora_rank</code>/<code>kv_lora_rank</code> 级别的小矩阵,TP 切分通信收益为负。因此每个 DP rank 复制全套注意力权重,各算各的请求 —— <b>零注意力通信</b>。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">⚖️</span>为什么 CP 还要 balanced:SWA/KV 压缩的不对称</h3>
        <p>朴素 CP(每 rank 拿连续一段)会让「靠窗口边界的 chunk」在 SWA 注意力与压缩 KV 下计算量倾斜。DeepInfer 采用 <b>mirror(zigzag)切分</b>:序列按块交错分配,rank r 拿第 r 块与第 <code>2*cp-1-r</code> 块 —— 首尾配对,任意窗口内各 rank 的负载天然接近(<code>prepare_cp_mirror.py:126-157</code> 参考实现)。</p>
      </div>
    </div>

    <div class="figure reveal">
      <svg viewBox="0 0 980 560" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="arrZ" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto"><path d="M0,0 L8,3.5 L0,7 Z" fill="#22d3ee"/></marker>
        </defs>
        <text x="490" y="30" text-anchor="middle" fill="#dbe4f5" font-size="16" font-weight="700">mirror-CP 交错切分(cp_size=2,序列长 16,块宽 ps=4)</text>
        <!-- 原始序列 -->
        <text x="70" y="66" fill="#8ea0c2" font-size="12.5">原始序列(varlen 展平后):</text>
        <g>
          <rect x="70" y="78" width="840" height="34" rx="8" fill="#141d33" stroke="#263352"/>
          <g font-size="11" fill="#8ea0c2" text-anchor="middle">
            <text x="100" y="100">t0</text><text x="152" y="100">t1</text><text x="204" y="100">t2</text><text x="256" y="100">t3</text>
            <text x="308" y="100">t4</text><text x="360" y="100">t5</text><text x="412" y="100">t6</text><text x="464" y="100">t7</text>
            <text x="516" y="100">t8</text><text x="568" y="100">t9</text><text x="620" y="100">t10</text><text x="672" y="100">t11</text>
            <text x="724" y="100">t12</text><text x="776" y="100">t13</text><text x="828" y="100">t14</text><text x="880" y="100">t15</text>
          </g>
          <!-- 块着色: rank0 = block0 + block3, rank1 = block1 + block2 -->
          <rect x="75"  y="83" width="104" height="24" rx="6" fill="rgba(79,140,255,.30)" stroke="#4f8cff"/>
          <rect x="183" y="83" width="104" height="24" rx="6" fill="rgba(34,211,238,.30)" stroke="#22d3ee"/>
          <rect x="291" y="83" width="104" height="24" rx="6" fill="rgba(34,211,238,.30)" stroke="#22d3ee"/>
          <rect x="399" y="83" width="104" height="24" rx="6" fill="rgba(79,140,255,.30)" stroke="#4f8cff"/>
          <rect x="507" y="83" width="104" height="24" rx="6" fill="rgba(79,140,255,.30)" stroke="#4f8cff"/>
          <rect x="615" y="83" width="104" height="24" rx="6" fill="rgba(34,211,238,.30)" stroke="#22d3ee"/>
          <rect x="723" y="83" width="104" height="24" rx="6" fill="rgba(34,211,238,.30)" stroke="#22d3ee"/>
          <rect x="831" y="83" width="104" height="24" rx="6" fill="rgba(79,140,255,.30)" stroke="#4f8cff"/>
        </g>
        <!-- zigzag 弧线 -->
        <g stroke-width="2" fill="none">
          <path d="M127,120 C150,168 470,168 555,196" stroke="#4f8cff" class="flowline" marker-end="url(#arrZ)"/>
          <path d="M665,120 C690,156 500,150 451,196" stroke="#22d3ee" class="flowline" marker-end="url(#arrZ)"/>
          <path d="M343,120 C370,190 350,180 347,196" stroke="#22d3ee" class="flowline" marker-end="url(#arrZ)"/>
          <path d="M883,120 C900,176 600,186 555,196" stroke="#4f8cff" class="flowline" marker-end="url(#arrZ)"/>
        </g>
        <!-- 两个 rank 通道 -->
        <g>
          <rect x="70" y="200" width="400" height="86" rx="12" fill="#141d33" stroke="#4f8cff" stroke-width="2"/>
          <text x="90" y="228" fill="#4f8cff" font-size="13.5" font-weight="700">CP rank 0:块 0 与块 3(t0-3, t12-15)</text>
          <rect x="90"  y="242" width="86" height="26" rx="6" fill="rgba(79,140,255,.35)"/><text x="133" y="260" fill="#dbe4f5" font-size="11" text-anchor="middle">块0</text>
          <rect x="184" y="242" width="86" height="26" rx="6" fill="rgba(79,140,255,.35)"/><text x="227" y="260" fill="#dbe4f5" font-size="11" text-anchor="middle">块3</text>
          <text x="300" y="260" fill="#8ea0c2" font-size="11.5">mirror 镜像布局 [块0|块3]</text>
          <circle cx="440" cy="243" r="6" fill="#4f8cff" class="pulse"/>
        </g>
        <g>
          <rect x="510" y="200" width="400" height="86" rx="12" fill="#141d33" stroke="#22d3ee" stroke-width="2"/>
          <text x="530" y="228" fill="#22d3ee" font-size="13.5" font-weight="700">CP rank 1:块 1 与块 2(t4-11)</text>
          <rect x="530" y="242" width="86" height="26" rx="6" fill="rgba(34,211,238,.35)"/><text x="573" y="260" fill="#dbe4f5" font-size="11" text-anchor="middle">块1</text>
          <rect x="624" y="242" width="86" height="26" rx="6" fill="rgba(34,211,238,.35)"/><text x="667" y="260" fill="#dbe4f5" font-size="11" text-anchor="middle">块2</text>
          <text x="740" y="260" fill="#8ea0c2" font-size="11.5">mirror 镜像布局 [块1|块2]</text>
          <circle cx="880" cy="243" r="6" fill="#22d3ee" class="pulse"/>
        </g>

        <!-- all-gather 阶段 -->
        <text x="70" y="326" fill="#8ea0c2" font-size="12.5">每层 prefill:KV 侧张量经 CPManager 会话式 all-gather 聚合(先发射、后等待,与 Q 投影重叠):</text>
        <g>
          <rect x="70" y="342" width="180" height="58" rx="10" class="node-gpu"/>
          <text x="160" y="366" text-anchor="middle" fill="#dbe4f5" font-size="12.5" font-weight="700">rank0 KV 分片</text>
          <text x="160" y="386" text-anchor="middle" fill="#8ea0c2" font-size="10.5">get_inplace_tensor 原地写</text>
          <rect x="400" y="342" width="180" height="58" rx="10" class="node-gpu"/>
          <text x="490" y="366" text-anchor="middle" fill="#dbe4f5" font-size="12.5" font-weight="700">rank1 KV 分片</text>
          <text x="490" y="386" text-anchor="middle" fill="#8ea0c2" font-size="10.5">同一 BucketBuffer 会话</text>
          <rect x="680" y="330" width="230" height="82" rx="12" fill="rgba(52,211,153,.08)" stroke="#34d399" stroke-width="2"/>
          <text x="795" y="360" text-anchor="middle" fill="#34d399" font-size="13" font-weight="700">聚合后完整 KV</text>
          <text x="795" y="382" text-anchor="middle" fill="#8ea0c2" font-size="11">wait() 后按 rank 顺序 flatten</text>
          <text x="795" y="400" text-anchor="middle" fill="#8ea0c2" font-size="11">再 gather(reverse_index) 还原 varlen</text>
          <path d="M250,371 L400,371" stroke="#34d399" stroke-width="2.4" class="flowline" marker-end="url(#arrZ)"/>
          <path d="M580,371 L680,371" stroke="#34d399" stroke-width="2.4" class="flowline" marker-end="url(#arrZ)"/>
          <circle r="6" fill="#4f8cff" class="barrow"><animateMotion dur="2s" repeatCount="indefinite" path="M250,371 L400,371 L680,371"/></circle>
          <circle r="6" fill="#22d3ee" class="barrow"><animateMotion dur="2s" begin="1s" repeatCount="indefinite" path="M580,371 L400,371 L680,371"/></circle>
        </g>
        <!-- 负载均衡条 -->
        <g font-size="12">
          <text x="70" y="452" fill="#8ea0c2">负载均衡对比(同一序列内 SWA 窗口覆盖数):</text>
          <rect x="70" y="464" width="360" height="22" rx="6" fill="#141d33" stroke="#263352"/>
          <rect x="70" y="464" width="178" height="22" rx="6" fill="#4f8cff" opacity=".55"/><rect x="252" y="464" width="178" height="22" rx="6" fill="#22d3ee" opacity=".55"/>
          <text x="452" y="480" fill="#34d399">mirror:各 ~50%</text>
          <rect x="640" y="464" width="270" height="22" rx="6" fill="#141d33" stroke="#263352"/>
          <rect x="640" y="464" width="60" height="22" rx="6" fill="#f87171" opacity=".55"/><rect x="704" y="464" width="206" height="22" rx="6" fill="#4f8cff" opacity=".4"/>
          <text x="640" y="506" fill="#f87171">朴素连续切分:头部密、尾部疏</text>
        </g>
        <text x="490" y="546" text-anchor="middle" fill="#8ea0c2" font-size="11.5">prepare_cp_mirror.py:135 ps=⌈sq/(2·cp)⌉;:146 块对 (rank, 2·cp−1−rank);attn.py:828 gather(wait_kv_swa(), mirror_cp_reverse_index)</text>
      </svg>
      <div class="cap">图 3-1 · mirror-CP 交错切分与会话式 all-gather。蓝/青数据包分别表示两个 rank 的 KV 分片汇入聚合缓冲。</div>
    </div>

    <h3 style="color:#fff;margin:26px 0 10px;font-size:17px">CPManager:DeepEP BucketBuffer 上的会话式 all-gather</h3>
    <div class="filepath">deepinfer/model_executor/parallel_utils/cp.py:9-54 · CPManager</div>
    <pre class="code"><span class="k">class</span> <span class="f">CPManager</span>:
    <span class="s">"""管理 CP 通信存储、会话与 all-gather。wait 回调必须在本会话内消费;
    聚合出的张量是 buffer 存储的视图,会被下一个会话复用。"""</span>
    <span class="k">def</span> <span class="f">__init__</span>(self, group, num_bytes):
        self._buffer = BucketBuffer(group, num_bytes, explicitly_destroy=<span class="k">True</span>)

    <span class="k">def</span> <span class="f">get_inplace_tensor</span>(self, shape, dtype):
        <span class="s">"""在会话中分配聚合区域,返回本 rank 的连续分片 —— 写入即无拷贝参与 all-gather"""</span>
        region = self._session.allocate((self._size, *shape), dtype)
        <span class="k">return</span> region[self._rank]

    <span class="k">def</span> <span class="f">all_gather</span>(self, x):
        <span class="s">"""发射 all-gather;返回的闭包等待完成后把各 rank 分片沿 token 轴拼接"""</span>
        <span class="k">if</span> <span class="k">not</span> x.is_contiguous():          <span class="c"># 非连续输入先拷进本 rank 分片</span>
            contiguous_x = self.get_inplace_tensor(x.shape, x.dtype)
            contiguous_x.copy_(x)
            x = contiguous_x
        handle = self._buffer.all_gather(x)
        gathered_shape = (self._size, *x.shape)
        <span class="k">return</span> <span class="k">lambda</span>: handle.wait().view(gathered_shape).flatten(<span class="n">0</span>, <span class="n">1</span>)</pre>
    <p style="font-size:14px;color:var(--muted)">「会话式」是精髓:一个 <code>cp_session</code> 内可以发射<b>多个</b> all-gather(最多 <code>max_num_ags_per_session=8</code>,<code>userbuffer.py:102</code>),DeepEP 把它们合并优化;会话结束时缓冲整体复用,所以所有 wait 闭包必须在此之前消费完。注意力前向把它用到了极致 —— <b>先发射 KV 的 all-gather,再去算 Q 投影</b>(<code>attn.py:783-785</code> 注释:overlap it with the Q projection below)。</p>

    <div class="filepath">deepinfer/model_executor/models/v4_modules/attn.py:766-830 · V4Attention.forward 中的 CP 骨架</div>
    <pre class="code">use_cp = input_metadata.is_prompt <span class="k">and</span> PG.context_parallel_group().size() &gt; <span class="n">1</span>   <span class="c"># :766 仅 prefill</span>
...
<span class="k">with</span> userbuffer.cp_session(enabled=use_cp):
    <span class="c"># 先发射 compressor 输入(kv)的 all-gather,与下方 Q 投影重叠</span>
    wait_projected_kv = _make_cp_gather_getter(projected_kv, use_cp) ...     <span class="c"># :785</span>
    q_a, kv_swa = self._project_q_and_swa(hidden_states, shared_hidden_bf16) <span class="c"># Q 投影与通信并行</span>
    kv_swa, wait_kv_swa = self._prepare_swa_kv(kv_swa, ..., use_cp)          <span class="c"># :411 get_inplace_tensor</span>
    q_b, index_q_b = self._project_q_b(q_a, input_metadata.positions)
    kv_ca_index = self._compute_kv_ca_index(wait_projected_kv, ...)          <span class="c"># 此处才 wait()</span>
    ...
    <span class="k">if</span> use_cp:
        kv_swa = gather(wait_kv_swa(), input_metadata.mirror_cp_reverse_index, out=kv_swa_cur)  <span class="c"># :828</span></pre>

    <table class="tbl">
      <tr><th>CP all-gather 调用点</th><th>聚合的张量</th><th>代码位置</th></tr>
      <tr><td>模型入口</td><td>embedding 后 hidden,按 <code>mirror_cp_index</code> 重排</td><td><code>deepseek.py:168-170</code></td></tr>
      <tr><td>注意力 compressor 输入</td><td>投影后 KV(<code>current_hidden_proj</code> / <code>shared_hidden_kv_proj</code> 输出)</td><td><code>attn.py:785</code> + <code>attn.py:54-62</code></td></tr>
      <tr><td>SWA KV</td><td>norm+RoPE+cast 后的 <code>kv_swa</code>(先写入 inplace 分片再聚合)</td><td><code>attn.py:411,450</code></td></tr>
      <tr><td>YOCO 边界压缩</td><td>consumer 层共享 hidden(contrib 选择 → all_gather → gather)</td><td><code>v4_modules/yoco.py:66-75</code></td></tr>
      <tr><td>DFlash main cache</td><td>MTP 主 token 的 k(独立小会话)</td><td><code>attn.py:937-944</code></td></tr>
      <tr><td>模型出口</td><td>output_norm 后 hidden,按 <code>mirror_cp_reverse_index</code> 还原 varlen 序</td><td><code>deepseek.py:241-244</code></td></tr>
    </table>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🧬</span>MLA / YOCO 结构下的 CP 细节</h3>
        <p>① <b>压缩 KV 源层才需要聚合</b>:只有 <code>is_kv_source</code> 的层真正持有 <code>PackedWkv</code> 压缩器(<code>mla_attn.py:252-269</code>),后续 consumer 复用 <code>loaded_prefill_kv</code> 缓冲(<code>attn.py:723-750</code>),避免重复 all-gather。② <b>YOCO 消费层</b>的 KV 来自跨层共享 hidden,full-KV 更新走独立内层会话(<code>attn.py:706-708</code>)。③ 索引器 topk 的行数断言使用 <code>cp_mirror_len</code>(<code>attn.py:572-578</code>)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🛠</span>控制面:communication_op.py</h3>
        <p><code>gather</code>(12-25 行)是 varlen 友好的 <code>dist.gather</code>+concat;<code>cp_broadcast</code> / <code>cp_broadcast_multi_tensor</code>(28-43 行)在 CP 组内广播张量;<code>broadcast_tensor_dict</code>(51-82 行)混合通道 —— <b>CUDA 张量走 NCCL/HCCL,元数据走 shm MessageQueue</b>(<code>parallel_state.py:17-23</code> 的 <code>cp_broadcast_object</code>:writer <code>enqueue</code>、reader <code>dequeue</code>)。驱动 worker 广播控制指令即用此通道(<code>worker/base.py:296-302</code>)。</p>
      </div>
    </div>

    <div class="note warn">
      <b>decode 为什么不做 CP?</b>decode 每步 token 极少,切序列得不偿失;CP 组在 decode 中仅剩控制面作用(shm 广播、<code>gate_force_random_cp</code> 的确定性随机,<code>mlp.py:374-377</code>)。因此 <code>max_num_decoding_tokens</code> 不除以 cp,而 <code>max_num_prefilling_tokens</code> 除以 cp(<code>model_loader.py:119-120</code>)。
    </div>
  </section>

  <!-- ============================================================ 4 MoE EP ============================================================ -->
  <section id="sec4">
    <h2 class="sec"><span class="num">4</span>MoE EP:dispatch / combine 全流程</h2>
    <p class="lede">routed expert 按 EP 组切分;token 携带 top-k 路由被 DeepEP-V2 <code>EPBuffer</code> 发往专家所在的卡,grouped GEMM 计算后 combine 回源卡并把 shared expert 结果一并叠加。</p>

    <h3 style="color:#fff;margin:22px 0 10px;font-size:17px">专家计数语义(理解 EPLB 的前提)</h3>
    <div class="filepath">deepinfer/model_executor/models/v4_modules/moe.py:1-7 · 模块 docstring</div>
    <pre class="code"><span class="c">Expert counting semantics (consistent with DeepInfer's eplb):
- logical  = cfg.moe.n_routed_experts, the range the gate selects from;
- extra    = cfg.moe.n_redundant_experts (written by model_loader._configure_moe_redundancy);
- physical = logical + extra, the number of parameter rows actually allocated, must be divisible by ep_size;
- local    = physical // ep_size, the number of experts held by this rank.</span></pre>
    <table class="tbl">
      <tr><th>概念</th><th>定义</th><th>代码位置</th></tr>
      <tr><td>logical expert</td><td>gate 打分的原始专家编号集合(<code>n_routed_experts</code>)</td><td><code>moe.py:77</code></td></tr>
      <tr><td>extra / redundant</td><td>冗余副本数;加载前由 <code>resolve_num_extra_experts</code> 向上取整到能被 <code>ep_size</code> 整除</td><td><code>eplb/__init__.py:21-28</code>、<code>model_loader.py:83-106</code></td></tr>
      <tr><td>physical expert</td><td>实际分配参数行的槽位,= logical + extra;<code>DeepseekMoE</code> 断言其可被 <code>ep_size</code> 整除</td><td><code>mlp.py:199-205</code></td></tr>
      <tr><td>local physical</td><td>每 rank 持有的槽数 = physical // ep_size;权重即按此重塑</td><td><code>mlp.py:201,212-213</code></td></tr>
    </table>
    <p style="font-size:14px;color:var(--muted)">加载器会把 <code>DEEPINFER_OVERRIDE_NUM_EXTRA_EXPERTS</code> 指定的下限向上取整并打 warning(<code>model_loader.py:94-99</code>);初始布局是「先放满 logical,extra 槽位循环复制 routed」(<code>eplb/__init__.py:31-39</code> <code>get_initial_global_physical_to_logical_map</code>)。</p>

    <div class="figure reveal">
      <svg viewBox="0 0 980 640" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="m4c" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto"><path d="M0,0 L8,3.5 L0,7 Z" fill="#22d3ee"/></marker>
          <marker id="m4g" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto"><path d="M0,0 L8,3.5 L0,7 Z" fill="#34d399"/></marker>
          <marker id="m4p" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto"><path d="M0,0 L8,3.5 L0,7 Z" fill="#a78bfa"/></marker>
        </defs>
        <text x="490" y="30" text-anchor="middle" fill="#dbe4f5" font-size="16" font-weight="700">MoE EP:dispatch → grouped GEMM → combine(ep_size=4, top-2 路由)</text>

        <!-- 左侧 token 块 -->
        <rect x="40" y="70" width="150" height="500" rx="12" fill="#141d33" stroke="#263352"/>
        <text x="115" y="98" text-anchor="middle" fill="#dbe4f5" font-size="13" font-weight="700">本 rank tokens</text>
        <text x="115" y="116" text-anchor="middle" fill="#8ea0c2" font-size="10.5">gate: topk_idx + 权重</text>
        <g font-size="11.5">
          <rect x="60" y="135" width="110" height="26" rx="6" fill="rgba(79,140,255,.25)" stroke="#4f8cff"/><text x="115" y="153" text-anchor="middle" fill="#dbe4f5">tok a → E2,E7</text>
          <rect x="60" y="175" width="110" height="26" rx="6" fill="rgba(34,211,238,.22)" stroke="#22d3ee"/><text x="115" y="193" text-anchor="middle" fill="#dbe4f5">tok b → E0,E2</text>
          <rect x="60" y="215" width="110" height="26" rx="6" fill="rgba(167,139,250,.22)" stroke="#a78bfa"/><text x="115" y="233" text-anchor="middle" fill="#dbe4f5">tok c → E5,E9</text>
          <rect x="60" y="255" width="110" height="26" rx="6" fill="rgba(52,211,153,.22)" stroke="#34d399"/><text x="115" y="273" text-anchor="middle" fill="#dbe4f5">tok d → E2,E9</text>
        </g>
        <text x="115" y="320" text-anchor="middle" fill="#8ea0c2" font-size="10.5">shared expert(本地)</text>
        <rect x="62" y="332" width="106" height="40" rx="8" fill="rgba(251,191,36,.14)" stroke="#fbbf24" stroke-dasharray="5 4"/>
        <text x="115" y="350" text-anchor="middle" fill="#fbbf24" font-size="10.5">shared_forward</text>
        <text x="115" y="364" text-anchor="middle" fill="#fbbf24" font-size="10.5">(limit_num_sms)</text>
        <text x="115" y="420" text-anchor="middle" fill="#8ea0c2" font-size="10">gate 输出 logical id,</text>
        <text x="115" y="434" text-anchor="middle" fill="#8ea0c2" font-size="10">经 logical_to_physical_map</text>
        <text x="115" y="448" text-anchor="middle" fill="#8ea0c2" font-size="10">映射到 physical 槽位</text>
        <circle cx="115" cy="500" r="8" fill="#22d3ee" class="pulse"/>

        <!-- 四张 EP 卡 -->
        <g>
          <rect class="node-gpu" x="360" y="70" width="200" height="150" rx="10"/>
          <text class="node-gpu-title" x="460" y="96" text-anchor="middle">EP rank 0</text>
          <text x="460" y="116" text-anchor="middle" fill="#8ea0c2" font-size="10.5">E0 E1 E2 E3(物理槽)</text>
          <rect x="380" y="130" width="70" height="22" rx="5" fill="rgba(34,211,238,.2)" stroke="#22d3ee"/><text x="415" y="145" text-anchor="middle" font-size="10" fill="#dbe4f5">E0: tok b</text>
          <rect x="456" y="130" width="84" height="22" rx="5" fill="rgba(34,211,238,.35)" stroke="#22d3ee" stroke-width="1.6"/><text x="498" y="145" text-anchor="middle" font-size="10" fill="#dbe4f5">E2: a,b,d 热!</text>
          <text x="460" y="182" text-anchor="middle" fill="#8ea0c2" font-size="10">grouped GEMM(psum 布局)</text>
          <text x="460" y="198" text-anchor="middle" fill="#8ea0c2" font-size="10">m_grouped_fp8_fp4_gemm</text>

          <rect class="node-gpu" x="640" y="70" width="200" height="150" rx="10"/>
          <text class="node-gpu-title" x="740" y="96" text-anchor="middle">EP rank 1</text>
          <text x="740" y="116" text-anchor="middle" fill="#8ea0c2" font-size="10.5">E4 E5 E6 E7</text>
          <rect x="660" y="130" width="80" height="22" rx="5" fill="rgba(167,139,250,.25)" stroke="#a78bfa"/><text x="700" y="145" text-anchor="middle" font-size="10" fill="#dbe4f5">E5: tok c</text>
          <rect x="748" y="130" width="80" height="22" rx="5" fill="rgba(34,211,238,.2)" stroke="#22d3ee"/><text x="788" y="145" text-anchor="middle" font-size="10" fill="#dbe4f5">E7: tok a</text>

          <rect class="node-gpu" x="360" y="300" width="200" height="150" rx="10"/>
          <text class="node-gpu-title" x="460" y="326" text-anchor="middle">EP rank 2</text>
          <text x="460" y="346" text-anchor="middle" fill="#8ea0c2" font-size="10.5">E8 E9 E10 E11</text>
          <rect x="380" y="360" width="80" height="22" rx="5" fill="rgba(52,211,153,.25)" stroke="#34d399"/><text x="420" y="375" text-anchor="middle" font-size="10" fill="#dbe4f5">E9: c,d</text>

          <rect class="node-gpu" x="640" y="300" width="200" height="150" rx="10"/>
          <text class="node-gpu-title" x="740" y="326" text-anchor="middle">EP rank 3</text>
          <text x="740" y="346" text-anchor="middle" fill="#8ea0c2" font-size="10.5">E12 E13 E14 E15</text>
          <text x="740" y="380" text-anchor="middle" fill="#8ea0c2" font-size="10">(空闲槽位 → EPLB 候选)</text>
        </g>

        <!-- dispatch 路径 -->
        <g stroke-width="2.2" fill="none">
          <path d="M190,148 C270,148 300,120 380,136" stroke="#22d3ee" class="flowline" marker-end="url(#m4c)"/>
          <path d="M190,148 C420,190 560,120 668,138" stroke="#22d3ee" class="flowline" marker-end="url(#m4c)"/>
          <path d="M190,226 C300,300 320,330 384,366" stroke="#22d3ee" class="flowline" marker-end="url(#m4c)"/>
          <path d="M190,186 C360,260 540,300 660,366" stroke="#22d3ee" class="flowline" marker-end="url(#m4c)"/>
        </g>
        <text x="268" y="120" fill="#22d3ee" font-size="11.5" font-weight="700">dispatch(NVLink 域内 / RDMA 跨机)</text>

        <!-- combine 路径 -->
        <g stroke-width="2.2" fill="none">
          <path d="M384,158 C300,200 260,470 196,492" stroke="#34d399" class="flowline" marker-end="url(#m4g)"/>
          <path d="M668,160 C480,240 300,460 198,486" stroke="#34d399" class="flowline" marker-end="url(#m4g)"/>
          <path d="M384,388 C300,430 250,486 198,478" stroke="#34d399" class="flowline" marker-end="url(#m4g)"/>
        </g>
        <text x="300" y="520" fill="#34d399" font-size="11.5" font-weight="700">combine(叠加 shared 结果:bias=shared_hidden_states)</text>

        <!-- 输出 -->
        <rect x="42" y="452" width="150" height="60" rx="10" fill="rgba(52,211,153,.08)" stroke="#34d399" stroke-width="1.8"/>
        <text x="117" y="476" text-anchor="middle" fill="#34d399" font-size="12" font-weight="700">moe_combined_hidden</text>
        <text x="117" y="494" text-anchor="middle" fill="#8ea0c2" font-size="10">event_overlap.current_stream_wait()</text>

        <!-- 底部时序条 -->
        <g font-size="11.5">
          <rect x="40" y="560" width="900" height="58" rx="10" fill="rgba(13,20,36,.9)" stroke="#263352"/>
          <rect x="60"  y="578" width="130" height="24" rx="6" fill="rgba(34,211,238,.3)" stroke="#22d3ee"/><text x="125" y="594" text-anchor="middle" fill="#dbe4f5">dispatch(异步)</text>
          <rect x="200" y="578" width="240" height="24" rx="6" fill="rgba(167,139,250,.25)" stroke="#a78bfa"/><text x="320" y="594" text-anchor="middle" fill="#dbe4f5">routed grouped GEMM ×2 + swiglu</text>
          <rect x="450" y="578" width="150" height="24" rx="6" fill="rgba(251,191,36,.22)" stroke="#fbbf24"/><text x="525" y="594" text-anchor="middle" fill="#dbe4f5">shared(限 SM 并行)</text>
          <rect x="610" y="578" width="130" height="24" rx="6" fill="rgba(52,211,153,.25)" stroke="#34d399"/><text x="675" y="594" text-anchor="middle" fill="#dbe4f5">combine(异步)</text>
          <rect x="750" y="578" width="170" height="24" rx="6" fill="rgba(79,140,255,.22)" stroke="#4f8cff"/><text x="835" y="594" text-anchor="middle" fill="#dbe4f5">wait → 返回主 hidden</text>
          <path d="M190,590 L200,590" stroke="#8ea0c2" marker-end="url(#m4p)"/><path d="M440,590 L450,590" stroke="#8ea0c2" marker-end="url(#m4p)"/>
          <path d="M600,590 L610,590" stroke="#8ea0c2" marker-end="url(#m4p)"/><path d="M740,590 L750,590" stroke="#8ea0c2" marker-end="url(#m4p)"/>
        </g>
        <!-- 数据包动画 -->
        <circle r="6" fill="#22d3ee" class="barrow"><animateMotion dur="2.4s" repeatCount="indefinite" path="M190,148 C270,148 300,120 380,136"/></circle>
        <circle r="6" fill="#22d3ee" class="barrow"><animateMotion dur="3s" begin="0.6s" repeatCount="indefinite" path="M190,148 C420,190 560,120 668,138"/></circle>
        <circle r="6" fill="#22d3ee" class="barrow"><animateMotion dur="2.8s" begin="1.2s" repeatCount="indefinite" path="M190,226 C300,300 320,330 384,366"/></circle>
        <circle r="6" fill="#34d399" class="barrow"><animateMotion dur="3.2s" repeatCount="indefinite" path="M384,158 C300,200 260,470 196,492"/></circle>
        <circle r="6" fill="#34d399" class="barrow"><animateMotion dur="3.8s" begin="0.9s" repeatCount="indefinite" path="M668,160 C480,240 300,460 198,486"/></circle>
        <circle r="5" fill="#fbbf24" class="barrow"><animateMotion dur="2.6s" repeatCount="indefinite" path="M115,372 L115,452"/></circle>
      </svg>
      <div class="cap">图 4-1 · dispatch/combine 动画:青色包 = token 按 top-k 路由发往专家卡;绿色包 = 计算结果 combine 回源并叠加 shared expert;底部为 forward 时间线(<code>mlp.py:565-616</code>)。</div>
    </div>

    <h3 style="color:#fff;margin:26px 0 10px;font-size:17px">dispatch / combine 的完整参数面</h3>
    <div class="filepath">deepinfer/model_executor/models/v4_modules/mlp.py:461-511 · DeepseekMoE.dispatch / combine</div>
    <pre class="code"><span class="k">def</span> <span class="f">dispatch</span>(self, hidden_states, topk_idx, topk_weights, input_metadata, dispatch_pre_evt):
    event_overlap = self.ep_buffer.dispatch(
        x=hidden_states,
        num_sms=envs.DEEPINFER_USERBUFFER_COMM_SMS,     <span class="c"># 通信专用 SM 数(见第 6 章)</span>
        topk_idx=topk_idx, topk_weights=topk_weights,
        cumulative_local_expert_recv_stats=self._eplb_layer().expert_count,  <span class="c"># EPLB 统计直连!</span>
        num_experts=self.num_physical_experts,
        num_max_tokens_per_rank=self.max_num_prefilling_tokens <span class="k">if</span> input_metadata.is_prompt <span class="k">else</span> self.max_num_decoding_tokens,
        expert_alignment=deep_gemm.get_mk_alignment_for_contiguous_layout(),
        previous_event=dispatch_pre_evt,
        async_with_compute_stream=<span class="k">True</span>,          <span class="c"># 与计算流异步 → event overlap</span>
        allocate_on_comm_stream=dispatch_pre_evt <span class="k">is not</span> <span class="k">None</span>,
        do_cpu_sync=input_metadata.is_prompt <span class="k">and</span> envs.DEEPINFER_YOCO_PREFILL_TRUNCATION_MODE != <span class="s">"compact"</span>,
        do_expand=<span class="k">True</span>, use_tma_aligned_col_major_sf=<span class="k">True</span>, defer_epilogue=<span class="k">True</span>)
    <span class="k">return</span> event_overlap

<span class="k">def</span> <span class="f">combine</span>(self, hidden_states, shared_hidden_states, handle, combine_pre_evt):
    <span class="k">return</span> self.ep_buffer.combine(
        x=hidden_states, handle=handle,
        num_sms=envs.DEEPINFER_USERBUFFER_COMM_SMS,
        bias=shared_hidden_states,      <span class="c"># shared expert 结果在 combine kernel 里直接累加</span>
        previous_event=combine_pre_evt, async_with_compute_stream=<span class="k">True</span>,
        allocate_on_comm_stream=combine_pre_evt <span class="k">is not</span> <span class="k">None</span>, defer_epilogue=<span class="k">True</span>)</pre>

    <table class="tbl">
      <tr><th>参数</th><th>取值</th><th>作用</th></tr>
      <tr><td><code>num_sms</code></td><td><code>DEEPINFER_USERBUFFER_COMM_SMS</code>(自动推导,见 6 章)</td><td>DeepEP 通信 kernel 使用的 SM 预算,与计算 kernel 抢占式共存</td></tr>
      <tr><td><code>cumulative_local_expert_recv_stats</code></td><td><code>eplb_layer.expert_count</code></td><td><b>EPLB 的统计入口</b>:dispatch kernel 每收到一个 token 顺带累加对应本地专家计数,零额外 kernel(<code>mlp.py:474</code>)</td></tr>
      <tr><td><code>num_max_tokens_per_rank</code></td><td>prefill / decode 两档</td><td>选择缓冲上限:prefill 用 <code>max_num_prefilling_tokens</code>(已除以 cp),decode 用 <code>max_num_decoding_tokens</code>(含 MTP 深度,<code>model_loader.py:119</code>)</td></tr>
      <tr><td><code>async_with_compute_stream</code></td><td>恒 <code>True</code></td><td>dispatch/combine 在<b>独立通信流</b>发射,计算流经 event 句柄衔接</td></tr>
      <tr><td><code>do_cpu_sync</code></td><td>prefill 且非 compact 模式</td><td>把接收计数同步回 CPU 供 grouped GEMM 的 <code>expected_m</code>;compact(YOCO)模式下关闭以免 CPU 瓶颈(<code>mlp.py:482-485</code> 注释)</td></tr>
      <tr><td><code>defer_epilogue</code></td><td>恒 <code>True</code></td><td>延迟归约尾部,配合 <code>allow_multiple_reduction</code> 减少 combine 轮次</td></tr>
      <tr><td><code>bias</code>(combine)</td><td><code>shared_hidden_states</code></td><td>共享专家输出在 combine 中融合,省一次独立 all-reduce</td></tr>
    </table>

    <h3 style="color:#fff;margin:26px 0 10px;font-size:17px">forward 编排:事件重叠与 SM 让渡</h3>
    <div class="filepath">deepinfer/model_executor/models/v4_modules/mlp.py:565-616 · DeepseekMoE.forward(非 mega 路径)</div>
    <pre class="code">topk_idx, topk_weights = self.gate_forward(hidden_states_bf16, input_metadata)   <span class="c"># :574</span>
<span class="c"># Dispatch —— 异步发射</span>
event_overlap = self.dispatch(hidden_states, topk_idx, topk_weights, input_metadata, <span class="k">None</span>)  <span class="c"># :578</span>
moe_in_hidden, _idx, dispatched_topk_weights, handle = event_overlap.current_stream_wait()  <span class="c"># :585</span>
<span class="c"># MoE 计算(grouped GEMM ×2 + swiglu,psum 布局按每专家接收计数分组)</span>
moe_out_hidden = self.routed_experts_forward(
    moe_in_hidden, dispatched_topk_weights, handle.psum_num_recv_tokens_per_expert, expected_m=<span class="k">None</span>)  <span class="c"># :593-598</span>
<span class="c"># Combine —— 先 capture 当前计算进度,shared expert 在受限 SM 下与 combine 并行</span>
combine_pre_evt = self.ep_buffer.capture()                                        <span class="c"># :601</span>
<span class="k">with</span> limit_num_sms(envs.DEEPINFER_USERBUFFER_COMM_SMS, enabled=PLATFORM.is_gpu):
    shared_out = self.shared_forward(hidden_states)                               <span class="c"># :602-603</span>
event_overlap = self.combine(moe_out_hidden, shared_out, handle, combine_pre_evt)  <span class="c"># :604</span>
moe_combined_hidden, _w = event_overlap.current_stream_wait()                     <span class="c"># :610</span></pre>
    <p style="font-size:14px;color:var(--muted)"><code>limit_num_sms</code>(<code>userbuffer.py:40-51</code>)通过 <code>deep_gemm.set_num_sms</code> / <code>tile_kernels.set_num_sms</code> 临时压缩计算 SM 数,给同时发射的 combine 通信 kernel 让出物理 SM —— 通信与计算在同一 GPU 上真正并发。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🚀</span>fast path:NVLink 域内 mega-MoE</h3>
        <p>当 EP 组在单个 NVLink 域内(<code>is_within_nvl_domain</code>,<code>mlp.py:187</code>),DeepInfer 改走 <b>mega-MoE 单内核路径</b>:dispatch/combine/grouped GEMM/shared expert 融合为 <code>deep_gemm.fp8_fp4_mega_moe</code> 一个调用(<code>mlp.py:549-559</code>),通信经 <code>SymmBuffer</code> 对称内存完成。注意它仍把 <code>cumulative_local_expert_recv_stats</code> 喂给 EPLB(<code>mlp.py:555</code>)—— 统计口径与普通路径完全一致。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🎛</span>gate:路由即 EPLB 的消费端</h3>
        <p><code>gate_forward</code>(<code>mlp.py:359-401</code>)把 <code>to_physical_map=eplb_layer.logical_to_physical_map</code> 与 <code>logical_count</code> 传入打分 kernel(<code>mlp.py:392-393</code>):logical 专家可映射到多个 physical 槽位,选择由计数加权 —— <b>重排完成后下一个 forward 立即生效,无需重启</b>。GPU 上用 <code>deep_gemm.bf16_mega_gate</code>(<code>mlp.py:397-398</code>)。压测旋钮 <code>DEEPINFER_FORCE_IMBALANCE_RATIO</code> 可强制制造不均衡路由(<code>mlp.py:367-371</code>,比值→评分因子的推导在 <code>mlp.py:347-357</code>)。</p>
      </div>
    </div>
  </section>

  <!-- ============================================================ 5 EPLB ============================================================ -->
  <section id="sec5">
    <h2 class="sec"><span class="num">5</span>EPLB:统计 → 策略 → 权重重排</h2>
    <p class="lede">EPLB(Expert Parallelism Load Balancer)是运行在 EP 之上的反馈回路:dispatch kernel 顺手计数 → 统计窗口滚动 → 到期把窗口内 token 数 all_reduce 成全局视图 → 贪心策略算出新放置 → P2P/IPC 搬权重 → gate 切换映射。</p>

    <div class="figure reveal">
      <svg viewBox="0 0 980 600" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="m5b" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto"><path d="M0,0 L8,3.5 L0,7 Z" fill="#4f8cff"/></marker>
          <marker id="m5c" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto"><path d="M0,0 L8,3.5 L0,7 Z" fill="#22d3ee"/></marker>
          <marker id="m5g" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto"><path d="M0,0 L8,3.5 L0,7 Z" fill="#34d399"/></marker>
          <marker id="m5y" markerWidth="9" markerHeight="9" refX="7" refY="3.5" orient="auto"><path d="M0,0 L8,3.5 L0,7 Z" fill="#fbbf24"/></marker>
        </defs>
        <text x="490" y="30" text-anchor="middle" fill="#dbe4f5" font-size="16" font-weight="700">EPLB 闭环:每 step 计数,每 interval 步重排</text>

        <!-- 阶段1 统计 -->
        <rect x="30" y="60" width="280" height="240" rx="14" fill="rgba(34,211,238,.05)" stroke="#22d3ee" stroke-width="2"/>
        <text x="170" y="88" text-anchor="middle" fill="#22d3ee" font-size="14" font-weight="700">① 统计(every step)</text>
        <text x="46" y="114" fill="#8ea0c2" font-size="11">· dispatch kernel 累加 expert_count</text>
        <text x="46" y="132" fill="#8ea0c2" font-size="11">  [num_moe_layers, num_local_physical]</text>
        <g>
          <rect x="52" y="146" width="60" height="26" rx="5" fill="rgba(79,140,255,.3)" stroke="#4f8cff"/><text x="82" y="163" text-anchor="middle" font-size="10" fill="#dbe4f5">step t-1</text>
          <rect x="120" y="146" width="60" height="26" rx="5" fill="rgba(79,140,255,.3)" stroke="#4f8cff"/><text x="150" y="163" text-anchor="middle" font-size="10" fill="#dbe4f5">step t</text>
          <rect x="188" y="146" width="60" height="26" rx="5" fill="rgba(79,140,255,.3)" stroke="#4f8cff"/><text x="218" y="163" text-anchor="middle" font-size="10" fill="#dbe4f5">step t+1</text>
          <rect x="256" y="146" width="40" height="26" rx="5" fill="rgba(79,140,255,.15)" stroke="#4f8cff" stroke-dasharray="4 3"/><text x="276" y="163" text-anchor="middle" font-size="10" fill="#8ea0c2">…</text>
        </g>
        <text x="46" y="200" fill="#8ea0c2" font-size="11">· 滚动窗口 ring buffer(默认 100 步):</text>
        <g>
          <rect x="52" y="212" width="30" height="22" rx="4" fill="rgba(34,211,238,.28)" stroke="#22d3ee"/><rect x="86" y="212" width="30" height="22" rx="4" fill="rgba(34,211,238,.28)" stroke="#22d3ee"/>
          <rect x="120" y="212" width="30" height="22" rx="4" fill="rgba(34,211,238,.28)" stroke="#22d3ee"/><rect x="154" y="212" width="30" height="22" rx="4" fill="rgba(34,211,238,.12)" stroke="#22d3ee" stroke-dasharray="4 3"/>
          <text x="196" y="228" fill="#8ea0c2" font-size="10.5">窗口 = 重排依据</text>
        </g>
        <text x="46" y="264" fill="#8ea0c2" font-size="11">· 另一支:每 128 步 all_gather_into_tensor</text>
        <text x="46" y="282" fill="#8ea0c2" font-size="11">  各 rank token 总量 → moe_load_balance_ratio</text>

        <!-- 阶段2 策略 -->
        <rect x="350" y="60" width="280" height="240" rx="14" fill="rgba(167,139,250,.05)" stroke="#a78bfa" stroke-width="2"/>
        <text x="490" y="88" text-anchor="middle" fill="#a78bfa" font-size="14" font-weight="700">② 策略(rearrange 到期时)</text>
        <text x="366" y="118" fill="#8ea0c2" font-size="11">scatter_add_:本地 physical 计数聚合到 logical,</text>
        <text x="366" y="136" fill="#8ea0c2" font-size="11">再 EP 组 all_reduce 成全局视图</text>
        <g>
          <rect x="380" y="152" width="220" height="34" rx="8" fill="#0d1424" stroke="#263352"/>
          <text x="490" y="173" text-anchor="middle" font-size="10.5" fill="#c792ea">tokens_per_expert[window, layers, logical]</text>
        </g>
        <text x="366" y="212" fill="#8ea0c2" font-size="11">rebalance_experts_global 两段贪心:</text>
        <g font-size="11">
          <rect x="380" y="224" width="220" height="30" rx="8" fill="rgba(251,191,36,.12)" stroke="#fbbf24"/>
          <text x="490" y="243" text-anchor="middle" fill="#fbbf24">a. 冗余副本分配(热点专家复制)</text>
          <rect x="380" y="260" width="220" height="30" rx="8" fill="rgba(52,211,153,.12)" stroke="#34d399"/>
          <text x="490" y="279" text-anchor="middle" fill="#34d399">b. 副本贪心排布到各 rank</text>
        </g>

        <!-- 阶段3 重排 -->
        <rect x="670" y="60" width="280" height="240" rx="14" fill="rgba(52,211,153,.05)" stroke="#34d399" stroke-width="2"/>
        <text x="810" y="88" text-anchor="middle" fill="#34d399" font-size="14" font-weight="700">③ 权重重排(in-place)</text>
        <g font-size="11">
          <rect x="690" y="106" width="240" height="40" rx="8" fill="rgba(79,140,255,.12)" stroke="#4f8cff"/>
          <text x="810" y="123" text-anchor="middle" fill="#4f8cff">跨机:batch_isend_irecv</text>
          <text x="810" y="139" text-anchor="middle" fill="#8ea0c2">按 (rank差 mod 组数) 分桶批量收发</text>
          <rect x="690" y="156" width="240" height="40" rx="8" fill="rgba(34,211,238,.10)" stroke="#22d3ee"/>
          <text x="810" y="173" text-anchor="middle" fill="#22d3ee">单机:symm_mem/IPC 镜像直读</text>
          <text x="810" y="189" text-anchor="middle" fill="#8ea0c2">无 P2P 通信,barrier 同步逐层刷新</text>
        </g>
        <text x="686" y="222" fill="#8ea0c2" font-size="11">新映射生效:</text>
        <g>
          <rect x="690" y="232" width="110" height="26" rx="6" fill="#0d1424" stroke="#263352"/><text x="745" y="249" text-anchor="middle" font-size="9.5" fill="#89ddff">physical_to_logical</text>
          <rect x="810" y="232" width="120" height="26" rx="6" fill="#0d1424" stroke="#263352"/><text x="870" y="249" text-anchor="middle" font-size="9.5" fill="#89ddff">logical_to_physical</text>
          <path d="M800,245 L810,245" stroke="#8ea0c2" marker-end="url(#m5g)"/>
        </g>
        <text x="686" y="284" fill="#8ea0c2" font-size="11">→ gate 下一 forward 即用新映射路由</text>

        <!-- 阶段间箭头 -->
        <path d="M310,180 L350,180" stroke="#4f8cff" stroke-width="2.6" class="flowline" marker-end="url(#m5b)"/>
        <path d="M630,180 L670,180" stroke="#a78bfa" stroke-width="2.6" class="flowline" marker-end="url(#m5b)"/>
        <path d="M810,300 C810,360 170,360 170,300" stroke="#34d399" stroke-width="2.4" fill="none" class="flowline" marker-end="url(#m5g)"/>
        <text x="490" y="352" text-anchor="middle" fill="#34d399" font-size="11.5">反馈:重排后的负载差异进入下一个统计窗口</text>

        <!-- P2P 细节面板 -->
        <rect x="30" y="384" width="920" height="180" rx="12" fill="rgba(13,20,36,.9)" stroke="#263352"/>
        <text x="52" y="412" fill="#dbe4f5" font-size="13" font-weight="700">P2P 重排细节:三个 rank 交换专家权重(shuffle.py:94-147)</text>
        <g>
          <rect class="node-gpu" x="80" y="430" width="150" height="100" rx="10"/>
          <text class="node-gpu-title" x="155" y="454" text-anchor="middle" font-size="12">rank 0</text>
          <rect x="98" y="466" width="52" height="20" rx="4" fill="rgba(251,191,36,.3)" stroke="#fbbf24"/><text x="124" y="480" text-anchor="middle" font-size="9.5" fill="#dbe4f5">E2</text>
          <rect x="158" y="466" width="52" height="20" rx="4" fill="rgba(79,140,255,.25)" stroke="#4f8cff"/><text x="184" y="480" text-anchor="middle" font-size="9.5" fill="#dbe4f5">E7</text>
          <text x="155" y="516" text-anchor="middle" font-size="9.5" fill="#8ea0c2">槽位不变,内容换血</text>
          <rect class="node-gpu" x="415" y="430" width="150" height="100" rx="10"/>
          <text class="node-gpu-title" x="490" y="454" text-anchor="middle" font-size="12">rank 1</text>
          <rect x="433" y="466" width="52" height="20" rx="4" fill="rgba(52,211,153,.25)" stroke="#34d399"/><text x="459" y="480" text-anchor="middle" font-size="9.5" fill="#dbe4f5">E5</text>
          <rect x="493" y="466" width="52" height="20" rx="4" fill="rgba(34,211,238,.25)" stroke="#22d3ee"/><text x="519" y="480" text-anchor="middle" font-size="9.5" fill="#dbe4f5">E9</text>
          <rect class="node-gpu" x="750" y="430" width="150" height="100" rx="10"/>
          <text class="node-gpu-title" x="825" y="454" text-anchor="middle" font-size="12">rank 2</text>
          <rect x="768" y="466" width="52" height="20" rx="4" fill="rgba(167,139,250,.25)" stroke="#a78bfa"/><text x="794" y="480" text-anchor="middle" font-size="9.5" fill="#dbe4f5">E11</text>
          <rect x="828" y="466" width="52" height="20" rx="4" fill="rgba(251,191,36,.3)" stroke="#fbbf24"/><text x="854" y="480" text-anchor="middle" font-size="9.5" fill="#dbe4f5">E2′</text>
          <text x="825" y="516" text-anchor="middle" font-size="9.5" fill="#8ea0c2">E2 复制到新 rank(冗余副本)</text>
        </g>
        <path d="M232,470 C320,440 350,450 413,468" stroke="#fbbf24" stroke-width="2.2" class="flowline" marker-end="url(#m5y)"/>
        <path d="M567,486 C660,510 700,500 748,486" stroke="#a78bfa" stroke-width="2.2" class="flowline" marker-end="url(#m5g)"/>
        <text x="320" y="440" fill="#fbbf24" font-size="10.5">isend(E2 权重)</text>
        <text x="628" y="516" fill="#a78bfa" font-size="10.5">irecv(E11 → 腾槽)</text>
        <circle r="6" fill="#fbbf24" class="barrow"><animateMotion dur="2.4s" repeatCount="indefinite" path="M232,470 C320,440 350,450 413,468"/></circle>
        <circle r="6" fill="#a78bfa" class="barrow"><animateMotion dur="2.8s" begin="0.8s" repeatCount="indefinite" path="M567,486 C660,510 700,500 748,486"/></circle>
        <text x="52" y="552" fill="#8ea0c2" font-size="10.5">收发双方用同一 _paired_sender 函数配对(j//n 规则,shuffle.py:47-53),保证 P2P 两端一致;每桶 dist.batch_isend_irecv(ops) 后逐 req.wait()(:135-138)</text>
      </svg>
      <div class="cap">图 5-1 · EPLB 闭环全景:统计(青)→ 策略(紫)→ 重排(绿),底部为 P2P 权重交换细节。引用:<code>eplb/__init__.py:131-288</code>、<code>policy.py:73-140</code>、<code>shuffle.py:94-147</code>。</div>
    </div>

    <h3 style="color:#fff;margin:26px 0 10px;font-size:17px">① 统计:零成本计数与两个观测通道</h3>
    <div class="filepath">deepinfer/model_executor/eplb/__init__.py:131-193 · step / _update_rearrangement / _update_load_balance_stats</div>
    <pre class="code"><span class="k">def</span> <span class="f">step</span>(self, is_prompt):                       <span class="c"># 由 DeepseekForCausalLM.sample 每 step 调用 (deepseek.py:402-404)</span>
    <span class="k">if</span> self._ep_group.size() &lt;= <span class="n">1</span>: <span class="k">return</span>
    self._update_rearrangement(is_prompt)
    self._update_load_balance_stats()
    self.expert_count.zero_()                    <span class="c"># 本 step 计数清零,等待下个 dispatch 再累计</span>

<span class="k">def</span> <span class="f">_update_rearrangement</span>(self, is_prompt):
    window_index = self._expert_count_window_index
    self._expert_count_window[window_index].copy_(self.expert_count)   <span class="c"># 滚动窗口写入</span>
    self._expert_count_window_index = (window_index + <span class="n">1</span>) % self._expert_count_window.size(<span class="n">0</span>)
    ...
    self._rearrangement_step += <span class="n">1</span>
    <span class="k">if</span> self._rearrangement_step &lt; self._rearrangement_interval: <span class="k">return</span>
    self._rearrangement_step = <span class="n">0</span>
    self._rearrange_experts()

<span class="k">def</span> <span class="f">_update_load_balance_stats</span>(self):
    torch.sum(self.expert_count, dim=-<span class="n">1</span>, dtype=torch.long, out=self._local_tokens_per_step[stat_index])
    ...
    dist.all_gather_into_tensor(gathered_tokens, self._local_tokens_per_step, group=self._ep_group)  <span class="c"># :188</span>
    self.moe_load_balance_ratio = (tokens_per_rank.mean(...).sum().to(<span class="s">"cpu"</span>, non_blocking=<span class="k">True</span>),
                                   tokens_per_rank.max(...).sum().to(<span class="s">"cpu"</span>, non_blocking=<span class="k">True</span>))</pre>
    <p style="font-size:14px;color:var(--muted)">两条独立通道:<b>重排通道</b>(逐专家计数,决定放置)与 <b>观测通道</b>(rank 级 token 总量,每 <code>DEEPINFER_MOE_LB_STAT_INTERVAL=128</code> 步 all_gather 一次,产出 <code>(avg, max)</code> 比值,经 <code>take_moe_load_balance_ratio</code>(<code>eplb/__init__.py:387-395</code>)供调度器/监控消费;迁移到 CPU 用 <code>non_blocking</code> 避免同步)。</p>

    <h3 style="color:#fff;margin:26px 0 10px;font-size:17px">② 策略:rebalance_experts_global 的两段贪心</h3>
    <div class="filepath">deepinfer/model_executor/eplb/policy.py:73-140 · rebalance_experts_global</div>
    <pre class="code"><span class="c"># 初始:前 num_logical 槽位放 identity,冗余槽位待分配</span>
physical_to_logical_map[:, :num_logical_experts] = arange_logical

<span class="c"># a. 冗余副本贪心:每轮给一个 expert 加副本,最小化「最大每副本负载」</span>
tokens_per_expert_all_diff = tokens_per_expert + arange_logical * <span class="n">1e-4</span>   <span class="c"># 打破平局,保证确定性</span>
<span class="k">for</span> i <span class="k">in</span> range(num_redundant_experts):
    score = tokens_per_expert_all_diff / logical_count          <span class="c"># 当前每副本负载</span>
    score_added = tokens_per_expert / (logical_count + <span class="n">1</span>)      <span class="c"># 加一个副本后的负载</span>
    values, indices = score.max(-<span class="n">1</span>, keepdim=<span class="k">True</span>)
    ...                                                             <span class="c"># 用 score_added 替换 argmax 位再取 max</span>
    redundancy_indices = values.sum(<span class="n">0</span>).argmin(-<span class="n">1</span>)                   <span class="c"># [num_moe_layers] 本轮复制谁</span>
    physical_to_logical_map[:, num_logical_experts + i] = redundancy_indices
    logical_count[arange_layers, redundancy_indices] += <span class="n">1</span>

<span class="c"># b. 排布贪心:_batch_greedy_indices 把全部 physical 副本分到各 rank</span>
<span class="k">if</span> num_local_physical_experts &gt; <span class="n">1</span>:
    indices = _batch_greedy_indices(tokens_per_expert, physical_to_logical_map,
                                    logical_count, num_local_physical_experts)
    physical_to_logical_map = physical_to_logical_map.gather(-<span class="n">1</span>, indices)</pre>
    <table class="tbl">
      <tr><th>策略阶段</th><th>目标函数</th><th>贪心规则</th><th>代码位置</th></tr>
      <tr><td>冗余副本分配</td><td>逐层最小化 <code>sum_step max_j (负载_j/副本数_j)</code>(每副本峰值负载之和)</td><td>每轮模拟「给 argmax expert 加一副本」,取总和最小者;1e-4 扰动保证确定性</td><td><code>policy.py:109-123</code></td></tr>
      <tr><td>副本→rank 排布</td><td><code>sum_step max_rank (rank 内各 expert 在该 step 的负载和)</code> —— 对窗口内每一步的历史负载 jointly 优化</td><td>expert 按每副本历史负载<b>降序</b>入场;每个 expert 试放到各 rank,选使目标最小者;已满 rank 屏蔽(<code>occupancy==capacity → inf</code>),同分 argmin 取最小 rank ID</td><td><code>policy.py:12-70</code>(排序 :34,目标 :44-45,屏蔽 :62,argmin :63)</td></tr>
    </table>
    <div class="note">
      <b>为什么用历史多步而非单步?</b>窗口(<code>window_size</code> 步)内的负载向量被当作多目标联合优化:单步贪心会在抖动负载下来回搬运权重;对整个窗口求和的峰值最小化则只在<b>持续</b>偏斜时才改变放置。首排提前(<code>eplb/__init__.py:121-123</code>:<code>interval - interval//4</code>)则用于尽快纠正冷启动不均衡。
    </div>

    <h3 style="color:#fff;margin:26px 0 10px;font-size:17px">③ 重排:两条搬运路径</h3>
    <div class="filepath">deepinfer/model_executor/eplb/shuffle.py:94-147 · _shuffle_layer_p2p(P2P 路径核心)</div>
    <pre class="code"><span class="c"># 卡内可满足的搬运:origin→缓冲 直拷</span>
received, intra_copies = _plan_intra_copies(origin_local, current_local)
<span class="c"># 跨卡:按 (对端 rank 差 mod 组数) 分桶,逐桶批量收发</span>
p2p_buckets = [[] <span class="k">for</span> _ <span class="k">in</span> range(envs.DEEPINFER_REARRANGE_P2P_GROUPS)]     <span class="c"># :114</span>
<span class="k">for</span> expert, src <span class="k">in</span> _first_slot_per_expert(origin_local):               <span class="c"># 发送侧</span>
    senders, receivers = _remote_routes(origin, current, num_local, expert)
    <span class="k">for</span> j, dst <span class="k">in</span> enumerate(receivers):
        <span class="k">if</span> _paired_sender(j, len(senders), len(receivers)) == my_index:    <span class="c"># 收发同函数配对</span>
            p2p_buckets[(ep_rank - dst) % len(p2p_buckets)].extend(
                dist.P2POp(dist.isend, weight[src], dist.get_global_rank(ep, dst), ep) <span class="k">for</span> weight <span class="k">in</span> weights)
<span class="k">for</span> expert, dst <span class="k">in</span> experts_to_recv:                                     <span class="c"># 接收侧</span>
    ...
    p2p_buckets[(src_rank - ep_rank) % len(p2p_buckets)].extend(
        dist.P2POp(dist.irecv, buf[dst], ...) <span class="k">for</span> buf <span class="k">in</span> recv_buffers)
<span class="k">for</span> ops <span class="k">in</span> p2p_buckets:
    <span class="k">if</span> ops:
        <span class="k">for</span> req <span class="k">in</span> dist.batch_isend_irecv(ops):   <span class="c"># :137 每桶一次批量 P2P</span>
            req.wait()</pre>
    <table class="tbl">
      <tr><th>路径</th><th>触发条件</th><th>机制</th><th>代码位置</th></tr>
      <tr><td><b>P2P(NCCL/HCCL)</b></td><td>EP 组跨 NVLink 域,或 NPU(symm_mem 未支持)</td><td><code>dist.P2POp(isend/irecv)</code> 按 rank 差分桶;<code>batch_isend_irecv</code> 批量执行;接收缓冲跨层复用(各层 hidden 同宽假设,:81-82)</td><td><code>shuffle.py:65-147</code></td></tr>
      <tr><td><b>IPC 直读(单机)</b></td><td><code>is_within_nvl_domain(ep_group) and PLATFORM.is_gpu</code>(<code>eplb/__init__.py:200</code>)</td><td>首次重排时 <code>symm_mem.empty</code> 建一层权重大小的镜像 + <code>rendezvous</code> 拿全 rank 句柄;逐层「barrier → 刷镜像 → barrier → 直接 <code>copy_</code> 对端显存」,无网络通信</td><td><code>eplb/__init__.py:195-220</code>、<code>shuffle.py:150-218</code></td></tr>
    </table>
    <p style="font-size:14px;color:var(--muted)">重排完成后,三张映射表整体替换(<code>eplb/__init__.py:276-278</code>):<code>physical_to_logical_map</code>、<code>logical_to_physical_map</code>、<code>logical_count</code>;rank 0 记录 <code>rank_balance / logical_balance / physical_peak</code> 与耗时(<code>eplb/__init__.py:290-325</code>),<code>DEEPINFER_SHOW_EPLB_DETAIL=1</code> 时还打印逐层逐专家的负载表格。</p>

    <table class="tbl">
      <tr><th>时序参数</th><th>默认 / 约束</th><th>语义</th></tr>
      <tr><td><code>DEEPINFER_EXPERT_COUNT_WINDOW_SIZE</code></td><td>100;启用重排时须 <code>1 ≤ w ≤ interval</code></td><td>重排依据的滑动窗口步数(<code>eplb/__init__.py:102-111</code> 校验)</td></tr>
      <tr><td><code>DEEPINFER_EXPERT_REARRANGEMENT_STEP_INTERVAL</code></td><td>未设(=0 关闭)</td><td>每多少 step 重排一次;首次提前到 <code>interval - interval//4</code>(:121-123)</td></tr>
      <tr><td><code>DEEPINFER_REARRANGE_AFTER_PREFILL_IN_NORMAL_ENGINE</code></td><td>False</td><td>NORMAL 引擎 prefill 后立即安排重排(:83-84,156-159);否则 prefill 步跳过重排</td></tr>
      <tr><td><code>DEEPINFER_MOE_LB_STAT_INTERVAL</code></td><td>128,须 &gt; 0</td><td>rank 级 LB 观测的 all_gather 周期(:125-129)</td></tr>
      <tr><td><code>DEEPINFER_OVERRIDE_NUM_EXTRA_EXPERTS</code></td><td>未设</td><td>冗余专家数下限,加载时向上取整到可整除(<code>model_loader.py:94-99</code>)</td></tr>
      <tr><td><code>DEEPINFER_REARRANGE_P2P_GROUPS</code></td><td>1</td><td>P2P 分桶数;桶越多并发交换轮次越多(:114)</td></tr>
      <tr><td><code>DEEPINFER_FORCE_IMBALANCE_RATIO</code> / <code>DEEPINFER_SHOW_EPLB_DETAIL</code></td><td>—</td><td>压测注入不均衡 / 打印逐专家明细(<code>mlp.py:367-371</code> / <code>eplb/__init__.py:327-343</code>)</td></tr>
    </table>

    <div class="note good">
      <b>EPLB 的分组组织:</b>同构 MoE 层(相同 logical/physical 数、相同 EP 组、相同权重形状)共享一个 <code>ExpertLoadBalancer</code>,主模型层与 DFlash/MTP 层分别成组(<code>deepseek.py:324-365</code> <code>_init_eplb</code>,按 layout 元组分组后 <code>set_current(ExpertLoadBalancerManager(...))</code>)。每层的 <code>logical_to_physical_map</code> 独立 —— <b>每层可以有不同的专家放置</b>,这正是 V4.1-Flash「层间负载差异大」所需要的粒度。
    </div>
  </section>

  <!-- ============================================================ 6 缓冲区管理 ============================================================ -->
  <section id="sec6">
    <h2 class="sec"><span class="num">6</span>通信缓冲区管理:_UserBufferManager</h2>
    <p class="lede">进程级单例 <code>userbuffer</code>(<code>userbuffer.py:240</code>)持有四类通信缓冲:EPBuffer(DeepEP)、CPManager(BucketBuffer)、EngramBuffer、SymmBuffer(DeepGEMM)。所有已加载模型共享它们 —— 尺寸只增不减、后分配者必须是前者的视图。</p>

    <table class="tbl">
      <tr><th>缓冲</th><th>归属库 / 组</th><th>尺寸来源</th><th>复用规则</th></tr>
      <tr><td><code>EPBuffer</code>(<code>userbuffer.py:63-95</code>)</td><td>DeepEP-V2 · EP 组</td><td><code>EPBuffer.get_buffer_size_hint(max_num_tokens, hidden, num_topk, fp8_dispatch, hybrid)</code>;再次分配断言 <code>num_bytes ≥ hint</code>(:82)</td><td>整个进程一块;<code>allow_multiple_reduction</code> 在「批次不变 + 启用重排」时强制关闭以保证确定性(:79)</td></tr>
      <tr><td><code>CPManager</code>(<code>userbuffer.py:97-117</code>)</td><td>DeepEP BucketBuffer · CP 组</td><td><code>max_num_tokens × max_ag_bytes_per_token × cp_size + 8 × rdma 对齐</code>,再向上对齐(:107-110)</td><td>多模型共存时断言旧缓冲足够;会话内多次 all-gather 复用同一存储</td></tr>
      <tr><td><code>EngramBuffer</code>(<code>userbuffer.py:127-181</code>)</td><td>DeepEP-V2-Engram · ENP 组</td><td><code>get_storage_size_hint(...)</code> + <code>get_theoretical_config</code> 推 QP 数/深度(:138-154)</td><td>仅可分配一次(:137 assert);RDMA 存储默认放 CPU(省显存),昇腾强制 GPU(:148,154);服务层 sl3,kv cache 留 sl2 流量隔离(:155)</td></tr>
      <tr><td><code>SymmBuffer</code>(<code>userbuffer.py:183-225</code>)</td><td>DeepGEMM · EP 组</td><td>由 <code>_SymBufferSpec</code>(group/num_experts/topk/hidden/mma_type… )唯一确定</td><td><b>第一个 spec 必须最大</b>(拥有底层存储,docstring :195-197);后续 spec 以 <code>base=</code> 挂成缓存视图;相等 spec 共享实例(构造后不可变)</td></tr>
    </table>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📐</span>CP 缓冲的精确公式</h3>
        <p><code>max_ag_bytes_per_token</code> 由模型侧汇总:输出 hidden(<code>hidden*2</code> 字节)与各注意力层的 KV/索引投影宽度取 max(<code>deepseek.py:415-430</code>;单层口径见 <code>attn.py:375-384</code> <code>get_max_ag_bytes_per_token</code>:kv_swa FP32 + 投影 KV + indexer 上界)。乘 <code>cp_size</code> 是因为 all-gather 后每 rank 都要看到全组数据。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🔥</span>通信 SM 预算的自动推导</h3>
        <p><code>DEEPINFER_USERBUFFER_COMM_SMS==0</code> 时(<code>userbuffer.py:86-90</code>):<code>theoretical = EPBuffer.get_theoretical_num_sms(experts, topk)</code>,计算侧保底 <code>min(32, device_sms//4)</code>,最终取 <code>min(theoretical, device_sms - compute)</code>。NCCL 子组的 CTA 数也由 <code>DEEPINFER_NCCL_NUM_SMS=32</code> 固定(<code>platform.py:75-83</code> 的 max/min_ctas)—— 三家通信库的 SM 消耗都被显式约束,避免互相挤兑。</p>
      </div>
    </div>

    <div class="filepath">deepinfer/model_executor/parallel_utils/userbuffer.py:183-225 · allocate_sym_buffer(视图复用)</div>
    <pre class="code"><span class="k">def</span> <span class="f">allocate_sym_buffer</span>(self, ep_group, num_experts, max_num_tokens, num_topk,
                         hidden_size, moe_intermediate_size, num_shared_experts, mma_type, activation):
    <span class="s">"""The first spec allocated must be the largest: it owns the backing storage,
    later specs are cached views of it. Callers passing equal specs share one
    instance; that is safe since SymmBuffer never mutates after construction."""</span>
    spec = _SymBufferSpec(...)
    buffer = self._sym_buffers.get(spec)
    <span class="k">if</span> buffer <span class="k">is not</span> <span class="k">None</span>: <span class="k">return</span> buffer            <span class="c"># 相同 spec 直接复用</span>
    base = next(iter(self._sym_buffers.values()), <span class="k">None</span>)       <span class="c"># 取基座(首个分配者)</span>
    <span class="k">if</span> base <span class="k">is</span> <span class="k">None</span> <span class="k">and</span> PLATFORM.is_gpu:
        <span class="c"># 首次使用会触发 DeepGEMM 的 SM locality 探测(含同步),</span>
        <span class="c"># 提前到这里做,避开 guarded forward 与 CUDA graph 捕获 :216-220</span>
        ...
    buffer = deep_gemm.SymmBuffer(**spec._asdict(), base=base)   <span class="c"># 后续 spec 以视图挂载</span></pre>

    <div class="note warn">
      <b>生命周期:</b><code>close()</code>(<code>userbuffer.py:227-237</code>)逆序销毁 sym buffer(先视图后基座)、逐个 <code>destroy()</code> EP/CP/Engram 缓冲并 <code>vars(buffer).clear()</code>。CPManager 每次会话结束只是归还存储,<code>destroy</code> 显式触发 DeepEP 侧资源释放(<code>cp.py:53-54</code>)—— 与 <code>explicitly_destroy=True</code> 的构造参数配套,防止依赖进程外 comm 的延迟释放。
    </div>
  </section>

  <!-- ============================================================ 7 配置汇总 ============================================================ -->
  <section id="sec7">
    <h2 class="sec"><span class="num">7</span>配置项汇总</h2>
    <p class="lede">并行策略相关的全部环境变量(<code>deepinfer/environ.py</code>)与启动参数(<code>config.py:ParallelConfig</code>),含默认值与生效点。</p>

    <table class="tbl">
      <tr><th>配置项</th><th>默认</th><th>作用域</th><th>生效点(file:line)</th></tr>
      <tr><td><code>DEEPINFER_USERBUFFER_COMM_SMS</code></td><td>0=自动</td><td>DeepEP EP/CP 通信 kernel 的 SM 数</td><td><code>userbuffer.py:86-90</code> 推导;消费:<code>mlp.py:471,504,602</code></td></tr>
      <tr><td><code>DEEPINFER_NCCL_NUM_SMS</code></td><td>32</td><td>NCCL 子组 max/min CTAs</td><td><code>platform.py:75-83</code></td></tr>
      <tr><td><code>DEEPINFER_REARRANGE_P2P_GROUPS</code></td><td>1</td><td>EPLB P2P 交换分桶数</td><td><code>shuffle.py:114,122,131</code></td></tr>
      <tr><td><code>DEEPINFER_OVERRIDE_NUM_EXTRA_EXPERTS</code></td><td>未设</td><td>冗余专家下限(取整到可整除)</td><td><code>model_loader.py:122-123</code> → <code>eplb/__init__.py:21-28</code></td></tr>
      <tr><td><code>DEEPINFER_EXPERT_COUNT_WINDOW_SIZE</code></td><td>100</td><td>重排统计窗口(步)</td><td><code>eplb/__init__.py:102-111,152-154</code></td></tr>
      <tr><td><code>DEEPINFER_EXPERT_REARRANGEMENT_STEP_INTERVAL</code></td><td>未设(0=关)</td><td>重排周期;亦影响 multiple-reduction 确定性</td><td><code>eplb/__init__.py:103,146-165</code>、<code>userbuffer.py:79</code></td></tr>
      <tr><td><code>DEEPINFER_REARRANGE_AFTER_PREFILL_IN_NORMAL_ENGINE</code></td><td>False</td><td>NORMAL 引擎 prefill 后立即重排</td><td><code>eplb/__init__.py:83-84,156-159</code></td></tr>
      <tr><td><code>DEEPINFER_MOE_LB_STAT_INTERVAL</code></td><td>128</td><td>rank 级 LB 观测周期</td><td><code>eplb/__init__.py:125-129,167-193</code></td></tr>
      <tr><td><code>DEEPINFER_FORCE_IMBALANCE_RATIO</code></td><td>未设</td><td>压测:注入指定倍率不均衡</td><td><code>mlp.py:347-371</code></td></tr>
      <tr><td><code>DEEPINFER_SHOW_EPLB_DETAIL</code></td><td>False</td><td>打印逐层逐专家负载表</td><td><code>eplb/__init__.py:327-343</code></td></tr>
      <tr><td><code>DEEPINFER_ENGRAM_FORCE_GPU_STORAGE</code></td><td>False(昇腾恒 True)</td><td>Engram RDMA 存储放 GPU</td><td><code>environ.py:154</code>、<code>userbuffer.py:148</code></td></tr>
      <tr><td><code>DEEPINFER_GLOO_TIMEOUT</code></td><td>14400s</td><td>默认 gloo PG 超时(重排等长操作的安全阀)</td><td><code>environ.py:117</code>、<code>worker/base.py:335</code></td></tr>
      <tr><td>启动:<code>data_parallel_size</code></td><td>0 → <code>ep//cp</code></td><td>DP 副本数</td><td><code>config.py:161-162</code></td></tr>
      <tr><td>启动:<code>context_parallel_size</code></td><td>—</td><td>mirror-CP 组大小(= model_parallel_size)</td><td><code>config.py:171</code></td></tr>
      <tr><td>启动:<code>expert_parallel_size</code> / <code>engram_parallel_size</code></td><td>— / 0 → cp×dp</td><td>EP 段大小 / ENP 组大小</td><td><code>config.py:165,172</code></td></tr>
    </table>

    <div class="note">
      <b>推荐起步组合</b>(单机 8×SM100,256 专家 / top-8 类配置):<code>dp = ep // cp</code> 交给框架推导;长上下文 prefill 瓶颈明显时开 <code>cp=2/4</code>;EPLB 用默认 <code>window=100</code>,<code>interval</code> 从 1000 起调,观测 <code>[EPLB] rearranged: ... rank_balance=...</code> 日志趋于 1 后再放宽 interval。跨机 EP 时保持 <code>ep ≤ 单机卡数</code> 可让 mega-MoE + IPC shuffle 双 fast path 生效。
    </div>
  </section>

  <!-- ============================================================ 8 总结 ============================================================ -->
  <section id="sec8">
    <h2 class="sec"><span class="num">8</span>总结</h2>
    <p class="lede">DeepInfer 并行策略的设计主线:用「复制 + 序列切分」取代张量并行,用「运行时反馈」取代静态专家放置。</p>

    <div class="timeline">
      <div class="tl-item reveal">
        <div class="tl-date">PARALLEL STATE</div>
        <div class="tl-body">一个 <code>ParallelProcessGroup</code> 管 8 类组,einops rearrange 模式串即拓扑定义;gloo 默认 PG + <code>init_device_groups</code> eager all_reduce 保证 NCCL/HCCL 子组真正建链,连单 rank 组也不放过(engram <code>_comm_ptr</code> 依赖)。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">ATTENTION</div>
        <div class="tl-body">全 <code>ReplicatedLinear</code> 复制 → Attention DP 零通信;prefill 走 mirror-CP(块对 <code>(r, 2cp-1-r)</code> 交错切分)均衡 SWA/压缩 KV;每层把 KV all-gather 的发射提前到 Q 投影之前,BucketBuffer 会话把多次聚合合并、缓冲复用。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">MOE EP</div>
        <div class="tl-body">logical/extra/physical/local 四级专家语义;dispatch 顺带累计 EPLB 统计(<code>cumulative_local_expert_recv_stats</code>),combine 顺带叠加 shared expert(<code>bias=</code>);独立通信流 + <code>limit_num_sms</code> 让通信与计算同卡并发;NVLink 域内升级 mega-MoE 单内核。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">EPLB</div>
        <div class="tl-body">每步零成本计数 → 窗口滚动 → 到期 scatter_add + all_reduce 汇聚全局视图 → 两段贪心(冗余副本分配 + 多步联合排布)→ batch_isend_irecv 分桶 P2P 或 symm_mem IPC 直读搬权重 → 三张映射表原子替换,gate 下个 forward 即生效;每层独立放置,rank_balance 指标闭环可观测。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">BUFFERS</div>
        <div class="tl-body">EPBuffer / BucketBuffer / EngramBuffer / SymmBuffer 四类缓冲进程级共享、只增不减;SM 预算在 DeepEP、DeepGEMM、NCCL 三方间显式划分;SymmBuffer 以「首个 spec 最大」的约定实现零拷贝视图复用。</div>
      </div>
    </div>

    <div class="grid c3">
      <div class="card reveal">
        <h3><span class="ico">🧩</span>设计取舍</h3>
        <p>TP 缺席是结构性选择:MLA 低秩 + 压缩 KV 让注意力权重小而密,复制比切分便宜;CP 只在 prefill 出现,恰好覆盖长序列的注意力二次增长,而 decode 由 KV cache 分页承担。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🔗</span>与跨卡通信的关系</h3>
        <p>本文的每个组都对应具体的通信原语:CP 组 → BucketBuffer all-gather;EP 组 → DeepEP dispatch/combine + EPLB all_reduce/P2P;world → gloo 控制面。原语级细节(TP/SP 缺席、NCCL 调用矩阵)见系列 <a href="/docs/inference-engines/deepinfer/10-cross-card-comm/" style="color:var(--accent2)">⑩ 跨卡通信行为全景</a>。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🧭</span>延伸阅读</h3>
        <p>异步调度如何与 DP 引擎配合见 <a href="/docs/inference-engines/deepinfer/05-async-scheduling/" style="color:var(--accent2)">⑤ 异步调度</a>;EPLB 与批次不变性的互斥(<code>allow_multiple_reduction</code>)见 <a href="/docs/inference-engines/deepinfer/06-batch-invariant/" style="color:var(--accent2)">⑥ 批次不变性</a>;YOCO 截断与 CP 边界重分布在 <a href="/docs/inference-engines/deepinfer/04-swa-replay/" style="color:var(--accent2)">④ SWA 有界重放</a>。</p>
      </div>
    </div>

    <div class="pgnav">
      <span>DeepInfer 代码分析系列 · 由 ZCode 生成于 2026-11</span>
      <span><a href="/docs/inference-engines/deepinfer/">← 返回系列总览</a></span>
    </div>
  </section>
<script>
// 滚动显现动画
const io=new IntersectionObserver(es=>{es.forEach(e=>{if(e.isIntersecting){e.target.classList.add('on');io.unobserve(e.target)}})},{threshold:.12});
document.querySelectorAll('.reveal').forEach(el=>io.observe(el));
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>DSpark 投机解码与置信度调度验证</title><link>https://hccl.club/docs/inference-engines/deepinfer/03-dspark/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/03-dspark/</guid><description><![CDATA[<div class="fwdoc">
<style>
.fwdoc{--bg:#0b1020; --bg2:#0f1729; --panel:#141d33; --panel2:#1a2440;
  --border:#263352; --text:#dbe4f5; --muted:#8ea0c2;
  --accent:#4f8cff; --accent2:#22d3ee; --good:#34d399; --warn:#fbbf24; --bad:#f87171; --purple:#a78bfa;
  --code-bg:#0d1424; --radius:14px;
  --serif:"Noto Serif SC","Songti SC",serif;}
.fwdoc *{box-sizing:border-box;margin:0;padding:0}
.fwdoc{background:linear-gradient(160deg,var(--bg) 0%,var(--bg2) 60%,#0a0f1e 100%);color:var(--text);
  font-family:"PingFang SC","Microsoft YaHei","Segoe UI",system-ui,sans-serif;line-height:1.75;}
.fwdoc{flex:1;min-width:0;padding:36px 48px 80px}
@media(max-width:960px){.fwdoc{padding:24px 18px 60px}}
.fwdoc .hero{position:relative;border-radius:var(--radius);overflow:hidden;padding:46px 44px;margin-bottom:34px;
  background:radial-gradient(1200px 400px at 15% -20%,rgba(79,140,255,.28),transparent 60%),
             radial-gradient(900px 380px at 95% 0%,rgba(167,139,250,.20),transparent 55%),
             linear-gradient(135deg,#16213e,#101a30);border:1px solid var(--border)}
.fwdoc .hero .crumb{font-size:12px;color:var(--accent2);letter-spacing:1px;margin-bottom:12px}
.fwdoc .hero h1{font-size:34px;color:#fff;font-weight:800;letter-spacing:.5px;margin-bottom:10px}
.fwdoc .hero p.desc{color:var(--muted);max-width:760px;font-size:15px}
.fwdoc .hero .tags{margin-top:18px;display:flex;gap:10px;flex-wrap:wrap}
.fwdoc .hero .tag{font-size:12px;padding:4px 14px;border-radius:999px;border:1px solid var(--border);
  background:rgba(79,140,255,.10);color:var(--accent2)}
.fwdoc .tag.good{border-color:rgba(52,211,153,.4);color:var(--good);background:rgba(52,211,153,.08)}
.fwdoc .tag.warn{border-color:rgba(251,191,36,.4);color:var(--warn);background:rgba(251,191,36,.08)}
.fwdoc section{margin-bottom:44px;scroll-margin-top:20px}
.fwdoc h2.sec{display:flex;align-items:center;gap:12px;font-size:23px;color:#fff;margin-bottom:6px;padding-bottom:10px;border-bottom:1px solid var(--border)}
.fwdoc h2.sec .num{display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:10px;flex-shrink:0;
  background:linear-gradient(135deg,var(--accent),var(--purple));color:#fff;font-size:15px;font-weight:800}
.fwdoc .lede{color:var(--muted);font-size:14px;margin-bottom:20px}
.fwdoc .grid{display:grid;gap:18px}
.fwdoc .grid.c2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}
.fwdoc .grid.c3{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}
.fwdoc .card{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:var(--radius);padding:22px 24px;transition:transform .3s,border-color .3s,box-shadow .3s}
.fwdoc .card:hover{transform:translateY(-3px);border-color:rgba(79,140,255,.55);box-shadow:0 12px 34px -14px rgba(79,140,255,.35)}
.fwdoc .card h3{font-size:16.5px;color:#fff;margin-bottom:8px;display:flex;align-items:center;gap:9px}
.fwdoc .card h3 .ico{width:26px;height:26px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;
  background:rgba(79,140,255,.16);font-size:14px;flex-shrink:0}
.fwdoc .card p{font-size:13.5px;color:var(--muted)}
.fwdoc .card p code,.fwdoc .inline-code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1.5px 7px;border-radius:6px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px}
.fwdoc ul.feat{list-style:none}
.fwdoc ul.feat li{padding:9px 0 9px 30px;position:relative;font-size:14px;color:var(--text);border-bottom:1px dashed rgba(38,51,82,.6)}
.fwdoc ul.feat li:last-child{border-bottom:none}
.fwdoc ul.feat li::before{content:"▸";position:absolute;left:8px;color:var(--accent);font-weight:700;animation:fw-blink 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
@keyframes fw-blink{0%,100%{opacity:.35}50%{opacity:1}}
.fwdoc pre.code{background:var(--code-bg);border:1px solid var(--border);border-radius:12px;padding:18px 20px;
  overflow-x:auto;font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px;line-height:1.65;margin:14px 0;position:relative}
.fwdoc pre.code::before{content:"● ● ●";display:block;color:#3a4a70;font-size:10px;letter-spacing:3px;margin-bottom:10px}
.fwdoc pre.code .k{color:#c792ea}
.fwdoc pre.code .s{color:#89ddff}
.fwdoc pre.code .c{color:#5d7294;font-style:italic}
.fwdoc pre.code .f{color:#82aaff}
.fwdoc pre.code .n{color:#f78c6c}
.fwdoc pre.code .h{color:#ffcb6b}
.fwdoc .filepath{font-family:"JetBrains Mono",Consolas,monospace;font-size:11.5px;color:var(--accent2);
  background:rgba(34,211,238,.08);border:1px solid rgba(34,211,238,.25);border-radius:6px;padding:2px 10px;display:inline-block;margin-bottom:4px}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border)}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px}
.fwdoc table.tbl td{padding:10px 14px;border-top:1px solid var(--border);color:var(--text);vertical-align:top}
.fwdoc table.tbl tr{transition:background .2s}
.fwdoc table.tbl tr:nth-child(even) td{background:rgba(20,29,51,.5)}
.fwdoc table.tbl tr:hover td{background:rgba(79,140,255,.10)}
.fwdoc table.tbl td code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;font-family:Consolas,monospace;font-size:12px}
.fwdoc .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px}
.fwdoc .badge.merged{background:rgba(52,211,153,.15);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.open{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.closed{background:rgba(248,113,113,.13);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.nccl{background:rgba(251,191,36,.12);color:var(--warn);border:1px solid rgba(251,191,36,.4)}
.fwdoc .badge.hccl{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .badge.deepep{background:rgba(34,211,238,.12);color:var(--accent2);border:1px solid rgba(34,211,238,.4)}
.fwdoc .reveal{opacity:0;transform:translateY(26px);transition:opacity .7s cubic-bezier(.2,.7,.3,1),transform .7s cubic-bezier(.2,.7,.3,1)}
.fwdoc .reveal.on{opacity:1;transform:none}
.fwdoc .reveal.d1{transition-delay:.12s}
.fwdoc .reveal.d2{transition-delay:.24s}
.fwdoc .reveal.d3{transition-delay:.36s}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:20px;margin:18px 0;position:relative;overflow:hidden}
.fwdoc .figure .cap{text-align:center;font-size:12.5px;color:var(--muted);margin-top:10px}
.fwdoc .figure svg{width:100%;height:auto;display:block}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-flow 1.2s linear infinite}
@keyframes fw-flow{to{stroke-dashoffset:-14}}
.fwdoc .pulse{animation:fw-pulse 2s ease-in-out infinite;transform-origin:center}
@keyframes fw-pulse{0%,100%{opacity:.45;transform:scale(1)}50%{opacity:1;transform:scale(1.06)}}
.fwdoc .node-gpu{fill:#16233f;stroke:#4f8cff;stroke-width:1.6;rx:10}
.fwdoc .node-gpu-title{fill:#dbe4f5;font-size:13px;font-weight:700}
.fwdoc .token-dot{fill:#22d3ee}
.fwdoc .barrow{filter:drop-shadow(0 0 6px rgba(34,211,238,.7))}
.fwdoc .timeline{position:relative;padding-left:34px}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .tl-item{position:relative;margin-bottom:20px}
.fwdoc .tl-item::before{content:"";position:absolute;left:-30px;top:7px;width:12px;height:12px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.18);animation:fw-pulse 2.4s infinite}
.fwdoc .tl-item .tl-date{font-size:11.5px;color:var(--accent2);letter-spacing:.5px}
.fwdoc .tl-item .tl-body{font-size:13.5px;color:var(--text);margin-top:3px}
.fwdoc .note{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13px;color:var(--text);margin:16px 0}
.fwdoc .note.warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .note.good{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .note b{color:#fff}
.fwdoc .pgnav{margin-top:60px;padding-top:20px;border-top:1px solid var(--border);color:#5a6b92;font-size:12px;
  display:flex;justify-content:space-between;flex-wrap:wrap;gap:10px}
.fwdoc .pgnav a{color:var(--accent2);text-decoration:none}
/* ===== 导入面板附加样式 ===== */
.fwdoc{border-radius:14px;margin:18px 0}
.fwdoc table.tbl{display:block;overflow-x:auto;max-width:100%}
@media (prefers-reduced-motion:reduce){
.fwdoc *,.fwdoc *::before,.fwdoc *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
.fwdoc .reveal{opacity:1!important;transform:none!important}
}

</style>

<!-- ================= 1. 概述 ================= -->
  <section id="s1">
    <h2 class="sec"><span class="num">1</span>概述:DSpark 是什么、解决什么问题</h2>
    <p class="lede">大模型 decode 是典型的 memory-bound 阶段:每步只为每个请求产出 1 个 token,权重与 KV cache 的读取成本无法被摊薄。DSpark 用「起草-验证」两阶段把单步产出提升到 1~nextn+1 个 token。</p>

    <div class="grid c3">
      <div class="card reveal">
        <h3><span class="ico">🧩</span>DFlash 投机头</h3>
        <p>权重来自 HF checkpoint 中主模型之后的 <code>DFlashNextPredictHeadHC</code> 模块,与主模型共享 <code>embed_tokens</code> 与 <code>lm_head</code>,从主模型若干目标层(<code>dspark_target_layer_ids</code>)的特征投影出 draft 输入,一次性并行起草 <code>nextn</code> 个 token。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">✅</span>并行验证(分布无损)</h3>
        <p>主模型一次 varlen forward 同时算出所有验证行的 logits,按 speculative decoding 的拒绝采样规则接受 draft 前缀、在首个拒绝位置用残差概率重采样。任意请求接受任意条数,输出分布与逐 token 解码完全一致。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🎯</span>置信度调度验证</h3>
        <p><code>ConfidenceHead</code> 为每个 draft token 预测接受概率;调度器 <code>MTPVarlen</code> 用累计置信度 + 实测 decode 性能曲线,决定本步 <code>total_q</code> 预算以及每个请求验证几个 draft——「该多的多验,该少的少验」。</p>
      </div>
    </div>

    <div class="note good reveal">
      <b>README 原文</b>(README.md:24):「<b>DSpark and confidence-scheduled verification:</b> accelerate decoding with draft tokens and use confidence estimates to schedule verification. Set <code>DEEPINFER_ENABLE_MTP_VARLEN=1</code>; <code>DEEPINFER_USE_NEXTN_DECODE</code> controls the maximum draft length (default: 5).」
    </div>

    <h3 style="color:#fff;margin:18px 0 8px;font-size:16px">一次 decode step 中五个组件的分工</h3>
    <table class="tbl reveal">
      <tr><th>组件</th><th>位置</th><th>职责</th></tr>
      <tr><td><code>DFlash</code> 投机模型</td><td><code>deepinfer/model_executor/models/mtp/dflash.py:82</code></td><td>加载 draft 层权重;主模型 forward 内更新 main-token KV(<code>update_main_cache</code>);采样阶段执行 draft forward 并采样出 <code>nextn</code> 个候选</td></tr>
      <tr><td><code>MTPInfoPool</code></td><td><code>deepinfer/model_executor/layers/mtp_info_pool.py:14</code></td><td>GPU 上按调度器 slot 稳定存放 draft 的 token_ids / logprobs / confidence,跨 step 供验证读取</td></tr>
      <tr><td><code>Sampler._verification</code></td><td><code>deepinfer/model_executor/layers/sampler.py:410</code></td><td>构建 packed 验证布局、执行拒绝采样、计算接受前缀与 <code>last_valid_offset</code>(回退位置)</td></tr>
      <tr><td><code>MTPVarlen</code> 调度器</td><td><code>csrc/engine/mtp_varlen.hpp:133</code></td><td>用置信度与 decode 性能曲线搜索最优 <code>total_q</code>,并按置信度排序为每个请求分配 <code>seqlen_q</code></td></tr>
      <tr><td><code>DFlashCudaGraphRunner</code></td><td><code>deepinfer/worker/dflash_cuda_graph_runner.py:31</code></td><td>把整段 draft 执行(广播→metadata→draft 层→采样与 pool 写入)捕获为 CUDA graph,单次 replay 完成</td></tr>
    </table>

    <div class="note reveal">
      <b>与系列其他篇的关系</b>:varlen 验证 batch 会改变每步的实际 batch 组成,因此 <b>DSpark 的置信度调度与「批次不变性/确定性采样」互斥</b>(详见第 9 节);ZOS 异步调度下的 seqlens_q GPU 修正路径与第 ⑤ 篇联动;SWA 有界重放必须为 MTP 回退保留余量(第 7 节)。
    </div>
  </section>

  <!-- ================= 2. 开关与全局链路 ================= -->
  <section id="s2">
    <h2 class="sec"><span class="num">2</span>启用方式与全局执行链路</h2>
    <p class="lede">两个环境变量决定投机解码的「开关」与「最大深度」;其余变量控制置信度温度、回退余量与 DFlash CUDA graph 粒度(完整表格见第 8 节)。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🔌</span>总开关</h3>
        <p><code>DEEPINFER_USE_NEXTN_DECODE</code>(默认 5,设 0 关闭投机解码,environ.py:136-137)决定每个请求每步最多起草/验证多少个 draft;<code>DEEPINFER_ENABLE_MTP_VARLEN</code>(environ.py:138)决定是否启用「按置信度动态变长」的调度与配套 GPU 修正路径。varlen 关闭时调度退化为「验证全部 draft」(mtp_varlen.hpp:153-158 空曲线分支)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧮</span>一个 decode step 的完整顺序</h3>
        <p><code>Worker.execute_model_step</code>(worker.py:89)按固定顺序执行:① 前向主模型(验证行 forward);② post-process 上一步;③ 采样:验证 + DFlash 起草;④ ZOS 时把本步 post-process 延迟到下一步与 forward 重叠(worker.py:182-187)。</p>
      </div>
    </div>

    <div class="timeline reveal">
      <div class="tl-item"><div class="tl-date">STEP 1 · 调度(C++)</div><div class="tl-body"><code>Scheduler::_schedule</code> 取出 running 序列,调用 <code>_mtp_varlen.schedule(scheduled, seqlens_q)</code>(scheduler.hpp:651-652)得到每请求验证行数;<code>seqlen_q = 1(采样行) + 验证的 draft 数</code>,并满足 <code>seqlen_q &lt;= nextn + 1</code>(prepare_sample.cpp:212)。</div></div>
      <div class="tl-item"><div class="tl-date">STEP 2 · 主模型 forward(varlen)</div><div class="tl-body">所有请求的验证行拼接成一个 varlen batch 一次前向;同时主模型在目标层把特征写入 <code>dflash_input</code>,循环结束后调用 <code>dflash.update_main_cache(...)</code>(deepseek.py:223)把 main-token KV 写入 DFlash 各层的 cache。</div></div>
      <div class="tl-item"><div class="tl-date">STEP 3 · 采样与验证</div><div class="tl-body"><code>Sampler.forward</code> 走 decode 分支:<code>_verification</code>(sampler.py:225)对 packed 行做拒绝采样,产出接受前缀、<code>last_valid_offset</code> 与新采样出的 golden token;随后 <code>mtp_module.decode_forward</code>(sampler.py:237)驱动 DFlash 起草下一轮 draft 并写入 <code>MTPInfoPool</code>。</div></div>
      <div class="tl-item"><div class="tl-date">STEP 4 · post-process(C++)</div><div class="tl-body">引擎侧 <code>process_MTPInfo</code>(llm_engine.py:717-724)消费 draft token 与 confidence(累乘成 accept_rates,scheduler.hpp:1242-1251);<code>scheduler.process_outputs</code> 乐观推进 KV 后按实际接受数回填(scheduler.hpp:927, 997-1000);实测 forward/sampler 耗时回传 <code>update_mtp_runtime</code>(llm_engine.py:997-1002)更新调度器的性能模型。</div></div>
    </div>
  </section>

  <!-- ================= 3. DFlash 模型结构 ================= -->
  <section id="s3">
    <h2 class="sec"><span class="num">3</span>DFlash / NextN draft 模型结构</h2>
    <p class="lede">DFlash 不是独立小网络,而是「主模型特征的投影 + 若干与主模型同构的 draft decoder 层 + 共享头」。<span class="filepath">deepinfer/model_executor/models/mtp/dflash.py</span></p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📦</span>权重切分:主模型之后的全是 draft</h3>
        <p>加载时按 <code>num_non_mtp_layers = num_hidden_layers + 2</code>(主模型层数 + embedding 层 + lm_head 层)切分 HF 模块(dflash.py:92-95),剩余模块必须全部是 <code>DFlashNextPredictHeadHC</code>(dflash.py:96-97),且层数必须等于配置的 <code>num_nextn_predict_layers</code>(dflash.py:109-110)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🔗</span>共享与克隆</h3>
        <p>draft 层与主模型<b>共享</b> <code>embed_tokens</code> 和 <code>lm_head</code>(dflash.py:138, 100);由于 main/draft 投影需要不同连续布局,各层 KV 权重会克隆后 <code>merge_linear_weights</code> 合并为一个 <code>main_kv_proj</code>(dflash.py:117-123,显存略增)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🧲</span>输入投影:来自主模型目标层</h3>
        <p><code>dspark_target_layer_ids</code> 指定的主模型层在 attention-norm 之后把 residual 写入 <code>dflash_input</code>(decoder_layer.py:144-145,经 <code>dflash_input_store</code> 融合 kernel 做 hc 维均值归约,tilelang_ops/dflash.py:130-155);DFlash 端用 <code>projection(hidden*num_layers → hidden)</code> + <code>projection_norm</code> 还原成 draft 输入(dflash.py:146-153)。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">🎲</span>noise token 初始化</h3>
        <p>draft forward 的输入是 <code>[req_cnt, dflash_block_size]</code> 的 token 矩阵:第 0 列是本步 golden token,其余列全部填 <code>dspark_noise_token_id</code>(dflash.py:230-239)——即除锚点外的 draft 槽位由可学习的噪声 token 承担。</p>
      </div>
    </div>

    <h3 style="color:#fff;margin:20px 0 8px;font-size:16px">main-cache 路径:随主模型 CUDA graph 一起执行</h3>
    <p style="font-size:14px;color:var(--muted);margin-bottom:10px">每步主模型 forward 结束时,把投影后的 hidden 经 <code>main_kv_proj</code> 生成各 draft 层的 main-token key,写入 DFlash 专属 KV cache。decode 时该路径随主模型 CUDA graph 一起捕获/重放(dflash.py:204-209 的注释明确说明:接受结果尚未产生,被拒绝的 draft 位置随后会被 draft key 覆盖,因此无需按接受结果屏蔽)。</p>
    <pre class="code"><span class="filepath">deepinfer/model_executor/models/mtp/dflash.py:219-228(节选)</span>
main_hiddens = self.projection_norm(self.projection(dflash_input))
main_k = self.main_kv_proj(main_hiddens).unflatten(-1, (self.MTP_num_layers, self.qk_head_dim))
for i, layer in enumerate(self.layers):
    layer.update_main_cache(main_k=main_k[:, i], kv_cache=nextn_kv_caches[layer.layer_idx],
                            main_positions=main_positions,
                            slot_mapping_store_swa=input_metadata.slot_mapping_store_swa, ...)</pre>

    <h3 style="color:#fff;margin:20px 0 8px;font-size:16px">draft 层:固定步长(fixed-stride)forward</h3>
    <ul class="feat reveal">
      <li><code>DFlashDecoderLayer</code>(decoder_layer.py:178)与主模型层同构:attn-norm → <code>DFlashAttention.forward_drafts</code> → ffn-norm → MoE MLP;「DFlash MoE 可能跟 main model 不同构」(decoder_layer.py:199)。</li>
      <li><code>DFlashAttention</code>(attn.py:883)语义:「prefill 更新 main-token KV;decode 写独立的 draft KV 并计算 draft query」;draft key <b>只存活一个 decode step</b>,下一步直接覆盖(attn.py:975 注释)。</li>
      <li>draft 的 query/key 走 <code>q_a_kv_proj</code>(合并 LoRA A 权重)+ <code>q_b_proj</code>(attn.py:902-911),KV 经 fused norm+RoPE+e4m3 cast 写入 <code>dflash_newx_slot_mapping_store</code> 指定的 SWA cache 槽位(attn.py:976-991)。</li>
      <li>注意力通过 <code>decode_mla_mqa_sparse</code> 以 <code>dflash_kv_index</code> 读取滑窗内 KV(attn.py:994-1010),且把 <code>DEEPINFER_BATCH_INVARIANT</code> 一并传入内核(attn.py:1002)。</li>
    </ul>

    <h3 style="color:#fff;margin:20px 0 8px;font-size:16px">fixed-stride metadata:build_dflash_input</h3>
    <p style="font-size:14px;color:var(--muted);margin-bottom:10px">draft attention 不复用主模型的 varlen 布局,而是由 <code>InputMetadataV4.build_dflash_input</code>(input_metadata/dflash.py:36-84)构造「每请求恰好 <code>dflash_block_size</code> 行」的等宽布局,使 DFlash CUDA graph 可以按请求数捕获。两个字段:</p>
    <table class="tbl reveal">
      <tr><th>字段</th><th>形状 / 语义</th><th>出处</th></tr>
      <tr><td><code>dflash_newx_slot_mapping_store</code></td><td><code>[real_cnt * dflash_block_size]</code>,draft token KV 的 SWA cache 写入槽位</td><td>input_metadata/dflash.py:30-31</td></tr>
      <tr><td><code>dflash_kv_index</code></td><td><code>[real_cnt * dflash_block_size, pad64(window_size + dflash_block_size)]</code>,每个 draft token 可见的 key 槽位,-1 = 无效</td><td>input_metadata/dflash.py:32-34</td></tr>
    </table>
    <p style="font-size:14px;color:var(--muted)">底层由 <code>get_fused_dflash_get_input</code> 单个 TileLang kernel 完成:<code>accepted_pos = positions[ftp] + last_valid_offset</code>(本步实际推进到的位置),draft positions 为 <code>accepted_pos + 1 + [0..block)</code>,KV 索引覆盖 <code>[accepted_pos - (window_size-1), accepted_pos + block)</code> 并 pad 到 64 对齐(get_kv_index.py:164-195 参考实现)。<code>first_token_positions = -1</code> 标记 CUDA graph 的 padding 请求,其行全部填屏蔽值(input_metadata/dflash.py:44-46)。</p>

    <h3 style="color:#fff;margin:20px 0 8px;font-size:16px">Markov 头与 draft 采样循环</h3>
    <p style="font-size:14px;color:var(--muted);margin-bottom:10px">若配置 <code>dspark_markov_rank &gt; 0</code>(dflash.py:155-156),DFlash 额外持有 <code>markov_w1</code>(词表嵌入,rank 维)与 <code>markov_w2</code>(rank → 词表,fp32 输出)(dflash.py:165-177):采样时把上一个 draft token 的 markov 分量累加进 logits,为 draft 链引入一阶马尔可夫依赖(dflash.py:310-314)。<code>sample_drafts</code> 对 <code>max_MTP_value</code> 个 step 逐个采样:</p>
    <pre class="code"><span class="filepath">deepinfer/model_executor/models/mtp/dflash.py:308-334(节选)</span>
for step_i in range(self.max_MTP_value):
    logits = logits_next[step_i :: self.max_MTP_value]          <span class="c"># 等宽布局下按步取行</span>
    if self.enable_markov:
        w1 = self.markov_w1(draft_token_ids)
        logits = self.markov_w2(w1, out_acc=logits)
    if confidence_rates is not None:
        self.confidence_head(hidden_states_before_norm[step_i :: self.max_MTP_value], w1,
                             out=confidence_rates[:, step_i], step_i=step_i)   <span class="c"># 逐步置信度</span>
    _, token_index_next, draft_token_ids, _, _, _ = process_sampling(
        logits, SamplingKernelInputs(..., sample_positions_table[step_i]),
        self.force_topk, logprobs_out=next_n_token_logprobs[:, step_i], tag=<span class="s">"mtp"</span>)  <span class="c"># 独立 RNG 命名空间</span></pre>
    <div class="note reveal">draft 采样位置由 <code>sample_positions_table = arange(1, nextn+1) + sample_positions + last_valid_offset</code>(dflash.py:290-294)给出——每个 draft step 的采样位置天然不同;<code>tag="mtp"</code> 使 draft 与主模型采样使用不同随机流(<code>_MTP_SEED_OFFSET = 1000000007</code>,fused_sample.py:15,93)。采样结果连同 logprobs、confidence 一起由 <code>store_mtp_info</code> 写入 <code>MTPInfoPool</code>(dflash.py:336-345)。</div>
  </section>

  <!-- ================= 4. 全流程动画 ================= -->
  <section id="s4">
    <h2 class="sec"><span class="num">4</span>投机解码全流程:起草 → 并行验证 → 接受/回退</h2>
    <p class="lede">下面这个循环动画覆盖一个完整 decode step:上一轮 draft 从 MTPInfoPool 流入主模型验证 → 接受前缀(绿)进入输出序列、首个拒绝位置重采样出 golden token(黄)→ golden token 驱动 DFlash 起草新一轮 draft(青)→ 写回 pool,循环往复。</p>

    <div class="figure reveal">
      <svg viewBox="0 0 960 600" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="投机解码全流程循环动画">
        <defs>
          <marker id="arrA" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#4f8cff"/>
          </marker>
          <linearGradient id="gbox" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stop-color="#16233f"/><stop offset="1" stop-color="#101a30"/>
          </linearGradient>
        </defs>

        <text x="480" y="28" text-anchor="middle" fill="#dbe4f5" font-size="15" font-weight="700">DSpark 投机解码循环(一个 decode step)</text>

        <!-- 连接路径(可见虚线) -->
        <path class="flowline" d="M250,300 C300,300 280,150 330,140" stroke="#4f8cff" stroke-width="2" fill="none" marker-end="url(#arrA)"/>
        <path class="flowline" d="M640,120 C670,110 690,95 715,90" stroke="#34d399" stroke-width="2" fill="none" marker-end="url(#arrA)"/>
        <path class="flowline" d="M480,215 C480,280 480,320 480,375" stroke="#fbbf24" stroke-width="2" fill="none" marker-end="url(#arrA)"/>
        <path class="flowline" d="M325,450 C240,480 110,430 138,325" stroke="#22d3ee" stroke-width="2" fill="none" marker-end="url(#arrA)"/>

        <!-- 池子:上一轮 draft -->
        <rect x="40" y="200" width="210" height="120" rx="10" fill="url(#gbox)" stroke="#4f8cff" stroke-width="1.6"/>
        <text x="145" y="226" text-anchor="middle" fill="#dbe4f5" font-size="13" font-weight="700">MTPInfoPool(GPU)</text>
        <text x="145" y="244" text-anchor="middle" fill="#8ea0c2" font-size="10.5">上一轮 draft:token / logprobs / confidence</text>
        <text x="145" y="262" text-anchor="middle" fill="#8ea0c2" font-size="10.5">pool_rows = (max_num_seqs+1) * nextn</text>
        <text x="145" y="288" text-anchor="middle" fill="#5a6b92" font-size="10">mtp_info_pool.py:33</text>
        <!-- pool 中的静态 draft -->
        <g font-size="10" font-weight="700">
          <rect x="66" y="298" width="22" height="18" rx="4" fill="#22d3ee" opacity=".85"/><text x="77" y="311" text-anchor="middle" fill="#0b1020">d1</text>
          <rect x="92" y="298" width="22" height="18" rx="4" fill="#22d3ee" opacity=".7"/><text x="103" y="311" text-anchor="middle" fill="#0b1020">d2</text>
          <rect x="118" y="298" width="22" height="18" rx="4" fill="#22d3ee" opacity=".55"/><text x="129" y="311" text-anchor="middle" fill="#0b1020">d3</text>
          <rect x="144" y="298" width="22" height="18" rx="4" fill="#22d3ee" opacity=".4"/><text x="155" y="311" text-anchor="middle" fill="#0b1020">d4</text>
          <rect x="170" y="298" width="22" height="18" rx="4" fill="#22d3ee" opacity=".3"/><text x="181" y="311" text-anchor="middle" fill="#0b1020">d5</text>
        </g>

        <!-- 验证框 -->
        <rect x="330" y="60" width="310" height="155" rx="10" fill="url(#gbox)" stroke="#4f8cff" stroke-width="1.8"/>
        <text x="485" y="86" text-anchor="middle" fill="#dbe4f5" font-size="13" font-weight="700">主模型 varlen forward · 并行验证</text>
        <text x="485" y="104" text-anchor="middle" fill="#8ea0c2" font-size="10.5">seqlen_q = 1 + 本请求验证的 draft 数 · 拒绝采样(分布无损)</text>
        <!-- 验证行示意 -->
        <g font-size="10">
          <rect x="352" y="118" width="26" height="20" rx="4" fill="#34d399"/><text x="365" y="132" text-anchor="middle" fill="#06281c">d1✓</text>
          <rect x="382" y="118" width="26" height="20" rx="4" fill="#34d399"/><text x="395" y="132" text-anchor="middle" fill="#06281c">d2✓</text>
          <rect x="412" y="118" width="26" height="20" rx="4" fill="#34d399"/><text x="425" y="132" text-anchor="middle" fill="#06281c">d3✓</text>
          <rect x="442" y="118" width="26" height="20" rx="4" fill="#f87171"/><text x="455" y="132" text-anchor="middle" fill="#2b0b0b">d4✗</text>
          <rect x="472" y="118" width="26" height="20" rx="4" fill="#fbbf24"/><text x="485" y="132" text-anchor="middle" fill="#33230a">r ↻</text>
          <text x="512" y="132" fill="#8ea0c2" font-size="10">← 拒绝位残差重采样</text>
          <text x="352" y="158" fill="#8ea0c2">is_verify: 前 seqlen_q-1 行为验证行,最后一行 fresh(sampler.py:43-46)</text>
          <text x="352" y="176" fill="#8ea0c2">last_valid_offset = 首个被拒行的请求内偏移(sampler.py:458-459)</text>
          <text x="352" y="196" fill="#5a6b92">fused_sample 残差: r = max(q − α·p, 0), α = exp(−5e-5)</text>
        </g>

        <!-- 输出序列 -->
        <rect x="715" y="45" width="205" height="100" rx="10" fill="url(#gbox)" stroke="#34d399" stroke-width="1.6"/>
        <text x="817" y="71" text-anchor="middle" fill="#dbe4f5" font-size="13" font-weight="700">输出序列(已提交)</text>
        <text x="817" y="89" text-anchor="middle" fill="#8ea0c2" font-size="10.5">接受前缀 + 重采样 token 一起 append</text>
        <text x="817" y="107" text-anchor="middle" fill="#8ea0c2" font-size="10.5">commit_processed_tokens 回填 KV(scheduler.hpp:997)</text>
        <g font-size="10" font-weight="700">
          <rect x="745" y="118" width="20" height="16" rx="4" fill="#34d399" opacity=".9"/><text x="755" y="130" text-anchor="middle" fill="#06281c">t</text>
          <rect x="769" y="118" width="20" height="16" rx="4" fill="#34d399" opacity=".75"/><text x="779" y="130" text-anchor="middle" fill="#06281c">t</text>
          <rect x="793" y="118" width="20" height="16" rx="4" fill="#34d399" opacity=".6"/><text x="803" y="130" text-anchor="middle" fill="#06281c">t</text>
          <rect x="817" y="118" width="20" height="16" rx="4" fill="#fbbf24" opacity=".9"/><text x="827" y="130" text-anchor="middle" fill="#33230a">r</text>
        </g>

        <!-- 拒绝掉落 -->
        <rect x="536" y="118" width="24" height="20" rx="4" fill="#f87171" opacity=".85">
          <animate attributeName="opacity" values="0;.85;.85;0" keyTimes="0;.1;.55;1" dur="7s" repeatCount="indefinite"/>
        </rect>
        <text x="548" y="132" text-anchor="middle" fill="#2b0b0b" font-size="10" font-weight="700">d4✗</text>

        <!-- DFlash 框 -->
        <rect x="330" y="375" width="310" height="135" rx="10" fill="url(#gbox)" stroke="#a78bfa" stroke-width="1.8"/>
        <text x="485" y="401" text-anchor="middle" fill="#dbe4f5" font-size="13" font-weight="700">DFlash 投机头 · 起草 nextn 个 draft</text>
        <text x="485" y="419" text-anchor="middle" fill="#8ea0c2" font-size="10.5">输入 = golden token + (block−1) 个 noise token(dflash.py:230-239)</text>
        <text x="485" y="437" text-anchor="middle" fill="#8ea0c2" font-size="10.5">draft 层×N + Markov 头 + ConfidenceHead + 共享 lm_head 采样</text>
        <text x="485" y="455" text-anchor="middle" fill="#8ea0c2" font-size="10.5">整段可作为一张 DFlash CUDA graph 重放(dflash.py:353-357)</text>
        <g font-size="10" font-weight="700">
          <rect x="378" y="470" width="22" height="18" rx="4" fill="#22d3ee" opacity=".9"/><text x="389" y="483" text-anchor="middle" fill="#0b1020">n1</text>
          <rect x="404" y="470" width="22" height="18" rx="4" fill="#22d3ee" opacity=".75"/><text x="415" y="483" text-anchor="middle" fill="#0b1020">n2</text>
          <rect x="430" y="470" width="22" height="18" rx="4" fill="#22d3ee" opacity=".6"/><text x="441" y="483" text-anchor="middle" fill="#0b1020">n3</text>
          <rect x="456" y="470" width="22" height="18" rx="4" fill="#22d3ee" opacity=".45"/><text x="467" y="483" text-anchor="middle" fill="#0b1020">n4</text>
          <rect x="482" y="470" width="22" height="18" rx="4" fill="#22d3ee" opacity=".35"/><text x="493" y="483" text-anchor="middle" fill="#0b1020">n5</text>
          <text x="522" y="483" fill="#8ea0c2" font-size="10">→ store_mtp_info 写回 pool</text>
        </g>

        <!-- 流动的 draft tokens: pool → 验证 -->
        <g>
          <g><rect width="20" height="16" rx="4" fill="#22d3ee"/><animateMotion dur="7s" begin="0s" repeatCount="indefinite" path="M240,270 C290,260 280,150 332,140"/></g>
          <g><rect width="20" height="16" rx="4" fill="#22d3ee"/><animateMotion dur="7s" begin="0.5s" repeatCount="indefinite" path="M240,270 C290,260 280,150 332,140"/></g>
          <g><rect width="20" height="16" rx="4" fill="#22d3ee"/><animateMotion dur="7s" begin="1s" repeatCount="indefinite" path="M240,270 C290,260 280,150 332,140"/></g>
          <g><rect width="20" height="16" rx="4" fill="#22d3ee"/><animateMotion dur="7s" begin="1.5s" repeatCount="indefinite" path="M240,270 C290,260 280,150 332,140"/></g>
          <g><rect width="20" height="16" rx="4" fill="#22d3ee"/><animateMotion dur="7s" begin="2s" repeatCount="indefinite" path="M240,270 C290,260 280,150 332,140"/></g>
        </g>
        <!-- 流动的接受 tokens: 验证 → 输出 -->
        <g>
          <g><rect width="18" height="15" rx="4" fill="#34d399"/><animateMotion dur="7s" begin="2.6s" repeatCount="indefinite" path="M632,120 C668,112 690,96 718,88"/></g>
          <g><rect width="18" height="15" rx="4" fill="#34d399"/><animateMotion dur="7s" begin="3.1s" repeatCount="indefinite" path="M632,120 C668,112 690,96 718,88"/></g>
          <g><rect width="18" height="15" rx="4" fill="#34d399"/><animateMotion dur="7s" begin="3.6s" repeatCount="indefinite" path="M632,120 C668,112 690,96 718,88"/></g>
          <g><rect width="18" height="15" rx="4" fill="#fbbf24"/><animateMotion dur="7s" begin="4.1s" repeatCount="indefinite" path="M632,120 C668,112 690,96 718,88"/></g>
        </g>
        <!-- golden token: 验证 → DFlash -->
        <g>
          <g><rect width="22" height="18" rx="4" fill="#fbbf24"/><text x="11" y="13" text-anchor="middle" font-size="10" font-weight="700" fill="#33230a">G</text>
            <animateMotion dur="7s" begin="4.3s" repeatCount="indefinite" path="M480,220 C480,280 480,330 480,372"/></g>
        </g>
        <!-- 新 draft: DFlash → pool(闭环) -->
        <g>
          <g><rect width="20" height="16" rx="4" fill="#22d3ee"/><animateMotion dur="7s" begin="5.4s" repeatCount="indefinite" path="M330,455 C240,485 115,435 142,328"/></g>
          <g><rect width="20" height="16" rx="4" fill="#22d3ee"/><animateMotion dur="7s" begin="5.9s" repeatCount="indefinite" path="M330,455 C240,485 115,435 142,328"/></g>
          <g><rect width="20" height="16" rx="4" fill="#22d3ee"/><animateMotion dur="7s" begin="6.4s" repeatCount="indefinite" path="M330,455 C240,485 115,435 142,328"/></g>
        </g>

        <!-- 步骤编号 -->
        <g font-size="11" font-weight="700" fill="#22d3ee">
          <circle cx="285" cy="215" r="12" fill="#16233f" stroke="#22d3ee"/><text x="285" y="219" text-anchor="middle">①</text>
          <circle cx="700" cy="72" r="12" fill="#16233f" stroke="#34d399"/><text x="700" y="76" text-anchor="middle" fill="#34d399">②</text>
          <circle cx="527" cy="300" r="12" fill="#16233f" stroke="#fbbf24"/><text x="527" y="304" text-anchor="middle" fill="#fbbf24">③</text>
          <circle cx="205" cy="470" r="12" fill="#16233f" stroke="#22d3ee"/><text x="205" y="474" text-anchor="middle">④</text>
        </g>

        <text x="480" y="560" text-anchor="middle" fill="#8ea0c2" font-size="11">① 上一轮 draft 从 pool 读出参与验证 ② 接受前缀流入输出 ③ golden token 驱动 DFlash ④ 新 draft 写回 pool,进入下一轮</text>
        <text x="480" y="580" text-anchor="middle" fill="#5a6b92" font-size="10.5">绿=接受 青=draft 黄=golden/重采样 红=拒绝(回退至该位置)</text>
      </svg>
      <div class="cap">图 1 · 投机解码「起草-验证-接受/回退」循环(token 方块沿路径流动,animateMotion 驱动)</div>
    </div>

    <div class="note warn reveal">
      <b>回退(backtracking)在哪发生?</b>验证产出的 <code>last_valid_offset</code>(首个被拒行的请求内偏移,全接受时为 fresh 行位置,sampler.py:458-459)即回退点。C++ 调度器先按 <code>seqlens_q</code> 「乐观推进」 KV 计数(scheduler.hpp:927 <code>advance_optimistically</code>),再按实际接受数回填(scheduler.hpp:997-1000 <code>commit_processed_tokens</code>)——<b>未被接受的 draft 不占 KV</b>。KV/压缩环的物理布局需为此预留 <code>DEEPINFER_MAX_BACKTRACKING_TOKENS</code>(≥ nextn+1,environ.py:139)的回退余量,详见第 7 节。
    </div>
  </section>

  <!-- ================= 5. 验证内核 ================= -->
  <section id="s5">
    <h2 class="sec"><span class="num">5</span>并行验证内核:拒绝采样、前缀接受与统计</h2>
    <p class="lede">验证完全发生在 GPU 上的一串 TileLang fused kernel 中, packed 布局把「不同请求、不同数量的验证行」拼成一个稠密 batch。<span class="filepath">deepinfer/model_executor/layers/tilelang_ops/sampler.py</span></p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📐</span>① prepare_verification_metadata</h3>
        <p>由 <code>mtp_first_token_positions</code>(ftp)与 <code>mtp_seqlens_q</code> 生成三个逐行张量:<code>row_to_req</code>(行→请求)、<code>local_step</code>(请求内偏移)、<code>is_verify</code>(验证行;每个请求<b>最后一行恒为 fresh 采样行</b>)(sampler.py:28-53)。C++ 侧 <code>prepare_sampler_inputs</code> 同步产出 pool 读行:<code>read_row = read_slot * nextn + j</code>,fresh 行固定读 padding slot 0(prepare_sample.cpp:220-225)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🎲</span>② fused_sample 拒绝采样</h3>
        <p>对验证行比较 draft 与 target 分布:残差 <code>r[i] = max(q[i] − α·p[i], 0)</code>,<code>α = exp(−DRAFT_PROB_PENALTY)</code>,<code>DRAFT_PROB_PENALTY = 5e-5</code>(common.py:3-19, 52-53,注释「防止 reject sampling 采不出东西」);同时估计 <code>accept_probs = max(1 − Σ residual, 0)</code>(fused_sample.py:63)。<code>force_topk</code> 开启时先用 <code>remap_draft_topk</code> 把 draft 的 top-k 空间对齐到当前 target top-k 空间(sampler_utils.py:171-180)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">⛓️</span>③ get_accept_result 前缀接受</h3>
        <p>接受必须保持前缀性:某行被拒后,该请求后续验证行即使随机通过也不算数。参考实现用累计 blocked 计数判断 <code>alive</code>,<code>effective_accept = alive &amp; is_verify &amp; accept</code>,<code>is_final = alive &amp; blocked</code>(sampler.py:243-248)。golden teacher-forcing 覆盖也在这一步:强制 token 直接改写接受判定(sampler.py:239-242)。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">📊</span>④ finalize_verification 汇总</h3>
        <p>单 kernel 产出全部调度器要消费的量:<code>last_valid_offset</code>、逐步计数 <code>num_generated_tokens / num_verified_tokens</code>(按 local_step scatter-add,sampler.py:347-357)、<code>emitted_stop_token</code>(EOS 命中,用于把下一轮置信度清零)以及 <code>batch_confidence_error = Σ|accept_prob − confidence|</code>(sampler.py:584-588)——后者是<b>置信度头的在线校准监控指标</b>,经 llm_engine.py:778 进入统计输出。</p>
      </div>
    </div>

    <h3 style="color:#fff;margin:20px 0 8px;font-size:16px">采样参数扩展与 RNG 隔离</h3>
    <p style="font-size:14px;color:var(--muted)">验证行各自需要一份采样参数(expand_sampling_params,sampler.py:69-109):温度/top-p/top-k/种子按 <code>row_to_req</code> 广播,而采样位置混入步长哈希 <code>sample_positions[req] + local_step * DRAFT_POS_HASH_MUL</code>(<code>DRAFT_POS_HASH_MUL = 10000019</code>,common.py:52)——保证同一请求不同 draft 步、以及 draft 与主模型采样(different tag + <code>_MTP_SEED_OFFSET</code>)互不碰撞。这正是「确定性采样」能在 MTP 关闭时成立、而在 varlen 调度下被破坏的关键机制差异之一(见第 9 节)。</p>

    <pre class="code"><span class="filepath">deepinfer/model_executor/layers/sampler.py:212-259(decode 采样主路径,节选)</span>
speculative_inputs = driver_inputs.speculative
(sampled_tokens, verified_tokens, accepted_token_last_logprobs, last_valid_offset,
 num_generated_tokens, num_verified_tokens, batch_confidence_error, emitted_stop_token
) = self._verification(logits, driver_inputs, decode_inputs, ..., mtp_info_pool=mtp_module.mtp_info_pool)

golden_tokens = sampled_tokens.token_ids
if speculative_inputs is not None:
    predict_tokens = mtp_module.decode_forward(
        main_input_metadata=main_input_metadata, nextn_kv_caches=nextn_kv_caches,
        decode_input=MTPDecodeInput(
            first_token_positions=decode_inputs.mtp_first_token_positions,
            driver=MTPDriverInput(last_valid_offset=last_valid_offset,      <span class="c"># 回退点驱动 draft 起点</span>
                                  golden_tokens=golden_tokens,
                                  sampling=MTPSamplingInput(kernel_inputs=driver_inputs.kernel,
                                                            mtp_info_write_slots=speculative_inputs.mtp_info_write_slots))))
    if emitted_stop_token is not None and predict_tokens.confidence_rates is not None:
        predict_tokens.confidence_rates.masked_fill_(emitted_stop_token.unsqueeze(1), 0.0)  <span class="c"># EOS 后置信度清零</span></pre>

    <div class="note reveal"><b>验证读取的 draft 数据全部来自 GPU pool</b>:draft logprobs(含 force_topk 索引)、token ids、confidence 都由 <code>process_sampling</code> 经 <code>mtp_info_read_rows</code> 直接按行索引(sampler.py:439-457),CPU 全程不接触 draft 细节——这是 DSpark 能与 CUDA graph / ZOS 共存的前提。</div>
  </section>

  <!-- ================= 6. 置信度调度 ================= -->
  <section id="s6">
    <h2 class="sec"><span class="num">6</span>置信度调度验证机制(核心创新)</h2>
    <p class="lede">「验证多少」本身就是一道优化题:验证行越多,单步吞吐越高但每步越慢。DSpark 用 confidence head 的预测 + 在线性能模型解这道题,并且 CPU/ZOS 双路径实现。</p>

    <h3 style="color:#fff;margin:6px 0 8px;font-size:16px">6.1 ConfidenceHead:预测每个 draft 的接受概率</h3>
    <pre class="code"><span class="filepath">deepinfer/model_executor/models/mtp/dflash.py:46-79(节选)</span>
class ConfidenceHead(nn.Module):
    <span class="s">"""Predict the acceptance probability of each draft token."""</span>
    def __init__(self, n_embed, markov_rank, num_steps, weight):
        self.proj = ReplicatedLinear(input_size=n_embed + markov_rank, output_size=1, weight=weight)
        temperature = envs.DEEPINFER_DFLASH_CONFIDENCE_HEAD_TEMPERATURE
        temperatures = temperature if isinstance(temperature, tuple) else (temperature,) * num_steps
        self.temperature = tuple(max(value, SAMPLING_EPS) for value in temperatures)

    def forward(self, hidden, markov_emb, out=None, step_i=0):
        return confidence_head_fused(hidden, weight=self.proj.weight,
                                      temperature=self.temperature[step_i], markov_emb=markov_emb, out=out)</pre>
    <ul class="feat reveal">
      <li>计算即 <code>sigmoid(cat([hidden, markov_emb], -1) @ weight / temperature)</code>,bf16 输入、fp32 输出,由 TileLang fused kernel 一次完成(tilelang_ops/dflash.py:10-46);参考实现对 z 做 ±60 clamp 数值保护(tilelang_ops/dflash.py:49-51)。</li>
      <li>HF 的 DFlash <b>固定包含</b> confidence head(<code>enable_confidence = True</code>,dflash.py:159);权重转 bf16 加载(dflash.py:180-186)。</li>
      <li><b>温度可逐步配置</b>:<code>DEEPINFER_DFLASH_CONFIDENCE_HEAD_TEMPERATURE</code> 默认 1.0;传逗号分隔的元组时长度必须等于 <code>DEEPINFER_USE_NEXTN_DECODE</code>,否则抛错(environ.py:141-150)——直觉上越靠后的 draft 步置信度越失真,可用更高温度「软化」。</li>
      <li>每个 draft step 输出一个 ∈ [0,1] 的概率,组成 <code>confidence_rates [bs, nextn]</code>(sequence.py:92-94),随 <code>MTPPredictInfo</code> 返回并写入 pool。</li>
    </ul>

    <h3 style="color:#fff;margin:22px 0 8px;font-size:16px">6.2 从置信度到调度:接受率的「累乘 + 两轮延迟」</h3>
    <p style="font-size:14px;color:var(--muted);margin-bottom:10px">C++ <code>process_MTPInfo</code> 把逐步 confidence <b>累乘</b>成前缀接受率并按轮次移位(scheduler.hpp:1239-1251):<code>accept_rate[j] = Π_{k&lt;=j} confidence[k]</code>——第 j 个 draft 被接受当且仅当前面全部被接受,所以「第 j 步的验证价值」正比于这个累乘。MtpState 同时保存 <code>prev_accept_rates / accept_rates / confidence_raw / prev_confidence_raw</code>(sequence.hpp:118-156),并用 <code>schedule_cnt / process_cnt</code> 两个计数器标记 ZOS 异步下的配对关系(mtp_varlen.hpp:160-168 注释:N 轮用 N-2 轮算 total_q、用 N-1 轮算每请求 seqlen_q)。</p>

    <pre class="code"><span class="filepath">csrc/engine/mtp_varlen.hpp:228-266(MTPVarlen::schedule 吞吐搜索,节选)</span>
double best_throughput = 0.0; int best_bsz = 0;
float cur_expected = num_seqs;  int cur_bsz = num_seqs;
auto update_best = [&amp;]() {
    <span class="c">// 候选 graph 的耗时 = 启动曲线基线 + 斜率修正 + sampler 估时</span>
    const auto &amp;[graph_size, baseline_ms] = _decode_perf_curve[cur_bsz_idx];
    const double time_ms = baseline_ms + slope_ms * graph_size + sampler_ms;
    if (cur_expected / time_ms &gt; best_throughput) { best_throughput = ...; best_bsz = cur_bsz; }
};
update_best();                       <span class="c">// 只算 golden token 的基线</span>
for (auto &amp;acc : acc_queue_for_bsz) { <span class="c">// 按 (N-2 轮)接受率降序逐个加 draft 行</span>
    cur_expected += acc.first; cur_bsz += 1; update_best();
}
seqlens_q.assign(num_seqs, 1);
for (int i = 0; i &lt; best_bsz - num_seqs; ++i)
    seqlens_q[acc_queue_for_seqs_q[i].second] += 1;   <span class="c">// 多余预算按 (N-1 轮)接受率排序发放</span></pre>

    <ul class="feat reveal">
      <li><b>性能模型在线校准</b>:每步用 CUDA events 实测 forward 与 sampler 耗时(worker.py:129-138 记录, llm_engine.py:997-1002 回传);<code>ForwardRuntimeEstimator</code> 双层中位数拟合「graph size → 斜率」(mtp_varlen.hpp:44-131),<code>SamplerRuntimeEstimator</code> 滑窗中位数估 sampler 耗时(优先同 num_seqs 历史,mtp_varlen.hpp:216-223)。</li>
      <li><b>无曲线时保守退化</b>:<code>seqlens_q = 1 + draft_tokens.size()</code>,即验证全部 draft(mtp_varlen.hpp:153-158)。</li>
      <li>tie-break 规则:接受率相同时按 flat index 升序(mtp_varlen.hpp:210-212),与 GPU kernel 的 rank 规则严格一致(cuda/schedule_mtp_varlen.py:64-67)。</li>
    </ul>

    <div class="figure reveal">
      <svg viewBox="0 0 960 620" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="置信度调度动画">
        <defs>
          <marker id="arrB" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#4f8cff"/>
          </marker>
        </defs>
        <text x="480" y="26" text-anchor="middle" fill="#dbe4f5" font-size="15" font-weight="700">置信度调度:confidence → 累乘接受率 → 全局排序 → 预算分配</text>
        <text x="480" y="44" text-anchor="middle" fill="#8ea0c2" font-size="11">示例:num_seqs=3,nextn=5,total_q 预算=8 ⇒ extra_budget=5(mtp_varlen.hpp:264-266)</text>

        <!-- 左:三个请求的 confidence 芯片 -->
        <text x="150" y="76" text-anchor="middle" fill="#dbe4f5" font-size="12.5" font-weight="700">① ConfidenceHead 输出(逐步)</text>
        <text x="150" y="92" text-anchor="middle" fill="#5a6b92" font-size="10">dflash.py:315-321</text>

        <g font-size="10.5" font-weight="700">
          <!-- Req A -->
          <text x="58" y="122" fill="#8ea0c2">Req A</text>
          <g>
            <rect x="90" y="108" width="42" height="24" rx="5" fill="#22d3ee" opacity=".92"><animate attributeName="opacity" values=".25;.95;.95;.25" keyTimes="0;.05;.6;1" dur="10s" repeatCount="indefinite"/></rect><text x="111" y="124" text-anchor="middle" fill="#0b1020">.95</text>
            <rect x="136" y="108" width="42" height="24" rx="5" fill="#22d3ee" opacity=".85"><animate attributeName="opacity" values=".25;.9;.9;.25" keyTimes="0;.1;.6;1" dur="10s" repeatCount="indefinite"/></rect><text x="157" y="124" text-anchor="middle" fill="#0b1020">.90</text>
            <rect x="182" y="108" width="42" height="24" rx="5" fill="#22d3ee" opacity=".7"><animate attributeName="opacity" values=".25;.8;.8;.25" keyTimes="0;.15;.6;1" dur="10s" repeatCount="indefinite"/></rect><text x="203" y="124" text-anchor="middle" fill="#0b1020">.72</text>
            <rect x="228" y="108" width="42" height="24" rx="5" fill="#22d3ee" opacity=".5"><animate attributeName="opacity" values=".25;.6;.6;.25" keyTimes="0;.2;.6;1" dur="10s" repeatCount="indefinite"/></rect><text x="249" y="124" text-anchor="middle" fill="#0b1020">.54</text>
            <rect x="274" y="108" width="42" height="24" rx="5" fill="#22d3ee" opacity=".35"><animate attributeName="opacity" values=".25;.45;.45;.25" keyTimes="0;.25;.6;1" dur="10s" repeatCount="indefinite"/></rect><text x="295" y="124" text-anchor="middle" fill="#0b1020">.30</text>
          </g>
          <text x="90" y="152" fill="#8ea0c2" font-size="10" font-weight="400">累乘 →</text>
          <g font-weight="400">
            <rect x="130" y="140" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="151" y="153" text-anchor="middle" fill="#a78bfa">.95</text>
            <rect x="176" y="140" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="197" y="153" text-anchor="middle" fill="#a78bfa">.86</text>
            <rect x="222" y="140" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="243" y="153" text-anchor="middle" fill="#a78bfa">.62</text>
            <rect x="268" y="140" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="289" y="153" text-anchor="middle" fill="#a78bfa">.33</text>
            <rect x="314" y="140" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="335" y="153" text-anchor="middle" fill="#a78bfa">.10</text>
          </g>
          <!-- Req B -->
          <text x="58" y="212" fill="#8ea0c2">Req B</text>
          <g>
            <rect x="90" y="198" width="42" height="24" rx="5" fill="#22d3ee" opacity=".6"><animate attributeName="opacity" values=".2;.7;.7;.2" keyTimes="0;.3;.65;1" dur="10s" repeatCount="indefinite"/></rect><text x="111" y="214" text-anchor="middle" fill="#0b1020">.55</text>
            <rect x="136" y="198" width="42" height="24" rx="5" fill="#22d3ee" opacity=".45"><animate attributeName="opacity" values=".2;.55;.55;.2" keyTimes="0;.35;.65;1" dur="10s" repeatCount="indefinite"/></rect><text x="157" y="214" text-anchor="middle" fill="#0b1020">.42</text>
            <rect x="182" y="198" width="42" height="24" rx="5" fill="#22d3ee" opacity=".35"><animate attributeName="opacity" values=".2;.45;.45;.2" keyTimes="0;.4;.65;1" dur="10s" repeatCount="indefinite"/></rect><text x="203" y="214" text-anchor="middle" fill="#0b1020">.28</text>
            <rect x="228" y="198" width="42" height="24" rx="5" fill="#22d3ee" opacity=".28"><animate attributeName="opacity" values=".2;.38;.38;.2" keyTimes="0;.45;.65;1" dur="10s" repeatCount="indefinite"/></rect><text x="249" y="214" text-anchor="middle" fill="#0b1020">.18</text>
            <rect x="274" y="198" width="42" height="24" rx="5" fill="#22d3ee" opacity=".2"><animate attributeName="opacity" values=".2;.3;.3;.2" keyTimes="0;.5;.65;1" dur="10s" repeatCount="indefinite"/></rect><text x="295" y="214" text-anchor="middle" fill="#0b1020">.09</text>
          </g>
          <text x="90" y="242" fill="#8ea0c2" font-size="10" font-weight="400">累乘 →</text>
          <g font-weight="400">
            <rect x="130" y="230" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="151" y="243" text-anchor="middle" fill="#a78bfa">.55</text>
            <rect x="176" y="230" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="197" y="243" text-anchor="middle" fill="#a78bfa">.23</text>
            <rect x="222" y="230" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="243" y="243" text-anchor="middle" fill="#a78bfa">.06</text>
            <rect x="268" y="230" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="289" y="243" text-anchor="middle" fill="#a78bfa">.01</text>
            <rect x="314" y="230" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="335" y="243" text-anchor="middle" fill="#a78bfa">.00</text>
          </g>
          <!-- Req C -->
          <text x="58" y="302" fill="#8ea0c2">Req C</text>
          <g>
            <rect x="90" y="288" width="42" height="24" rx="5" fill="#22d3ee" opacity=".97"><animate attributeName="opacity" values=".25;1;1;.25" keyTimes="0;.55;.85;1" dur="10s" repeatCount="indefinite"/></rect><text x="111" y="304" text-anchor="middle" fill="#0b1020">.98</text>
            <rect x="136" y="288" width="42" height="24" rx="5" fill="#22d3ee" opacity=".9"><animate attributeName="opacity" values=".25;.95;.95;.25" keyTimes="0;.6;.85;1" dur="10s" repeatCount="indefinite"/></rect><text x="157" y="304" text-anchor="middle" fill="#0b1020">.95</text>
            <rect x="182" y="288" width="42" height="24" rx="5" fill="#22d3ee" opacity=".8"><animate attributeName="opacity" values=".25;.85;.85;.25" keyTimes="0;.65;.85;1" dur="10s" repeatCount="indefinite"/></rect><text x="203" y="304" text-anchor="middle" fill="#0b1020">.89</text>
            <rect x="228" y="288" width="42" height="24" rx="5" fill="#22d3ee" opacity=".7"><animate attributeName="opacity" values=".25;.78;.78;.25" keyTimes="0;.7;.85;1" dur="10s" repeatCount="indefinite"/></rect><text x="249" y="304" text-anchor="middle" fill="#0b1020">.80</text>
            <rect x="274" y="288" width="42" height="24" rx="5" fill="#22d3ee" opacity=".6"><animate attributeName="opacity" values=".25;.68;.68;.25" keyTimes="0;.75;.85;1" dur="10s" repeatCount="indefinite"/></rect><text x="295" y="304" text-anchor="middle" fill="#0b1020">.65</text>
          </g>
          <text x="90" y="332" fill="#8ea0c2" font-size="10" font-weight="400">累乘 →</text>
          <g font-weight="400">
            <rect x="130" y="320" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="151" y="333" text-anchor="middle" fill="#a78bfa">.98</text>
            <rect x="176" y="320" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="197" y="333" text-anchor="middle" fill="#a78bfa">.93</text>
            <rect x="222" y="320" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="243" y="333" text-anchor="middle" fill="#a78bfa">.83</text>
            <rect x="268" y="320" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="289" y="333" text-anchor="middle" fill="#a78bfa">.66</text>
            <rect x="314" y="320" width="42" height="18" rx="4" fill="none" stroke="#a78bfa" stroke-dasharray="3 3"/><text x="335" y="333" text-anchor="middle" fill="#a78bfa">.43</text>
          </g>
        </g>

        <!-- 中:全局排序 -->
        <text x="520" y="76" text-anchor="middle" fill="#dbe4f5" font-size="12.5" font-weight="700">② 全局排序(降序,tie 按索引)</text>
        <text x="520" y="92" text-anchor="middle" fill="#5a6b92" font-size="10">前 extra_budget 名获得验证行</text>
        <g font-size="10.5">
          <rect x="455" y="108" width="110" height="22" rx="5" fill="#34d399" opacity=".9"><animate attributeName="opacity" values=".3;.9;.9;.3" keyTimes="0;.55;.9;1" dur="10s" repeatCount="indefinite"/></rect><text x="470" y="123" fill="#06281c" font-weight="700">.98</text><text x="555" y="123" text-anchor="end" fill="#06281c">C·step1</text>
          <rect x="455" y="134" width="110" height="22" rx="5" fill="#34d399" opacity=".85"><animate attributeName="opacity" values=".3;.85;.85;.3" keyTimes="0;.6;.9;1" dur="10s" repeatCount="indefinite"/></rect><text x="470" y="149" fill="#06281c" font-weight="700">.95</text><text x="555" y="149" text-anchor="end" fill="#06281c">A·step1</text>
          <rect x="455" y="160" width="110" height="22" rx="5" fill="#34d399" opacity=".8"><animate attributeName="opacity" values=".3;.8;.8;.3" keyTimes="0;.65;.9;1" dur="10s" repeatCount="indefinite"/></rect><text x="470" y="175" fill="#06281c" font-weight="700">.93</text><text x="555" y="175" text-anchor="end" fill="#06281c">C·step2</text>
          <rect x="455" y="186" width="110" height="22" rx="5" fill="#34d399" opacity=".75"><animate attributeName="opacity" values=".3;.75;.75;.3" keyTimes="0;.7;.9;1" dur="10s" repeatCount="indefinite"/></rect><text x="470" y="201" fill="#06281c" font-weight="700">.86</text><text x="555" y="201" text-anchor="end" fill="#06281c">A·step2</text>
          <rect x="455" y="212" width="110" height="22" rx="5" fill="#34d399" opacity=".7"><animate attributeName="opacity" values=".3;.7;.7;.3" keyTimes="0;.75;.9;1" dur="10s" repeatCount="indefinite"/></rect><text x="470" y="227" fill="#06281c" font-weight="700">.83</text><text x="555" y="227" text-anchor="end" fill="#06281c">C·step3</text>
          <rect x="455" y="238" width="110" height="22" rx="5" fill="#1a2440" stroke="#263352"/><text x="470" y="253" fill="#8ea0c2">.66</text><text x="555" y="253" text-anchor="end" fill="#8ea0c2">C·step4</text>
          <rect x="455" y="264" width="110" height="22" rx="5" fill="#1a2440" stroke="#263352"/><text x="470" y="279" fill="#8ea0c2">.62</text><text x="555" y="279" text-anchor="end" fill="#8ea0c2">A·step3</text>
          <rect x="455" y="290" width="110" height="22" rx="5" fill="#1a2440" stroke="#263352"/><text x="470" y="305" fill="#8ea0c2">.55</text><text x="555" y="305" text-anchor="end" fill="#8ea0c2">B·step1</text>
          <rect x="455" y="316" width="110" height="22" rx="5" fill="#1a2440" stroke="#263352"/><text x="470" y="331" fill="#8ea0c2">.43</text><text x="555" y="331" text-anchor="end" fill="#8ea0c2">C·step5</text>
        </g>
        <text x="520" y="360" text-anchor="middle" fill="#5a6b92" font-size="10">未入榜:验证它们的机会成本高于期望收益</text>

        <!-- 飞行芯片:左 → 中 -->
        <g>
          <g><rect width="34" height="18" rx="4" fill="#34d399" opacity=".9"/><text x="17" y="13" text-anchor="middle" font-size="10" fill="#06281c" font-weight="700">.98</text><animateMotion dur="10s" begin="5.5s" repeatCount="indefinite" path="M150,300 C300,240 380,150 450,120"/></g>
          <g><rect width="34" height="18" rx="4" fill="#34d399" opacity=".85"/><text x="17" y="13" text-anchor="middle" font-size="10" fill="#06281c" font-weight="700">.95</text><animateMotion dur="10s" begin="6s" repeatCount="indefinite" path="M140,120 C300,90 380,140 450,146"/></g>
          <g><rect width="34" height="18" rx="4" fill="#34d399" opacity=".8"/><text x="17" y="13" text-anchor="middle" font-size="10" fill="#06281c" font-weight="700">.93</text><animateMotion dur="10s" begin="6.5s" repeatCount="indefinite" path="M185,300 C330,260 400,180 450,172"/></g>
          <g><rect width="34" height="18" rx="4" fill="#34d399" opacity=".75"/><text x="17" y="13" text-anchor="middle" font-size="10" fill="#06281c" font-weight="700">.86</text><animateMotion dur="10s" begin="7s" repeatCount="indefinite" path="M185,120 C330,120 400,190 450,198"/></g>
          <g><rect width="34" height="18" rx="4" fill="#34d399" opacity=".7"/><text x="17" y="13" text-anchor="middle" font-size="10" fill="#06281c" font-weight="700">.83</text><animateMotion dur="10s" begin="7.5s" repeatCount="indefinite" path="M230,300 C360,280 420,220 450,224"/></g>
        </g>

        <!-- 右:seqlens_q 柱状图 -->
        <text x="800" y="76" text-anchor="middle" fill="#dbe4f5" font-size="12.5" font-weight="700">③ 每请求 seqlens_q = 1 + 赢得数</text>
        <text x="800" y="92" text-anchor="middle" fill="#5a6b92" font-size="10">A=3 · B=1 · C=4,合计 total_q=8</text>
        <line x1="700" y1="330" x2="900" y2="330" stroke="#263352" stroke-width="1.5"/>
        <g>
          <!-- A -->
          <rect x="730" y="328" width="44" height="2" fill="#4f8cff">
            <animate attributeName="height" values="2;2;2;86;86;2" keyTimes="0;.6;.65;.75;.92;1" dur="10s" repeatCount="indefinite"/>
            <animate attributeName="y" values="328;328;328;242;242;328" keyTimes="0;.6;.65;.75;.92;1" dur="10s" repeatCount="indefinite"/>
          </rect>
          <text x="752" y="346" text-anchor="middle" fill="#8ea0c2" font-size="11">A</text>
          <text x="752" y="236" text-anchor="middle" fill="#4f8cff" font-size="11" font-weight="700">3</text>
          <!-- B -->
          <rect x="790" y="328" width="44" height="2" fill="#fbbf24">
            <animate attributeName="height" values="2;2;2;29;29;2" keyTimes="0;.6;.65;.75;.92;1" dur="10s" repeatCount="indefinite"/>
            <animate attributeName="y" values="328;328;328;299;299;328" keyTimes="0;.6;.65;.75;.92;1" dur="10s" repeatCount="indefinite"/>
          </rect>
          <text x="812" y="346" text-anchor="middle" fill="#8ea0c2" font-size="11">B</text>
          <text x="812" y="293" text-anchor="middle" fill="#fbbf24" font-size="11" font-weight="700">1</text>
          <!-- C -->
          <rect x="850" y="328" width="44" height="2" fill="#34d399">
            <animate attributeName="height" values="2;2;2;115;115;2" keyTimes="0;.6;.65;.75;.92;1" dur="10s" repeatCount="indefinite"/>
            <animate attributeName="y" values="328;328;328;213;213;328" keyTimes="0;.6;.65;.75;.92;1" dur="10s" repeatCount="indefinite"/>
          </rect>
          <text x="872" y="346" text-anchor="middle" fill="#8ea0c2" font-size="11">C</text>
          <text x="872" y="207" text-anchor="middle" fill="#34d399" font-size="11" font-weight="700">4</text>
        </g>

        <!-- 预算条 -->
        <text x="800" y="386" text-anchor="middle" fill="#dbe4f5" font-size="12" font-weight="700">total_q 预算(由吞吐搜索决定)</text>
        <rect x="700" y="398" width="200" height="20" rx="6" fill="#1a2440" stroke="#263352"/>
        <rect x="700" y="398" width="2" height="20" rx="0" fill="#22d3ee">
          <animate attributeName="width" values="2;2;2;200;200;2" keyTimes="0;.6;.65;.75;.92;1" dur="10s" repeatCount="indefinite"/>
        </rect>
        <text x="800" y="436" text-anchor="middle" fill="#8ea0c2" font-size="10">best_bsz 搜索:throughput = cur_expected / (baseline + slope·graph + sampler_ms)</text>
        <text x="800" y="452" text-anchor="middle" fill="#5a6b92" font-size="10">mtp_varlen.hpp:242-248</text>

        <text x="480" y="492" text-anchor="middle" fill="#8ea0c2" font-size="11">ZOS 路径:CPU 先用旧一轮的接受率给出初始 seqlens_q,worker 在 GPU 上用<b>最新一轮</b> confidence_rates 重算修正(worker.py:218-219)</text>
        <text x="480" y="510" text-anchor="middle" fill="#8ea0c2" font-size="11">compute_seqlens_q_by_confidence_rates:cumprod → 全局 rank → seqlens_q = 1 + 赢得数(schedule_mtp_varlen.py)</text>
        <text x="480" y="528" text-anchor="middle" fill="#5a6b92" font-size="10">batch_confidence_error = Σ|accept_prob − confidence| 在线校准置信度头(sampler.py:584-588)</text>

        <text x="480" y="570" text-anchor="middle" fill="#5a6b92" font-size="10.5">绿=入榜(获得验证行) · 虚线紫框=累乘接受率(prev_accept_rates / accept_rates 两轮缓存,sequence.hpp:123-125)</text>
        <text x="480" y="588" text-anchor="middle" fill="#5a6b92" font-size="10.5">tie-break:rate 相同按 flat index 升序(CPU mtp_varlen.hpp:210-212 与 GPU kernel cuda/schedule_mtp_varlen.py:64-67 一致)</text>
      </svg>
      <div class="cap">图 2 · 置信度调度的三阶段动画:芯片点亮(累乘)→ 获胜芯片飞入全局排序 → seqlens_q 柱与 total_q 预算条生长</div>
    </div>

    <h3 style="color:#fff;margin:22px 0 8px;font-size:16px">6.3 ZOS 下的 GPU 修正路径(compute_seqlens_q_by_confidence_rates)</h3>
    <p style="font-size:14px;color:var(--muted);margin-bottom:10px">ZOS 异步调度下,C++ 侧 <code>seqlens_q</code> 落后真实采样结果一步。Worker 在主 forward 前用 <code>_correct_seqlens_qk</code>(worker.py:191-245)在 GPU 上修正:</p>
    <pre class="code"><span class="filepath">deepinfer/worker/worker.py:209-227(节选)</span>
remap_cpu, seqlens_q_cpu, seqlens_k_cpu, has_overlap = prepare_zos_inputs(
    seq_metadata_list, prev.seq_metadata_list, n_seq_with_padding, self.nextn)
if envs.DEEPINFER_ENABLE_MTP_VARLEN:
    compute_seqlens_q_by_confidence_rates(total_q, remap[:n_seq],
                                          prev.sampler_output.confidence_rates_gpu, seqlens_q[:n_seq])
if self.nextn &gt; 0:
    compute_seqlens_k_zos(seqlens_k[:n_seq], seqlens_q[:n_seq], remap[:n_seq],
                          prev.sampler_output.num_accepted_tokens_gpu, nextn=self.nextn)
if envs.DEEPINFER_ENABLE_MTP_VARLEN:
    seqlens_q_cpu[:n_seq].copy_(seqlens_q[:n_seq], non_blocking=True)   <span class="c"># D2H,事件同步后喂回 CPU 元数据</span>
    d2h_evt = torch.cuda.Event(); d2h_evt.record()</pre>
    <ul class="feat reveal">
      <li><code>remap</code> 由 <code>prepare_zos_inputs</code> 按 seq_id 对齐上一步 batch(同序走快速路径,zos.cpp:142-175);<code>-1</code> 表示新请求,其 confidence 视为 0(只保留 1 个 fresh 行)。</li>
      <li>TileLang kernel <b>两阶段 fused</b>(cuda/schedule_mtp_varlen.py:14-83):Phase 1 按行做 cumprod(remap 散读 + 新请求置 0);Phase 2 每 block 128 线程做全量 rank 计数(reducer 归约),<code>seqlens_q[pid] = 1 + count(rank &lt; total_q - num_seqs)</code>——与 CPU 参考实现(schedule_mtp_varlen.py:35-98)严格 bit-exact。NPU 侧要求 rates 不超过 32KB UB(schedule_mtp_varlen.py:30-31)。</li>
      <li>修正后还要同步修 K 长度:<code>seqlens_k += seqlens_q − (nextn − prev_num_accepted_tokens)</code>(compute_seqlens_k_zos.py:12-33),把上一步「多验但没全接受」的部分扣回来。</li>
      <li>D2H 完成后 <code>update_metadata_for_sampling_zos</code>(zos.cpp:279-306)重写 SequenceMetadata 的 seqlen_q/seqlen_k 并 <code>refresh_for_sampling</code> 重建读行——采样阶段使用的即修正后的布局(worker.py:147-152)。</li>
    </ul>
  </section>

  <!-- ================= 7. MTPInfoPool 与 KV 回退 ================= -->
  <section id="s7">
    <h2 class="sec"><span class="num">7</span>MTPInfoPool 与回退的 KV 代价</h2>
    <p class="lede">draft 信息需要跨 step 存活(本轮验证读上一轮写入),且被拒绝的 draft 不能污染 KV——这两点分别由 MTPInfoPool 与「乐观推进 + 回填」解决。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🗄️</span>MTPInfoPool:按调度器 slot 索引</h3>
        <p>每个 slot 拥有 <code>nextn</code> 行,<b>slot 0 保留作 padding</b>(token=词表尾,pad logprob 仅首位为 0);<code>pool_rows = (max_num_seqs+1) * nextn</code>,logprobs 占 <code>pool_rows × (force_topk 或 vocab_size) × 4B</code>,force-topk 模式再翻一份 int32 索引,confidence 为每行 1 个 fp32(mtp_info_pool.py:14-52)。<code>write_slots==0</code> 的写入被 store kernel 跳过以保护 padding(store_mtp_info.py:36-39)。仅在 driver completion worker 上分配(dflash.py:188-196, model_runner.py:98-99);slot 生命周期与 running 队列严格同步(scheduler.hpp:682-685),请求结束即释放(scheduler.hpp:907, 993)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">↩️</span>回退的物理代价</h3>
        <p>SWA cache 的 <code>swa_block_size = window_size + DEEPINFER_MAX_BACKTRACKING_TOKENS</code>(cache_engine.py:87-93);压缩环为 <code>compress_ratio + max(0, backtrack − 1)</code>(cache_engine.py:128-133);YoCo 截断模式要求 <code>KEEP_TOKENS ≥ window_size + backtrack</code>(model_runner.py:107-113,与 C++ 侧 TORCH_CHECK 一致:prepare_tensor_input_v4.cpp:354-357)。<code>DEEPINFER_MAX_BACKTRACKING_TOKENS</code> 被强制 ≥ <code>NEXTN+1</code>(environ.py:139)——回退余量天然覆盖「整步 draft 全军覆没」的最坏情形。</p>
      </div>
    </div>

    <div class="note warn reveal">
      <b>跨 step 写后读依赖</b>(sampler.py:85 注释):「MTP info pool 存在跨 step 的写后读依赖:本轮 verification 读取上一轮 DFlash graph replay 写入的 pool;二者当前位于同一 stream,执行顺序由 stream 保证。」——这也是 DFlash CUDA graph 能把 pool 写入一并捕获的安全前提。
    </div>

    <div class="figure reveal">
      <svg viewBox="0 0 960 470" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="varlen 验证 batch 布局与 ZOS 修正管线动画">
        <defs>
          <marker id="arrC" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#4f8cff"/>
          </marker>
        </defs>
        <text x="480" y="26" text-anchor="middle" fill="#dbe4f5" font-size="15" font-weight="700">varlen 验证 batch:packed 布局 + ZOS 下的 seqlens_q GPU 修正</text>

        <!-- 修正管线 -->
        <g>
          <rect x="30" y="52" width="200" height="64" rx="9" fill="#16233f" stroke="#4f8cff" stroke-width="1.5"/>
          <text x="130" y="76" text-anchor="middle" fill="#dbe4f5" font-size="12" font-weight="700">CPU 初始 seqlens_q</text>
          <text x="130" y="94" text-anchor="middle" fill="#8ea0c2" font-size="9.5">MTPVarlen::schedule(旧一轮接受率)</text>
          <text x="130" y="108" text-anchor="middle" fill="#5a6b92" font-size="9">scheduler.hpp:651-652</text>

          <rect x="270" y="52" width="230" height="64" rx="9" fill="#16233f" stroke="#a78bfa" stroke-width="1.5"/>
          <text x="385" y="76" text-anchor="middle" fill="#dbe4f5" font-size="12" font-weight="700">GPU:置信度重分配</text>
          <text x="385" y="94" text-anchor="middle" fill="#8ea0c2" font-size="9.5">cumprod + 全局 rank(两阶段 TileLang)</text>
          <text x="385" y="108" text-anchor="middle" fill="#5a6b92" font-size="9">cuda/schedule_mtp_varlen.py:14-83</text>

          <rect x="540" y="52" width="190" height="64" rx="9" fill="#16233f" stroke="#fbbf24" stroke-width="1.5"/>
          <text x="635" y="76" text-anchor="middle" fill="#dbe4f5" font-size="12" font-weight="700">D2H + 元数据刷新</text>
          <text x="635" y="94" text-anchor="middle" fill="#8ea0c2" font-size="9.5">update_metadata_for_sampling_zos</text>
          <text x="635" y="108" text-anchor="middle" fill="#5a6b92" font-size="9">zos.cpp:279-306</text>

          <rect x="770" y="52" width="160" height="64" rx="9" fill="#16233f" stroke="#34d399" stroke-width="1.5"/>
          <text x="850" y="76" text-anchor="middle" fill="#dbe4f5" font-size="12" font-weight="700">验证 batch</text>
          <text x="850" y="94" text-anchor="middle" fill="#8ea0c2" font-size="9.5">logits → fused_sample</text>
          <text x="850" y="108" text-anchor="middle" fill="#5a6b92" font-size="9">sampler.py:428-457</text>
        </g>
        <!-- 管线流动 tokens -->
        <g>
          <g><rect width="16" height="12" rx="3" fill="#4f8cff"/><animateMotion dur="6s" begin="0s" repeatCount="indefinite" path="M232,84 L266,84"/></g>
          <g><rect width="16" height="12" rx="3" fill="#a78bfa"/><animateMotion dur="6s" begin="1s" repeatCount="indefinite" path="M232,84 L266,84"/></g>
          <g><rect width="16" height="12" rx="3" fill="#a78bfa"/><animateMotion dur="6s" begin="1.6s" repeatCount="indefinite" path="M502,84 L536,84"/></g>
          <g><rect width="16" height="12" rx="3" fill="#fbbf24"/><animateMotion dur="6s" begin="2.6s" repeatCount="indefinite" path="M502,84 L536,84"/></g>
          <g><rect width="16" height="12" rx="3" fill="#fbbf24"/><animateMotion dur="6s" begin="3.4s" repeatCount="indefinite" path="M732,84 L766,84"/></g>
          <g><rect width="16" height="12" rx="3" fill="#34d399"/><animateMotion dur="6s" begin="4.4s" repeatCount="indefinite" path="M732,84 L766,84"/></g>
        </g>
        <path class="flowline" d="M232,84 L264,84" stroke="#4f8cff" stroke-width="1.8" fill="none"/>
        <path class="flowline" d="M502,84 L534,84" stroke="#a78bfa" stroke-width="1.8" fill="none"/>
        <path class="flowline" d="M732,84 L764,84" stroke="#fbbf24" stroke-width="1.8" fill="none"/>

        <!-- packed 布局(两个状态交叉淡入淡出) -->
        <text x="480" y="158" text-anchor="middle" fill="#dbe4f5" font-size="13" font-weight="700">packed total_q 布局(每请求:验证行…+ 1 个 fresh 行)</text>

        <!-- 状态 1 -->
        <g>
          <animate attributeName="opacity" values="1;1;0;0;1" keyTimes="0;.45;.5;.95;1" dur="8s" repeatCount="indefinite"/>
          <g font-size="10">
            <text x="40" y="184" fill="#8ea0c2">状态 A</text>
            <!-- R0: 3 -->
            <rect x="90" y="170" width="120" height="34" rx="6" fill="#22d3ee" opacity=".8"/><text x="150" y="188" text-anchor="middle" fill="#0b1020" font-weight="700">R0 · v v | fresh</text><text x="150" y="200" text-anchor="middle" fill="#062f38" font-size="9">seqlen_q=3</text>
            <!-- R1: 1 -->
            <rect x="218" y="170" width="56" height="34" rx="6" fill="#fbbf24" opacity=".85"/><text x="246" y="188" text-anchor="middle" fill="#33230a" font-weight="700">R1 · fresh</text><text x="246" y="200" text-anchor="middle" fill="#4a350c" font-size="9">seqlen_q=1</text>
            <!-- R2: 5 -->
            <rect x="282" y="170" width="240" height="34" rx="6" fill="#22d3ee" opacity=".8"/><text x="402" y="188" text-anchor="middle" fill="#0b1020" font-weight="700">R2 · v v v v | fresh</text><text x="402" y="200" text-anchor="middle" fill="#062f38" font-size="9">seqlen_q=5(= nextn+1)</text>
            <!-- R3: 2 -->
            <rect x="528" y="170" width="88" height="34" rx="6" fill="#22d3ee" opacity=".8"/><text x="572" y="188" text-anchor="middle" fill="#0b1020" font-weight="700">R3 · v | fresh</text><text x="572" y="200" text-anchor="middle" fill="#062f38" font-size="9">seqlen_q=2</text>
            <text x="640" y="188" fill="#8ea0c2">→ total_q = 11</text>
          </g>
        </g>
        <!-- 状态 2 -->
        <g>
          <animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;.45;.5;.95;1" dur="8s" repeatCount="indefinite"/>
          <g font-size="10">
            <text x="40" y="184" fill="#8ea0c2">状态 B</text>
            <rect x="90" y="170" width="184" height="34" rx="6" fill="#22d3ee" opacity=".8"/><text x="182" y="188" text-anchor="middle" fill="#0b1020" font-weight="700">R0 · v v v | fresh</text><text x="182" y="200" text-anchor="middle" fill="#062f38" font-size="9">seqlen_q=4(置信度上升)</text>
            <rect x="282" y="170" width="56" height="34" rx="6" fill="#fbbf24" opacity=".85"/><text x="310" y="188" text-anchor="middle" fill="#33230a" font-weight="700">R1 · fresh</text><text x="310" y="200" text-anchor="middle" fill="#4a350c" font-size="9">seqlen_q=1</text>
            <rect x="346" y="170" width="184" height="34" rx="6" fill="#22d3ee" opacity=".8"/><text x="438" y="188" text-anchor="middle" fill="#0b1020" font-weight="700">R2 · v v v | fresh</text><text x="438" y="200" text-anchor="middle" fill="#062f38" font-size="9">seqlen_q=4</text>
            <rect x="536" y="170" width="120" height="34" rx="6" fill="#22d3ee" opacity=".8"/><text x="596" y="188" text-anchor="middle" fill="#0b1020" font-weight="700">R3 · v v | fresh</text><text x="596" y="200" text-anchor="middle" fill="#062f38" font-size="9">seqlen_q=3</text>
            <text x="676" y="188" fill="#8ea0c2">→ total_q = 12</text>
          </g>
        </g>

        <!-- is_verify 图例 -->
        <g font-size="10.5">
          <rect x="90" y="228" width="14" height="14" rx="3" fill="#22d3ee" opacity=".8"/><text x="112" y="239" fill="#8ea0c2">验证行 is_verify=true(读 pool:read_slot*nextn + j,prepare_sample.cpp:221-223)</text>
          <rect x="90" y="250" width="14" height="14" rx="3" fill="#fbbf24" opacity=".85"/><text x="112" y="261" fill="#8ea0c2">fresh 行 is_verify=false(读 padding slot 0,prepare_sample.cpp:225)</text>
        </g>

        <!-- 乐观推进/回填动画 -->
        <text x="480" y="300" text-anchor="middle" fill="#dbe4f5" font-size="13" font-weight="700">KV 计数:乐观推进 → 按实际接受数回填(回退)</text>
        <g>
          <!-- 标尺 -->
          <line x1="120" y1="340" x2="840" y2="340" stroke="#263352" stroke-width="2"/>
          <g stroke="#263352"><line x1="120" y1="334" x2="120" y2="346"/><line x1="840" y1="334" x2="840" y2="346"/></g>
          <text x="120" y="364" text-anchor="middle" fill="#5a6b92" font-size="10">num_tokens</text>
          <text x="840" y="364" text-anchor="middle" fill="#5a6b92" font-size="10">乐观推进后</text>
          <!-- 乐观推进条 -->
          <rect x="120" y="322" width="0" height="14" rx="3" fill="#4f8cff" opacity=".8">
            <animate attributeName="width" values="0;0;720;720;0" keyTimes="0;.15;.3;.7;1" dur="8s" repeatCount="indefinite"/>
          </rect>
          <!-- 回退阴影 -->
          <rect x="620" y="322" width="0" height="14" rx="0" fill="#f87171" opacity=".55">
            <animate attributeName="width" values="0;0;220;220;0" keyTimes="0;.3;.45;.7;1" dur="8s" repeatCount="indefinite"/>
          </rect>
          <text x="730" y="312" fill="#f87171" font-size="10.5" opacity="0">
            nextn − 实际接受数(被拒 draft,不占 KV)
            <animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;.3;.45;.7;1" dur="8s" repeatCount="indefinite"/>
          </text>
          <!-- 回填游标 -->
          <line x1="840" y1="318" x2="840" y2="342" stroke="#34d399" stroke-width="3">
            <animate attributeName="x1" values="840;840;620;620;840" keyTimes="0;.3;.45;.7;1" dur="8s" repeatCount="indefinite"/>
            <animate attributeName="x2" values="840;840;620;620;840" keyTimes="0;.3;.45;.7;1" dur="8s" repeatCount="indefinite"/>
          </line>
          <text x="620" y="292" fill="#34d399" font-size="10.5" opacity="0">commit_processed_tokens(token_cnt)
            <animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;.3;.45;.7;1" dur="8s" repeatCount="indefinite"/>
          </text>
        </g>
        <text x="480" y="410" text-anchor="middle" fill="#8ea0c2" font-size="11">scheduler.hpp:927 advance_optimistically(seqlens_q[i]) → scheduler.hpp:997-1000 commit_processed_tokens(token_cnt)</text>
        <text x="480" y="430" text-anchor="middle" fill="#5a6b92" font-size="10.5">accepted_token_ids 为 [total_q] 扁平布局:每请求前 seqlens_q[i]−1 个是 draft(−1 = 未接受),最后 1 位是 main 位置(scheduler.hpp:873-875)</text>
        <text x="480" y="450" text-anchor="middle" fill="#5a6b92" font-size="10.5">物理 KV 预留:swa_block_size = window + DEEPINFER_MAX_BACKTRACKING_TOKENS(cache_engine.py:87-93)</text>
      </svg>
      <div class="cap">图 3 · 上:ZOS 下 seqlens_q 的 GPU 修正管线(数据包流动画);中:packed 布局两种状态交替(动态变长);下:KV 乐观推进与回填(回退)动画</div>
    </div>
  </section>

  <!-- ================= 8. DFlash CUDA Graph ================= -->
  <section id="s8">
    <h2 class="sec"><span class="num">8</span>DFlash CUDA Graph 与 decode 性能曲线</h2>
    <p class="lede">draft 执行是每步固定拓扑的小网络,DeepInfer 把它从 CP 广播到 pool 写入整段捕获成图,并顺带「量出」调度器要用的性能曲线。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🚀</span>启用条件与捕获粒度</h3>
        <p>需要主模型 CUDA graph 已启用、<code>DEEPINFER_DFLASH_ENFORCE_EAGER</code> 未设置、<code>nextn &gt; 0</code> 且模型带 <code>dflash_cfg</code>(model_runner.py:80-85)。图的 batch 轴是<b>请求数</b>(<code>max_num_seqs</code>,dflash_cuda_graph_runner.py:88-91)——与主图按 <code>total_q</code>(上限 <code>max_num_seqs×(1+nextn)</code>,model_runner.py:76-79)选择不同。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧰</span>batch size 梯度</h3>
        <p><code>build_graph_batch_sizes(max_num_seqs, DEEPINFER_DFLASH_CUDAGRAPH_BATCH_SIZE_INTERVAL)</code>:先 1,2,4,…2<sup>k</sup> 预热,再按 interval(默认 8)等距,最后补 max(cuda_graph_runner.py:41-51)。replay 时 <code>bisect_left</code> 选不小于当前请求数的最小图,尾部用 padding 输入补齐(dflash_cuda_graph_runner.py:77-91)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">💾</span>与主图共享内存池</h3>
        <p>捕获复用主图的 <code>graph_memory_pool</code> 与 <code>graph_stream</code>(model_runner.py:538-549),日志输出额外显存开销;<code>capture_error_mode="thread_local"</code>(dflash_cuda_graph_runner.py:68)。捕获前必须先捕获主图(assert,model_runner.py:539)。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">📈</span>decode 性能曲线(profile_decode_perf)</h3>
        <p>对每个 batch size 重放主图并用 CUDA events 计时(1 次预热 + 5 次测量 + 去掉最大最小各 1 次的截尾均值),跨 EP 组 all_reduce 取平均,结果写入 <code>DecodePerfCache</code>(model_runner.py:562-631)。曲线仅在 <code>ENABLE_MTP_VARLEN</code> 时采集(base.py:280-281),随后喂给 <code>MTPVarlen::set_decode_perf_curve</code> 作为吞吐搜索的基线。</p>
      </div>
    </div>

    <div class="note reveal">
      <b>整段捕获的收益</b>(dflash.py:353-357 注释):「With the DFlash CUDA graph this is captured as a unit: the driver's broadcast (followers receive into buffers allocated here, whose addresses the graph fixes), the fixed-stride metadata, the draft layers and the sampling (which includes the pool write) are all replayed.」——CP follower 的接收缓冲地址在捕获时固化,重放期间广播照常发生。
    </div>

    <div class="figure reveal">
      <svg viewBox="0 0 960 430" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="DFlash CUDA Graph 捕获与重放动画">
        <defs>
          <linearGradient id="capsule" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stop-color="#16233f"/><stop offset="1" stop-color="#1d2a4d"/>
          </linearGradient>
        </defs>
        <text x="480" y="26" text-anchor="middle" fill="#dbe4f5" font-size="15" font-weight="700">DFlash CUDA Graph:捕获为整体,重放一次完成</text>

        <!-- 捕获段 -->
        <text x="235" y="62" text-anchor="middle" fill="#a78bfa" font-size="12.5" font-weight="700">捕获(一次性)</text>
        <g font-size="9.5" fill="#8ea0c2">
          <rect x="40" y="80" width="120" height="26" rx="6" fill="#16233f" stroke="#4f8cff"/><text x="100" y="97" text-anchor="middle">driver 广播(warmup)</text>
          <rect x="40" y="114" width="120" height="26" rx="6" fill="#16233f" stroke="#4f8cff"/><text x="100" y="131" text-anchor="middle">build_dflash_input</text>
          <rect x="40" y="148" width="120" height="26" rx="6" fill="#16233f" stroke="#4f8cff"/><text x="100" y="165" text-anchor="middle">draft 层 × N</text>
          <rect x="40" y="182" width="120" height="26" rx="6" fill="#16233f" stroke="#4f8cff"/><text x="100" y="199" text-anchor="middle">sample + pool 写入</text>
        </g>
        <!-- 捕获胶囊 -->
        <rect x="235" y="92" width="220" height="120" rx="16" fill="url(#capsule)" stroke="#a78bfa" stroke-width="2">
          <animate attributeName="stroke-opacity" values=".5;1;.5" dur="3s" repeatCount="indefinite"/>
        </rect>
        <text x="345" y="128" text-anchor="middle" fill="#dbe4f5" font-size="12" font-weight="700">torch.cuda.CUDAGraph</text>
        <text x="345" y="148" text-anchor="middle" fill="#8ea0c2" font-size="9.5">pool = 主图 graph_memory_pool</text>
        <text x="345" y="164" text-anchor="middle" fill="#8ea0c2" font-size="9.5">stream = 主图 graph_stream</text>
        <text x="345" y="180" text-anchor="middle" fill="#5a6b92" font-size="9">dflash_cuda_graph_runner.py:42-75</text>
        <text x="345" y="198" text-anchor="middle" fill="#5a6b92" font-size="9">capture_error_mode="thread_local"</text>
        <!-- 捕获流动:op 块飞入胶囊 -->
        <g>
          <g><rect width="70" height="14" rx="4" fill="#4f8cff" opacity=".8"/><animateMotion dur="5s" begin="0s" repeatCount="indefinite" path="M100,93 C160,90 200,110 233,120"/></g>
          <g><rect width="70" height="14" rx="4" fill="#4f8cff" opacity=".7"/><animateMotion dur="5s" begin="1.2s" repeatCount="indefinite" path="M100,127 C160,124 200,130 233,140"/></g>
          <g><rect width="70" height="14" rx="4" fill="#4f8cff" opacity=".6"/><animateMotion dur="5s" begin="2.4s" repeatCount="indefinite" path="M100,161 C160,158 200,150 233,155"/></g>
          <g><rect width="70" height="14" rx="4" fill="#4f8cff" opacity=".5"/><animateMotion dur="5s" begin="3.6s" repeatCount="indefinite" path="M100,195 C160,192 200,175 233,168"/></g>
        </g>

        <!-- 重放段 -->
        <text x="730" y="62" text-anchor="middle" fill="#34d399" font-size="12.5" font-weight="700">重放(每个 decode step)</text>
        <g font-size="9.5" fill="#8ea0c2">
          <rect x="500" y="80" width="150" height="26" rx="6" fill="#16233f" stroke="#22d3ee"/><text x="575" y="97" text-anchor="middle">copy_dflash_decode_input</text>
          <rect x="500" y="114" width="150" height="26" rx="6" fill="#16233f" stroke="#22d3ee"/><text x="575" y="131" text-anchor="middle">graph.replay()</text>
          <rect x="500" y="148" width="150" height="26" rx="6" fill="#16233f" stroke="#22d3ee"/><text x="575" y="165" text-anchor="middle">output.narrow(req_cnt)</text>
        </g>
        <text x="575" y="196" text-anchor="middle" fill="#5a6b92" font-size="9">dflash_cuda_graph_runner.py:84-91</text>
        <!-- 重放胶囊 -->
        <rect x="700" y="92" width="230" height="120" rx="16" fill="url(#capsule)" stroke="#34d399" stroke-width="2">
          <animate attributeName="stroke-opacity" values="1;.45;1" dur="2.2s" repeatCount="indefinite"/>
        </rect>
        <text x="815" y="128" text-anchor="middle" fill="#dbe4f5" font-size="12" font-weight="700">已捕获的 draft 计算</text>
        <text x="815" y="148" text-anchor="middle" fill="#8ea0c2" font-size="9.5">9 个输入张量单 kernel 填充:</text>
        <text x="815" y="164" text-anchor="middle" fill="#8ea0c2" font-size="9.5">ftp / last_valid_offset / golden / 采样参数…</text>
        <text x="815" y="180" text-anchor="middle" fill="#5a6b92" font-size="9">dflash_copy.py:36-59(尾部取 padding)</text>
        <!-- 输入输出流动 -->
        <g>
          <g><rect width="60" height="13" rx="3" fill="#22d3ee" opacity=".85"/><animateMotion dur="3.2s" begin="0s" repeatCount="indefinite" path="M500,93 C560,60 640,70 698,110"/></g>
          <g><rect width="60" height="13" rx="3" fill="#22d3ee" opacity=".7"/><animateMotion dur="3.2s" begin="0.8s" repeatCount="indefinite" path="M500,93 C560,60 640,70 698,110"/></g>
          <g><rect width="60" height="13" rx="3" fill="#22d3ee" opacity=".55"/><animateMotion dur="3.2s" begin="1.6s" repeatCount="indefinite" path="M500,93 C560,60 640,70 698,110"/></g>
          <g><rect width="60" height="13" rx="3" fill="#22d3ee" opacity=".4"/><animateMotion dur="3.2s" begin="2.4s" repeatCount="indefinite" path="M500,93 C560,60 640,70 698,110"/></g>
        </g>
        <!-- 输出:token + confidence -->
        <g>
          <g><rect width="58" height="15" rx="4" fill="#34d399"/><text x="29" y="11.5" text-anchor="middle" font-size="8.5" fill="#06281c" font-weight="700">token_ids</text><animateMotion dur="3.2s" begin="1s" repeatCount="indefinite" path="M930,130 C950,140 950,170 928,182"/></g>
          <g><rect width="72" height="15" rx="4" fill="#fbbf24"/><text x="36" y="11.5" text-anchor="middle" font-size="8.5" fill="#33230a" font-weight="700">confidence</text><animateMotion dur="3.2s" begin="2.2s" repeatCount="indefinite" path="M930,130 C950,140 950,170 928,182"/></g>
        </g>
        <text x="815" y="212" text-anchor="middle" fill="#8ea0c2" font-size="9.5">MTPPredictInfo.narrow 去除图内 padding 后返回(dflash_cuda_graph_runner.py:91)</text>

        <!-- 底部:性能曲线 -->
        <text x="480" y="252" text-anchor="middle" fill="#dbe4f5" font-size="13" font-weight="700">profile_decode_perf → MTPVarlen 的 (bs, forward_ms) 基线曲线</text>
        <polyline points="60,368 160,352 260,344 360,338 460,332 560,326 660,321 760,316 860,312"
          fill="none" stroke="#22d3ee" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
        <g fill="#22d3ee">
          <circle cx="60" cy="368" r="4"><animate attributeName="r" values="4;6;4" dur="2.4s" repeatCount="indefinite"/></circle>
          <circle cx="260" cy="344" r="4"><animate attributeName="r" values="4;6;4" dur="2.4s" begin=".4s" repeatCount="indefinite"/></circle>
          <circle cx="460" cy="332" r="4"><animate attributeName="r" values="4;6;4" dur="2.4s" begin=".8s" repeatCount="indefinite"/></circle>
          <circle cx="660" cy="321" r="4"><animate attributeName="r" values="4;6;4" dur="2.4s" begin="1.2s" repeatCount="indefinite"/></circle>
          <circle cx="860" cy="312" r="4"><animate attributeName="r" values="4;6;4" dur="2.4s" begin="1.6s" repeatCount="indefinite"/></circle>
        </g>
        <text x="480" y="392" text-anchor="middle" fill="#8ea0c2" font-size="10.5">每点 = 一个捕获 batch size 的截尾均值耗时(5 测 2 截,model_runner.py:586-623),运行期再叠加 slope_ms·graph 与 sampler_ms 修正(mtp_varlen.hpp:242-248)</text>
        <text x="480" y="410" text-anchor="middle" fill="#5a6b92" font-size="10">曲线缓存:DEEPINFER_DECODE_PERF_CACHE_DIR / DEEPINFER_DECODE_PERF_CACHE_TTL_SEC(environ.py:165-166)</text>
      </svg>
      <div class="cap">图 4 · DFlash CUDA Graph 的捕获/重放双阶段(数据包流动画)+ decode 性能曲线采样点脉动</div>
    </div>

    <div class="note good reveal">
      <b>CP follower 的处理</b>:非 driver rank 上 <code>do_sample=False</code>,replay 不产出输出(dflash_cuda_graph_runner.py:90-91);<code>run_drafts</code> 内 driver 通过 <code>cp_broadcast_multi_tensor</code> 把 <code>last_valid_offset / golden_tokens</code> 广播给 follower——follower 断言必须开启 CP(dflash.py:362),且其接收缓冲地址被图固定(dflash.py:353-357)。
    </div>
  </section>

  <!-- ================= 9. 环境变量 ================= -->
  <section id="s9">
    <h2 class="sec"><span class="num">9</span>环境变量与调优速查</h2>
    <p class="lede">所有 DSpark 相关开关集中定义于 <span class="filepath">deepinfer/environ.py</span>;改回退相关变量后需清压缩环缓存(cache_engine.py:136-137)。</p>

    <table class="tbl reveal">
      <tr><th>变量</th><th>默认</th><th>语义与调优要点</th><th>出处</th></tr>
      <tr><td><code>DEEPINFER_ENABLE_MTP_VARLEN</code></td><td>关闭</td><td>启用置信度调度的变长验证:开启后才会采集 decode 性能曲线(base.py:280-281)、启用 ZOS 的 GPU seqlens_q 修正(worker.py:218)与耗时反馈(worker.py:129-138)。关闭时退化为「验证全部 draft」。</td><td>environ.py:138</td></tr>
      <tr><td><code>DEEPINFER_USE_NEXTN_DECODE</code></td><td>5</td><td>最大 draft 深度;设 0 彻底关闭投机解码。同时约束验证行上界 <code>seqlen_q ≤ nextn+1</code> 与回退下限。</td><td>environ.py:136-137<br>prepare_sample.cpp:212</td></tr>
      <tr><td><code>DEEPINFER_MAX_BACKTRACKING_TOKENS</code></td><td>≥ nextn+1</td><td>KV/压缩环/YoCo 截断为回退预留的 token 数;取值被钳制到不小于 <code>NEXTN+1</code>。增大它会同步增大 swa_block_size 与压缩环宽度(显存 ↑)。</td><td>environ.py:139<br>cache_engine.py:87-93</td></tr>
      <tr><td><code>DEEPINFER_DFLASH_CONFIDENCE_HEAD_TEMPERATURE</code></td><td>1.0</td><td>confidence sigmoid 温度;支持逗号分隔的<b>逐 draft 步</b>元组(长度必须等于 NEXTN,否则抛错)。&gt;1 软化预测、调度更保守;&lt;1 则更激进。</td><td>environ.py:141-150</td></tr>
      <tr><td><code>DEEPINFER_DFLASH_ENFORCE_EAGER</code></td><td>关闭</td><td>强制 DFlash 走 eager(不捕获 DFlash 图);调试逐 kernel 行为时使用。主图另有 <code>DEEPINFER_ENFORCE_EAGER</code>。</td><td>environ.py:163<br>model_runner.py:80-85</td></tr>
      <tr><td><code>DEEPINFER_DFLASH_CUDAGRAPH_BATCH_SIZE_INTERVAL</code></td><td>8</td><td>DFlash 图的 batch size 采样间隔(先 2 的幂预热再等距);减小间隔 → 更多图、重放 padding 更少但捕获耗时与显存增加。</td><td>environ.py:164<br>cuda_graph_runner.py:41-51</td></tr>
      <tr><td><code>DEEPINFER_CUDAGRAPH_BATCH_SIZE_INTERVAL</code></td><td>8</td><td>主模型图间隔;主图 batch 轴上限为 <code>max_num_seqs×(1+nextn)</code>——MTP 开启时主图候选数会显著变多。</td><td>environ.py:162<br>model_runner.py:76-79</td></tr>
      <tr><td><code>DEEPINFER_SAMPLER_FORCE_TOPK</code></td><td>关闭</td><td>采样只在 top-k logits 上进行(降低 logprobs 显存);开启后 draft/验证两侧需 <code>remap_draft_topk</code> 对齐 top-k 空间,MTPInfoPool 也需额外 int32 索引池。</td><td>environ.py:157<br>sampler_utils.py:171-180</td></tr>
      <tr><td><code>DEEPINFER_DECODE_PERF_CACHE_DIR / _TTL_SEC</code></td><td>无 / 3600s</td><td>decode 性能曲线的磁盘缓存目录与有效期;曲线失效会导致调度器短暂退化为「全验证」模式。</td><td>environ.py:165-166</td></tr>
      <tr><td><code>DEEPINFER_BATCH_INVARIANT</code></td><td>关闭</td><td>批次不变性;与确定性采样联动,要求和 <code>ENABLE_MTP_VARLEN=0</code> 一起使用(见第 10 节)。</td><td>environ.py:204<br>README.md:28</td></tr>
    </table>

    <div class="note warn reveal">
      <b>调优建议(基于代码行为的推演)</b>:① 负载以「接受率高、序列同质」为主时保持默认温度 1.0;若观察到 <code>batch_confidence_error</code> 持续偏大(说明 confidence head 失准),可用逐步温度把深层 draft 的预测压低。② 增大 <code>NEXTN</code> 时记得同步评估 <code>MAX_BACKTRACKING_TOKENS</code>、压缩环与 swa_block_size 的显存代价。③ 修改回退类变量后调用 <code>clear_compress_block_size_cache</code>(cache_engine.py:136-137)避免读到旧环宽。
    </div>
  </section>

  <!-- ================= 10. 批次不变性 ================= -->
  <section id="s10">
    <h2 class="sec"><span class="num">10</span>与批次不变性 / 确定性采样的交互</h2>
    <p class="lede">README 的确定性配方明确要求 <code>DEEPINFER_BATCH_INVARIANT=1 DEEPINFER_ENABLE_MTP_VARLEN=0</code>(README.md:28)——这不是巧合,而是 varlen 调度的本质冲突。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🔒</span>为什么 varlen 调度破坏不变性</h3>
        <p>① <b>batch 组成可变</b>:每步 <code>total_q</code> 与每请求 <code>seqlen_q</code> 由<b>上一两轮的置信度 + 实测耗时</b>决定(mtp_varlen.hpp:150-266),同一请求在不同邻居/不同时刻会得到不同的验证行数——请求在 packed batch 中的行位置随之漂移;② <b>性能反馈是全局量</b>:吞吐搜索用的 slope/sampler 估时来自全 batch 的中位数,任何其他请求的加入都会改变本请求的调度结果;③ batch 内行数变化会改变 GEMM 归约次序,数值上即非 batch-invariant。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">⚖️</span>兼容的部分</h3>
        <p>注意 <code>DEEPINFER_USE_NEXTN_DECODE=0</code> 才是「关投机」;MTP 本身的<b>拒绝采样在分布上无损</b>,且 RNG 设计(draft 独立 seed 偏移 + <code>DRAFT_POS_HASH_MUL</code> 步长哈希,fused_sample.py:15, common.py:52)使每个验证行的随机流只依赖请求自身与步数——因此「关 varlen、开固定 MTP」仍可保持逐请求采样流稳定;但 DeepInfer 官方的确定性配方仍要求 MTP_VARLEN=0 并配合固定 <code>seq_seed</code>(NVIDIA only)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🧮</span>内核层面的开关传递</h3>
        <p><code>DEEPINFER_BATCH_INVARIANT</code> 会切换 deep_gemm / tile_kernels 到确定性算法(runtime_config.py:67-69),并被显式传入注意力内核——<b>包括 DFlash draft attention</b>(attn.py:1002 <code>batch_invariant=envs.DEEPINFER_BATCH_INVARIANT</code>)与主模型 attention(attn.py:666);userbuffer 在 BATCH_INVARIANT + 专家重排开启时禁止多次归约(userbuffer.py:79)。NPU 暂不支持(断言, runtime_config.py:61-63)。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">🧪</span>其它相关约束</h3>
        <p>PROMPT 引擎不做 draft(prefill 只更新 main KV,sampler.py:69-72;PROMPT 引擎走 <code>prefill_only</code> 模式只加载 main-cache 参数,dflash.py:112-114);profile run 会用 <code>nextn_pad_token_id</code> 占位并给每个序列分配独立 pool slot(model_runner.py:449-494);ZOS 抢占重算会把 MTP 计数整组复位以维持 schedule/process 配对断言(scheduler.hpp:1214-1219)。</p>
      </div>
    </div>

    <div class="note reveal">
      <b>一句话结论</b>:DSpark 的加速来自「让 batch 组成随置信度自适应」,而批次不变性要求「batch 组成不影响数值」——二者在 <code>ENABLE_MTP_VARLEN</code> 这一个开关上正面相撞。生产上按场景二选一:追求吞吐开 varlen,追求可复现关 varlen 并配 BATCH_INVARIANT + 固定 seq_seed。
    </div>
  </section>

  <!-- ================= 11. 总结 ================= -->
  <section id="s11">
    <h2 class="sec"><span class="num">11</span>总结与关键文件索引</h2>
    <p class="lede">DSpark = DFlash 起草 + varlen 并行验证 + 置信度驱动调度 + 双 CUDA Graph,四件套环环相扣,全部状态流转都在 GPU 上闭环。</p>

    <div class="grid c3">
      <div class="card reveal">
        <h3><span class="ico">🧩</span>起草侧</h3>
        <p><code>models/mtp/dflash.py</code>(模型与采样循环)、<code>models/decoder_layer.py:178</code>(draft 层)、<code>v4_modules/attn.py:883</code>(DFlashAttention)、<code>input_metadata/dflash.py</code>(fixed-stride 元数据)、<code>tilelang_ops/get_kv_index.py:209</code>(fused draft KV 索引)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">✅</span>验证与调度侧</h3>
        <p><code>layers/sampler.py</code>(验证主流程)、<code>tilelang_ops/sampler.py</code>(验证内核族)、<code>tilelang_ops/fused_sample.py</code>(拒绝采样)、<code>layers/mtp_info_pool.py</code>(跨 step 池)、<code>csrc/engine/mtp_varlen.hpp</code>(置信度调度器)、<code>csrc/engine/scheduler.hpp:872</code>(接受/回退记账)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">⚡</span>运行时侧</h3>
        <p><code>worker/dflash_cuda_graph_runner.py</code>(DFlash 图)、<code>worker/model_runner.py:531</code>(捕获与性能曲线)、<code>worker/worker.py:191</code>(ZOS GPU 修正)、<code>tilelang_ops/schedule_mtp_varlen.py</code> + <code>cuda/</code> 同名(置信度分配 kernel)、<code>tilelang_ops/compute_seqlens_k_zos.py</code>(K 长度修正)、<code>csrc/engine/zos.cpp:279</code>(元数据回写)。</p>
      </div>
    </div>

    <ul class="feat reveal">
      <li><b>分布无损</b>:接受/拒绝规则是标准 speculative rejection sampling,残差重采样保证输出分布与逐 token 解码一致(仅 DRAFT_PROB_PENALTY=5e-5 的数值护栏)。</li>
      <li><b>调度即优化</b>:置信度不仅用于决定「验不验」,还通过吞吐模型决定「这一步整体验多少」——CPU(非 ZOS)与 GPU(ZOS 修正)两条路径共享同一套 cumprod/rank 语义,bit-exact 对齐。</li>
      <li><b>回退零浪费</b>:KV 记账先乐观推进再按实际接受数回填;物理布局(swa/压缩环/YoCo 截断)统一以 <code>MAX_BACKTRACKING_TOKENS</code> 预留回退余量,被拒 draft 不留任何 KV 残留。</li>
      <li><b>图友好设计</b>:fixed-stride draft 布局 + 地址固定的接收缓冲 + 跨 step 的 pool 流水,使「广播→draft 层→采样→pool 写入」可以整体进 CUDA graph,与主图共享内存池。</li>
      <li><b>可观测</b>:<code>batch_confidence_error</code> 在线监控置信度头偏差;<code>num_generated_tokens / num_verified_tokens</code> 逐步统计接受率,可直观评估投机收益。</li>
    </ul>

    <div class="note good reveal">
      <b>阅读路线建议</b>:先读 <code>layers/sampler.py</code> 的类 docstring(sampler.py:59-94,官方对整个 decode-MTP 流程的最完整叙述),再对照本文图 1 逐段进入 <code>dflash.py</code> 与 <code>mtp_varlen.hpp</code>;调试时打开 <code>DEEPINFER_DFLASH_ENFORCE_EAGER</code> 并关注 <code>batch_confidence_error</code> 指标。
    </div>
  </section>

  <div class="pgnav">
    <span>DeepInfer 代码分析系列 · 由 ZCode 生成于 2026-11 · 本篇所有 file:line 引用均来自仓库当前代码</span>
    <span><a href="/docs/inference-engines/deepinfer/">← 返回系列总览</a></span>
  </div>
<script>
// 滚动显现动画
const io=new IntersectionObserver(es=>{es.forEach(e=>{if(e.isIntersecting){e.target.classList.add('on');io.unobserve(e.target)}})},{threshold:.12});
document.querySelectorAll('.reveal').forEach(el=>io.observe(el));
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>SWA 有界重放(YOCO Prefill 截断)</title><link>https://hccl.club/docs/inference-engines/deepinfer/04-swa-replay/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/04-swa-replay/</guid><description><![CDATA[<div class="fwdoc">
<style>
.fwdoc{--bg:#0b1020; --bg2:#0f1729; --panel:#141d33; --panel2:#1a2440;
  --border:#263352; --text:#dbe4f5; --muted:#8ea0c2;
  --accent:#4f8cff; --accent2:#22d3ee; --good:#34d399; --warn:#fbbf24; --bad:#f87171; --purple:#a78bfa;
  --code-bg:#0d1424; --radius:14px;
  --serif:"Noto Serif SC","Songti SC",serif;}
.fwdoc *{box-sizing:border-box;margin:0;padding:0}
.fwdoc{background:linear-gradient(160deg,var(--bg) 0%,var(--bg2) 60%,#0a0f1e 100%);color:var(--text);
  font-family:"PingFang SC","Microsoft YaHei","Segoe UI",system-ui,sans-serif;line-height:1.75;}
.fwdoc{flex:1;min-width:0;padding:36px 48px 80px}
@media(max-width:960px){.fwdoc{padding:24px 18px 60px}}
.fwdoc .hero{position:relative;border-radius:var(--radius);overflow:hidden;padding:46px 44px;margin-bottom:34px;
  background:radial-gradient(1200px 400px at 15% -20%,rgba(79,140,255,.28),transparent 60%),
             radial-gradient(900px 380px at 95% 0%,rgba(167,139,250,.20),transparent 55%),
             linear-gradient(135deg,#16213e,#101a30);border:1px solid var(--border)}
.fwdoc .hero .crumb{font-size:12px;color:var(--accent2);letter-spacing:1px;margin-bottom:12px}
.fwdoc .hero h1{font-size:34px;color:#fff;font-weight:800;letter-spacing:.5px;margin-bottom:10px}
.fwdoc .hero p.desc{color:var(--muted);max-width:760px;font-size:15px}
.fwdoc .hero .tags{margin-top:18px;display:flex;gap:10px;flex-wrap:wrap}
.fwdoc .hero .tag{font-size:12px;padding:4px 14px;border-radius:999px;border:1px solid var(--border);
  background:rgba(79,140,255,.10);color:var(--accent2)}
.fwdoc .tag.good{border-color:rgba(52,211,153,.4);color:var(--good);background:rgba(52,211,153,.08)}
.fwdoc .tag.warn{border-color:rgba(251,191,36,.4);color:var(--warn);background:rgba(251,191,36,.08)}
.fwdoc section{margin-bottom:44px;scroll-margin-top:20px}
.fwdoc h2.sec{display:flex;align-items:center;gap:12px;font-size:23px;color:#fff;margin-bottom:6px;padding-bottom:10px;border-bottom:1px solid var(--border)}
.fwdoc h2.sec .num{display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:10px;flex-shrink:0;
  background:linear-gradient(135deg,var(--accent),var(--purple));color:#fff;font-size:15px;font-weight:800}
.fwdoc .lede{color:var(--muted);font-size:14px;margin-bottom:20px}
.fwdoc .grid{display:grid;gap:18px}
.fwdoc .grid.c2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}
.fwdoc .grid.c3{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}
.fwdoc .card{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:var(--radius);padding:22px 24px;transition:transform .3s,border-color .3s,box-shadow .3s}
.fwdoc .card:hover{transform:translateY(-3px);border-color:rgba(79,140,255,.55);box-shadow:0 12px 34px -14px rgba(79,140,255,.35)}
.fwdoc .card h3{font-size:16.5px;color:#fff;margin-bottom:8px;display:flex;align-items:center;gap:9px}
.fwdoc .card h3 .ico{width:26px;height:26px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;
  background:rgba(79,140,255,.16);font-size:14px;flex-shrink:0}
.fwdoc .card p{font-size:13.5px;color:var(--muted)}
.fwdoc .card p code,.fwdoc .inline-code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1.5px 7px;border-radius:6px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px}
.fwdoc ul.feat{list-style:none}
.fwdoc ul.feat li{padding:9px 0 9px 30px;position:relative;font-size:14px;color:var(--text);border-bottom:1px dashed rgba(38,51,82,.6)}
.fwdoc ul.feat li:last-child{border-bottom:none}
.fwdoc ul.feat li::before{content:"▸";position:absolute;left:8px;color:var(--accent);font-weight:700;animation:fw-blink 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
@keyframes fw-blink{0%,100%{opacity:.35}50%{opacity:1}}
.fwdoc pre.code{background:var(--code-bg);border:1px solid var(--border);border-radius:12px;padding:18px 20px;
  overflow-x:auto;font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px;line-height:1.65;margin:14px 0;position:relative}
.fwdoc pre.code::before{content:"● ● ●";display:block;color:#3a4a70;font-size:10px;letter-spacing:3px;margin-bottom:10px}
.fwdoc pre.code .k{color:#c792ea}
.fwdoc pre.code .s{color:#89ddff}
.fwdoc pre.code .c{color:#5d7294;font-style:italic}
.fwdoc pre.code .f{color:#82aaff}
.fwdoc pre.code .n{color:#f78c6c}
.fwdoc pre.code .h{color:#ffcb6b}
.fwdoc .filepath{font-family:"JetBrains Mono",Consolas,monospace;font-size:11.5px;color:var(--accent2);
  background:rgba(34,211,238,.08);border:1px solid rgba(34,211,238,.25);border-radius:6px;padding:2px 10px;display:inline-block;margin-bottom:4px}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border)}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px}
.fwdoc table.tbl td{padding:10px 14px;border-top:1px solid var(--border);color:var(--text);vertical-align:top}
.fwdoc table.tbl tr{transition:background .2s}
.fwdoc table.tbl tr:nth-child(even) td{background:rgba(20,29,51,.5)}
.fwdoc table.tbl tr:hover td{background:rgba(79,140,255,.10)}
.fwdoc table.tbl td code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;font-family:Consolas,monospace;font-size:12px}
.fwdoc .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px}
.fwdoc .badge.merged{background:rgba(52,211,153,.15);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.open{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.closed{background:rgba(248,113,113,.13);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.nccl{background:rgba(251,191,36,.12);color:var(--warn);border:1px solid rgba(251,191,36,.4)}
.fwdoc .badge.hccl{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .badge.deepep{background:rgba(34,211,238,.12);color:var(--accent2);border:1px solid rgba(34,211,238,.4)}
.fwdoc .reveal{opacity:0;transform:translateY(26px);transition:opacity .7s cubic-bezier(.2,.7,.3,1),transform .7s cubic-bezier(.2,.7,.3,1)}
.fwdoc .reveal.on{opacity:1;transform:none}
.fwdoc .reveal.d1{transition-delay:.12s}
.fwdoc .reveal.d2{transition-delay:.24s}
.fwdoc .reveal.d3{transition-delay:.36s}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:20px;margin:18px 0;position:relative;overflow:hidden}
.fwdoc .figure .cap{text-align:center;font-size:12.5px;color:var(--muted);margin-top:10px}
.fwdoc .figure svg{width:100%;height:auto;display:block}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-flow 1.2s linear infinite}
@keyframes fw-flow{to{stroke-dashoffset:-14}}
.fwdoc .pulse{animation:fw-pulse 2s ease-in-out infinite;transform-origin:center}
@keyframes fw-pulse{0%,100%{opacity:.45;transform:scale(1)}50%{opacity:1;transform:scale(1.06)}}
.fwdoc .node-gpu{fill:#16233f;stroke:#4f8cff;stroke-width:1.6;rx:10}
.fwdoc .node-gpu-title{fill:#dbe4f5;font-size:13px;font-weight:700}
.fwdoc .token-dot{fill:#22d3ee}
.fwdoc .barrow{filter:drop-shadow(0 0 6px rgba(34,211,238,.7))}
.fwdoc .timeline{position:relative;padding-left:34px}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .tl-item{position:relative;margin-bottom:20px}
.fwdoc .tl-item::before{content:"";position:absolute;left:-30px;top:7px;width:12px;height:12px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.18);animation:fw-pulse 2.4s infinite}
.fwdoc .tl-item .tl-date{font-size:11.5px;color:var(--accent2);letter-spacing:.5px}
.fwdoc .tl-item .tl-body{font-size:13.5px;color:var(--text);margin-top:3px}
.fwdoc .note{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13px;color:var(--text);margin:16px 0}
.fwdoc .note.warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .note.good{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .note b{color:#fff}
.fwdoc .pgnav{margin-top:60px;padding-top:20px;border-top:1px solid var(--border);color:#5a6b92;font-size:12px;
  display:flex;justify-content:space-between;flex-wrap:wrap;gap:10px}
.fwdoc .pgnav a{color:var(--accent2);text-decoration:none}
.fwdoc .figure svg .pulse{transform-box:fill-box;transform-origin:center}
.fwdoc .tokflow{animation:fw-tokflow 3.4s linear infinite}
@keyframes fw-tokflow{0%{transform:translateY(-10px);opacity:0}12%{opacity:1}82%{opacity:1}100%{transform:translateY(152px);opacity:0}}
.fwdoc .strip-slide{animation:fw-stripslide 7s ease-in-out infinite alternate}
@keyframes fw-stripslide{from{transform:translateX(0)}to{transform:translateX(-288px)}}
.fwdoc .growbar{transform-box:fill-box;transform-origin:left center;animation:fw-growbar 2.8s ease-in-out infinite alternate}
@keyframes fw-growbar{from{transform:scaleX(.08)}to{transform:scaleX(1)}}
.fwdoc .ringwrite{transform-box:fill-box;transform-origin:center;animation:spin 9s linear infinite}
.fwdoc .winpulse{animation:fw-winpulse 2.4s ease-in-out infinite}
@keyframes fw-winpulse{0%,100%{opacity:.45}50%{opacity:1}}
.fwdoc .rewind{animation:fw-rewind 5s ease-in-out infinite}
@keyframes fw-rewind{0%,18%{transform:translateX(0)}40%,68%{transform:translateX(132px)}88%,100%{transform:translateX(0)}}
.fwdoc .marchdash{stroke-dasharray:5 5;animation:fw-flow 1.1s linear infinite}
.fwdoc .fadeinout{animation:fw-winpulse 3s ease-in-out infinite}
.fwdoc .ckpt{animation:fw-pulse 2.6s ease-in-out infinite;transform-box:fill-box;transform-origin:center}
/* ===== 导入面板附加样式 ===== */
.fwdoc{border-radius:14px;margin:18px 0}
.fwdoc table.tbl{display:block;overflow-x:auto;max-width:100%}
@media (prefers-reduced-motion:reduce){
.fwdoc *,.fwdoc *::before,.fwdoc *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
.fwdoc .reveal{opacity:1!important;transform:none!important}
}

</style>

<!-- ================================================================ 1 -->
  <section>
    <h2 class="sec"><span class="num">1</span>概述:有界重放解决什么问题</h2>
    <p class="lede">README 对这个特性的描述只有一句话,但它同时压着「计算量、KV cache 布局、投机解码回退」三座大山。</p>
    <div class="note">
      <b>README.md:25</b> — “<b>Decoder SWA bounded replay:</b> reduce decoder prefill work by replaying only a bounded suffix. Set <code>DEEPINFER_YOCO_PREFILL_TRUNCATION_MODE=compact</code> and <code>DEEPINFER_YOCO_PREFILL_KEEP_TOKENS=140</code> for the default V4.1 settings; the retained suffix must cover the SWA window plus the maximum backtracking length.”
    </div>
    <div class="grid c3">
      <div class="card reveal">
        <h3><span class="ico">✂</span>问题:consumer 层的 prefill 冗余</h3>
        <p>YOCO 模型把 <code>[n_prefill_layer, n_layer)</code> 的层做成 SWA consumer(deepinfer/model_executor/models/v4_modules/yoco.py:19-21)。这些层的 query 只看最近 <code>W</code> 个 token,可 prefill 仍按整条 prompt 逐行计算 Q/KV/attention/MLP——对 32K 的 prompt,绝大多数行的输出既不参与采样,也不会进入后续 decode 的可见域。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">▶</span>方案:只重放有界后缀</h3>
        <p>把 prefill 的 query 集合收缩为序列尾部 <code>KEEP_TOKENS</code> 个 token 的「矩形」<code>[N-keep, N)</code>,SWA 可见域取「原始滑窗 ∩ 矩形」的交集(C++ 中共用同一个 <code>yoco_swa_visibility</code>,deepinfer/model_executor/input_metadata/yoco.py:6)。前缀部分对 consumer 层直接跳过,这就是「有界重放」。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">⚙</span>约束:窗口 + 回退余量</h3>
        <p>矩形必须 <code>≥ window_size + MAX_BACKTRACKING_TOKENS</code>:decode 期 DSpark 验证失败最多回退 B 个 token,回退后的位置仍要能在 SWA ring 里凑满 W 个有效 key。C++ 与 Python 双重断言(csrc/engine/input_metadata/prepare_tensor_input_v4.cpp:355-357、deepinfer/worker/model_runner.py:110-113)。</p>
      </div>
    </div>
    <ul class="feat">
      <li><b>两个环境变量控制一切</b>:模式三态 <code>off / mask / compact</code> + 保留长度,定义在 deepinfer/environ.py:195-201;默认关闭,启用必须显式设 <code>KEEP_TOKENS</code>。</li>
      <li><b>数值无损</b>:mask 与 compact 的 SWA 可见域公式完全相同,前者全量算、后者真截断,可逐位对齐(examples/yoco/yoco_equiv.py 提供 L1/L2 双层等价性验证)。</li>
      <li><b>不止省 attention</b>:compact 模式下被截断行连同 MLP/MoE、router、hyper-connection 一起跳过,FlopsEstimator 按行数感知这一差异(csrc/engine/flops_estimator.hpp:259-277)。</li>
      <li><b>但压缩 KV 仍要全量</b>:consumer 层的 main/index(压缩)KV 必须覆盖完整上下文,由 full hidden 走 <code>_store_yoco_full_kv</code> 补写(deepinfer/model_executor/models/v4_modules/attn.py:672-721)。</li>
    </ul>
  </section>

  <!-- ================================================================ 2 -->
  <section>
    <h2 class="sec"><span class="num">2</span>背景:YOCO 解码器的 producer / consumer 层分裂</h2>
    <p class="lede">V4.1-Flash 不是「所有层都做全局注意力」。前 <code>n_prefill_layer</code> 层是 producer,之后的层是 SWA consumer——这是截断特性存在的结构前提。</p>
    <div class="figure">
      <svg viewBox="0 0 960 480" xmlns="http://www.w3.org/2000/svg" font-family="'PingFang SC','Microsoft YaHei',sans-serif">
        <defs>
          <marker id="ar" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#4f8cff"/>
          </marker>
          <linearGradient id="gProd" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stop-color="#1b2a4a"/><stop offset="1" stop-color="#141d33"/>
          </linearGradient>
          <linearGradient id="gCons" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stop-color="#12313a"/><stop offset="1" stop-color="#0e2230"/>
          </linearGradient>
        </defs>
        <!-- 左侧 token 流 -->
        <text x="40" y="34" fill="#8ea0c2" font-size="12">输入 token(varlen)</text>
        <g>
          <circle class="tokflow" cx="52" cy="52" r="5" fill="#22d3ee" style="animation-delay:0s"/>
          <circle class="tokflow" cx="78" cy="52" r="5" fill="#22d3ee" style="animation-delay:.4s"/>
          <circle class="tokflow" cx="104" cy="52" r="5" fill="#22d3ee" style="animation-delay:.8s"/>
          <circle class="tokflow" cx="130" cy="52" r="5" fill="#22d3ee" style="animation-delay:1.2s"/>
          <circle class="tokflow" cx="156" cy="52" r="5" fill="#22d3ee" style="animation-delay:1.6s"/>
          <circle class="tokflow" cx="182" cy="52" r="5" fill="#22d3ee" style="animation-delay:2s"/>
          <circle class="tokflow" cx="208" cy="52" r="5" fill="#22d3ee" style="animation-delay:2.4s"/>
          <circle class="tokflow" cx="234" cy="52" r="5" fill="#22d3ee" style="animation-delay:2.8s"/>
        </g>
        <path class="flowline" d="M150 70 L150 108" stroke="#4f8cff" stroke-width="2" fill="none" marker-end="url(#ar)"/>

        <!-- producer 层 -->
        <g>
          <rect x="210" y="112" width="500" height="52" rx="10" fill="url(#gProd)" stroke="#4f8cff" stroke-width="1.6"/>
          <text x="238" y="144" fill="#dbe4f5" font-size="14" font-weight="700">producer 层 0 … n_prefill_layer-1</text>
          <text x="560" y="132" fill="#8ea0c2" font-size="11">全局注意力 · 完整 KV 写入</text>
          <!-- 全注意力扇形线 -->
          <g stroke="#4f8cff" stroke-width="1" opacity=".65">
            <line x1="460" y1="118" x2="300" y2="158"/><line x1="460" y1="118" x2="360" y2="160"/>
            <line x1="460" y1="118" x2="420" y2="162"/><line x1="460" y1="118" x2="480" y2="162"/>
            <line x1="460" y1="118" x2="540" y2="160"/><line x1="460" y1="118" x2="600" y2="158"/>
          </g>
        </g>
        <path class="flowline" d="M460 164 L460 196" stroke="#4f8cff" stroke-width="2" fill="none" marker-end="url(#ar)"/>

        <!-- 边界层 -->
        <g>
          <rect x="210" y="200" width="500" height="56" rx="10" fill="#1c2138" stroke="#fbbf24" stroke-width="2"/>
          <text x="238" y="224" fill="#ffcb6b" font-size="14" font-weight="700">边界层 i = n_prefill_layer(yoco_boundary_layer_idx)</text>
          <text x="238" y="244" fill="#8ea0c2" font-size="11">compact: get_consumer_view() 切 metadata;attn_norm 捕获 consumer_full_hidden / shared_hidden</text>
          <rect class="winpulse" x="712" y="178" width="14" height="100" rx="4" fill="#fbbf24" opacity=".8"/>
          <text x="736" y="232" fill="#fbbf24" font-size="11">截断边界</text>
        </g>
        <path class="flowline" d="M460 256 L460 288" stroke="#22d3ee" stroke-width="2" fill="none" marker-end="url(#ar)"/>

        <!-- consumer 层 -->
        <g>
          <rect x="210" y="292" width="500" height="52" rx="10" fill="url(#gCons)" stroke="#22d3ee" stroke-width="1.6"/>
          <text x="238" y="318" fill="#dbe4f5" font-size="14" font-weight="700">consumer 层 n_prefill_layer … n_layer-1</text>
          <text x="560" y="312" fill="#8ea0c2" font-size="11">SWA(窗口 W) · 压缩 KV</text>
          <g stroke="#22d3ee" stroke-width="1" opacity=".8">
            <line x1="440" y1="298" x2="396" y2="336"/><line x1="460" y1="298" x2="440" y2="338"/>
            <line x1="480" y1="298" x2="484" y2="338"/><line x1="500" y1="298" x2="528" y2="336"/>
          </g>
        </g>
        <g>
          <rect x="210" y="352" width="500" height="40" rx="10" fill="url(#gCons)" stroke="#22d3ee" stroke-width="1.2" opacity=".8"/>
          <text x="238" y="377" fill="#8ea0c2" font-size="12">…(更多 consumer 层;SWA ring / share-kv 共享)</text>
        </g>
        <path class="flowline" d="M460 392 L460 424" stroke="#a78bfa" stroke-width="2" fill="none" marker-end="url(#ar)"/>
        <text x="420" y="446" fill="#a78bfa" font-size="13" font-weight="700">输出 / 采样(每 chunk 仅最后一行参与采样)</text>

        <!-- 右侧注释:shared hidden -->
        <g>
          <rect x="752" y="292" width="188" height="100" rx="10" fill="#141d33" stroke="#a78bfa" stroke-width="1.4"/>
          <text x="768" y="316" fill="#a78bfa" font-size="12" font-weight="700">shared_hidden</text>
          <text x="768" y="336" fill="#8ea0c2" font-size="10.5">首个 consumer 层的 attn-norm</text>
          <text x="768" y="352" fill="#8ea0c2" font-size="10.5">bf16 hidden,跨层持有;</text>
          <text x="768" y="368" fill="#8ea0c2" font-size="10.5">SWA kv_swa 与压缩 KV 由它投影</text>
          <path class="flowline" d="M752 342 C716 342 716 226 712 226" stroke="#a78bfa" stroke-width="1.6" fill="none"/>
        </g>
        <!-- 左下注释 -->
        <g>
          <rect x="40" y="292" width="150" height="100" rx="10" fill="#141d33" stroke="#34d399" stroke-width="1.4"/>
          <text x="56" y="316" fill="#34d399" font-size="12" font-weight="700">截断的意义</text>
          <text x="56" y="336" fill="#8ea0c2" font-size="10.5">consumer 行数从 N 收缩到</text>
          <text x="56" y="352" fill="#8ea0c2" font-size="10.5">keep_len(≥W+B);W 之外的</text>
          <text x="56" y="368" fill="#8ea0c2" font-size="10.5">SWA 行既不被读也不被写</text>
        </g>
      </svg>
      <div class="cap">图 2-1 · YOCO 层分裂与截断边界:producer 全注意力、consumer 滑窗;边界层同时产出 compact 视图与 full hidden(token 圆点为 CSS 逐帧下流动画)</div>
    </div>
    <p>判定逻辑本身只有两行:<code>yoco_enabled(cfg)</code> 要求 <code>n_prefill_layer &lt; num_hidden_layers</code>,<code>is_yoco_consumer_layer</code> 则圈定 <code>[n_prefill_layer, n_layer)</code>(deepinfer/model_executor/models/v4_modules/yoco.py:14-21)。模型元数据在构造期就锁定这一切:</p>
    <pre class="code"><span class="filepath">deepinfer/model_executor/model_metadata_utils.py:88-92</span>
<span class="k">self</span>.yoco_enabled = n_prefill_layer &lt; <span class="k">self</span>.n_layer
<span class="s">"""模型是否有 YoCo consumer 层。有 YoCo consumer 层才能开截断。"""</span>
<span class="k">if</span> envs.DEEPINFER_YOCO_PREFILL_TRUNCATION_MODE != <span class="s">"off"</span>:
    <span class="k">assert</span> <span class="k">self</span>.yoco_enabled <span class="k">and</span> n_prefill_layer &gt; <span class="n">0</span>
    <span class="k">assert</span> envs.DEEPINFER_YOCO_PREFILL_KEEP_TOKENS &gt; <span class="n">0</span>  <span class="c"># 开 yoco 截断时,如果 keep token=0,c++ 里的判断会有问题</span></pre>
    <p>consumer 层有三个与截断强相关的结构事实,后面章节都会反复出现:</p>
    <ul class="feat">
      <li><b>SWA 的 KV 来自 shared hidden</b>:开启 <code>yoco_swa_share_hidden</code>(默认 True)时,consumer 层的 <code>kv_swa</code> 不是由本层 hidden 投影,而是由首个 consumer 层捕获的 shared hidden 投影(deepinfer/model_executor/models/v4_modules/attn.py:248-249、289-290、386-400)。</li>
      <li><b>hyper-connection 状态是逐 token 的</b>:HC 残差主干与混合系数存放在 <code>HCLazyPostData</code>(deepinfer/model_executor/models/v4_modules/hc_lazy.py:17-27),截断边界必须对这些 per-token 张量做 gather(deepinfer/model_executor/models/v4_modules/yoco.py:79-90)。hc.py / hc_blocks.py 是 mHC 运行时与参数容器,本身不感知截断。</li>
      <li><b>engram 被排除在 consumer 半区外</b>:compact 模式断言 engram 层全部位于 prefill 半区(deepinfer/model_executor/models/deepseek.py:136-138),DFlash target 层也必须同侧(deepseek.py:129-135)。</li>
    </ul>
  </section>

  <!-- ================================================================ 3 -->
  <section>
    <h2 class="sec"><span class="num">3</span>三种截断模式:off / mask / compact</h2>
    <p class="lede">一个环境变量三态切换,决定「不动 query」「只收窄可见域」「真删行」三种行为;两种截断模式的可见域公式完全一致,因此可以逐位对齐。</p>
    <pre class="code"><span class="filepath">deepinfer/environ.py:194-201</span>
<span class="c"># -- YoCo --</span>
DEEPINFER_YOCO_PREFILL_TRUNCATION_MODE = EnvVar.choice(default=<span class="s">"off"</span>, choices=(<span class="s">"off"</span>, <span class="s">"mask"</span>, <span class="s">"compact"</span>))
<span class="s">"""YoCo consumer prefill 截断模式:off 表示关闭;mask 保留全部 query,仅收窄 SWA
可见域;compact 真正移除截断区 query,以减少 consumer 层计算。"""</span>
DEEPINFER_YOCO_PREFILL_KEEP_TOKENS = EnvVar.int()
<span class="s">"""YoCo consumer prefill 截断开启时保留的末尾 query token 数。mask 与 compact 的
SWA 可见域均为原始滑窗和末尾 KEEP_TOKENS 矩形的交集。必须满足 KEEP_TOKENS &gt;=
window_size + DEEPINFER_MAX_BACKTRACKING_TOKENS;默认 0,启用截断时必须显式设置。"""</span></pre>
    <p>C++ 侧有完全对应的枚举与参数包,由 <code>YOCO_PREFILL_TRUNCATION_MODES</code> 字典完成字符串到枚举的映射(deepinfer/model_executor/model_metadata_utils.py:21-26),再在每次构造输入时塞进 <code>PrepareArgs</code>(model_metadata_utils.py:173-178):</p>
    <pre class="code"><span class="filepath">csrc/engine/input_metadata/prepare_tensor_input.hpp:13-17, 37-41</span>
<span class="k">enum class</span> YocoPrefillTruncationMode : int32_t {
    OFF = <span class="n">0</span>,
    MASK = <span class="n">1</span>,
    COMPACT = <span class="n">2</span>,
};
<span class="c">// v4-only</span>
int32_t window_size = <span class="n">0</span>;
int32_t swa_block_size = <span class="n">0</span>;
YocoPrefillTruncationMode yoco_prefill_truncation_mode = YocoPrefillTruncationMode::OFF;
int32_t yoco_prefill_keep_tokens = <span class="n">0</span>;
int32_t max_backtracking_tokens = <span class="n">0</span>; <span class="c">// 用于 keep_tokens &gt;= window_size + backtracking 约束检查</span></pre>
    <table class="tbl">
      <tr><th style="width:15%">维度</th><th>off(默认)</th><th>mask</th><th>compact</th></tr>
      <tr><td><b>query 行数</b></td><td>full(全部 N 行)</td><td>full(全部行照常计算)</td><td><b>compact</b>:每 chunk 只保留 <code>keep_len = q_len - clip_prefix</code> 行(csrc/.../prepare_tensor_input_v4.cpp:222-229)</td></tr>
      <tr><td><b>SWA 可见域</b></td><td>滑窗 <code>[pos-W+1, pos]</code> ∩ valid_start</td><td>滑窗 ∩ 矩形 <code>[N-keep, N)</code>(<code>yoco_mask_swa_index_pivots</code>,full 布局)</td><td>同 mask:滑窗 ∩ 矩形(共用 <code>yoco_swa_visibility</code>,cpp:149-168),写成 <code>yoco_consumer_swa_index_pivots</code>(compact 布局)</td></tr>
      <tr><td><b>consumer 层计算量</b></td><td>全量</td><td><b>不省</b>——“mask returns degenerate logp / 仅用于数值对齐”(examples/benchmark.py:47-49)</td><td><b>真省</b>:截断区的 attention + Q/KV 投影 + MLP/MoE + HC + topk 全部跳过</td></tr>
      <tr><td><b>SWA ring 写入</b></td><td>chunk 尾部 <code>swa_block_size</code> 个 token 写 ring(cpp:98-108)</td><td>复用 full 版 <code>slot_mapping_store_swa</code>,同 off</td><td>矩形外的占位 token 显式置 <code>-1</code> 不写 ring(cpp:266-271)</td></tr>
      <tr><td><b>main/index(压缩)KV</b></td><td>全量写入</td><td>全量写入</td><td><b>仍全量</b>:由 <code>consumer_full_hidden</code> 走 <code>_store_yoco_full_kv</code> 补写(attn.py:672-721)</td></tr>
      <tr><td><b>输出布局</b></td><td>full</td><td>full</td><td>compact:采样位置按 keep_len 寻址(csrc/engine/prepare_sample.cpp:168-179)</td></tr>
      <tr><td><b>prompt_logprobs</b></td><td>支持</td><td>强制关闭(deepinfer/engine/llm_engine.py:529-536)</td><td>强制关闭(截断行无法计算 logprob,prepare_sample.cpp:177-179)</td></tr>
      <tr><td><b>典型用途</b></td><td>非 YOCO 模型 / 基线</td><td>数值对齐、排查 compact 正确性(examples/yoco/README.md L1/L2)</td><td>生产提速(V4.1 默认)</td></tr>
    </table>
    <div class="note">
      <b>为什么需要 mask 模式?</b>它和 compact 的可见域公式一模一样,却一行都不省。价值在于「同一套语义跑两遍」:mask 全量计算但可见域收窄,compact 真截断——若两者输出逐位一致,就证明 compact 的 gather / 布局切换没有引入误差。examples/yoco/yoco_equiv.py 正是围绕这一点构建的(其 <code>_reference_visible</code> 给出解析参考:可见域 = 滑窗 ∩ 矩形,yoco_equiv.py:116-119)。
    </div>
    <p>Python 侧两种模式的宿主字段互斥地由 C++ 产出,判定也收敛为「字段存在性」:<code>yoco_compaction_enabled</code> 看 <code>yoco_consumer_query_indices</code>,<code>yoco_mask_enabled</code> 看 <code>yoco_mask_swa_index_pivots</code>(deepinfer/model_executor/input_metadata/yoco.py:66-79)。mask 视图的切换只是一次浅拷贝 + 换 pivots 槽位:</p>
    <pre class="code"><span class="filepath">deepinfer/model_executor/input_metadata/yoco.py:86-92</span>
<span class="k">def</span> <span class="f">get_mask_view</span>(<span class="k">self</span>: InputMetadataV4) -&gt; InputMetadataV4:
    <span class="s">"""yoco decoder 截断只改 mask,不做真截断。"""</span>
    <span class="k">assert</span> <span class="k">self</span>.yoco_mask_enabled
    view = copy.copy(<span class="k">self</span>)
    view.kv_swa_full_index_pivots = <span class="k">self</span>.yoco_mask_swa_index_pivots
    view.kv_swa_full_index = <span class="k">None</span>
    <span class="k">return</span> view</pre>
  </section>

  <!-- ================================================================ 4 -->
  <section>
    <h2 class="sec"><span class="num">4</span>有界重放主图:长 prompt → 尾部有界后缀</h2>
    <p class="lede">下图是整条特性的心脏:一条长 prompt,只有尾部 <code>KEEP_TOKENS</code> 落进重放矩形;矩形内部再叠加一个宽度为 W 的滑动窗口随生成推进而滑动(窗口内可见、窗外丢弃)。</p>
    <div class="figure">
      <svg viewBox="0 0 980 560" xmlns="http://www.w3.org/2000/svg" font-family="'PingFang SC','Microsoft YaHei',sans-serif">
        <defs>
          <linearGradient id="keepg" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stop-color="#0d5945"/><stop offset="1" stop-color="#0f766e"/>
          </linearGradient>
          <clipPath id="winclip">
            <rect x="600" y="330" width="192" height="56" rx="6"/>
          </clipPath>
          <marker id="ar4" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#4f8cff"/>
          </marker>
        </defs>

        <!-- 顶:full prompt 条 -->
        <text x="40" y="40" fill="#dbe4f5" font-size="14" font-weight="700">① 长 prompt 进入 consumer 层(full 布局,N 个 token)</text>
        <g>
          <!-- 28 个格子:前 21 个灰(截断区),后 7 个绿(矩形) -->
          <g>
            <rect x="40" y="58" width="588" height="46" rx="4" fill="#141d33" stroke="#263352"/>
            <text x="60" y="87" fill="#5a6b92" font-size="13">截断区:0 … N-KEEP_TOKENS-1(consumer 层跳过,clip_prefix 截掉)</text>
            <g stroke="#3a4a70" stroke-width="1" opacity=".8">
              <line x1="120" y1="60" x2="104" y2="102"/><line x1="180" y1="60" x2="164" y2="102"/>
              <line x1="240" y1="60" x2="224" y2="102"/><line x1="300" y1="60" x2="284" y2="102"/>
              <line x1="360" y1="60" x2="344" y2="102"/><line x1="420" y1="60" x2="404" y2="102"/>
              <line x1="480" y1="60" x2="464" y2="102"/><line x1="540" y1="60" x2="524" y2="102"/>
              <line x1="600" y1="60" x2="584" y2="102"/>
            </g>
          </g>
          <rect x="636" y="58" width="196" height="46" rx="4" fill="url(#keepg)" stroke="#34d399" stroke-width="2"/>
          <text x="648" y="87" fill="#a7f3d0" font-size="13" font-weight="700">保留矩形 [N-140, N)</text>
          <!-- 矩形左边界脉冲线 -->
          <line class="winpulse" x1="636" y1="46" x2="636" y2="118" stroke="#34d399" stroke-width="3"/>
          <text x="600" y="36" fill="#34d399" font-size="12" font-weight="700">rect_lo = N - KEEP_TOKENS</text>
          <text x="700" y="124" fill="#34d399" font-size="11">KEEP_TOKENS = 140 ≥ W + B</text>
          <!-- keep 弧括 -->
          <path d="M836 62 q14 18 0 38" stroke="#34d399" stroke-width="1.5" fill="none"/>
          <text x="852" y="87" fill="#34d399" font-size="11">140</text>
        </g>

        <path class="flowline" d="M700 128 L700 176" stroke="#34d399" stroke-width="2.2" fill="none" marker-end="url(#ar4)"/>
        <path class="flowline" d="M320 128 L320 176" stroke="#f87171" stroke-width="1.6" fill="none" stroke-dasharray="3 6" opacity=".55"/>
        <text x="236" y="160" fill="#f87171" font-size="11" opacity=".8">前缀不进入 consumer 计算</text>

        <!-- 中:compact 布局 -->
        <text x="40" y="196" fill="#dbe4f5" font-size="14" font-weight="700">② compact 布局:只保留矩形内的 query 行(占位 token 除外)</text>
        <g>
          <rect x="40" y="212" width="588" height="40" rx="4" fill="#0d1424" stroke="#263352" stroke-dasharray="4 4"/>
          <text x="60" y="238" fill="#5a6b92" font-size="12">clip_prefix = clamp(N - KEEP - q_start, 0, q_len-1) → 这些行被移除</text>
        </g>
        <g>
          <!-- 保留区放大条:14 格 -->
          <g>
            <rect x="636" y="206" width="196" height="52" rx="4" fill="url(#keepg)" stroke="#34d399" stroke-width="1.6"/>
            <g fill="#34d399" opacity=".85">
              <rect x="642" y="212" width="12" height="40" rx="2"/><rect x="656" y="212" width="12" height="40" rx="2"/>
              <rect x="670" y="212" width="12" height="40" rx="2"/><rect x="684" y="212" width="12" height="40" rx="2"/>
              <rect x="698" y="212" width="12" height="40" rx="2"/><rect x="712" y="212" width="12" height="40" rx="2"/>
              <rect x="726" y="212" width="12" height="40" rx="2"/><rect x="740" y="212" width="12" height="40" rx="2"/>
              <rect x="754" y="212" width="12" height="40" rx="2"/><rect x="768" y="212" width="12" height="40" rx="2"/>
              <rect x="782" y="212" width="12" height="40" rx="2"/><rect x="796" y="212" width="12" height="40" rx="2"/>
              <rect x="810" y="212" width="12" height="40" rx="2"/>
            </g>
            <text x="646" y="274" fill="#8ea0c2" font-size="11">keep_len 行:Q/KV/Attn/MLP/HC 逐行计算</text>
          </g>
        </g>

        <path class="flowline" d="M700 282 L700 318" stroke="#22d3ee" stroke-width="2.2" fill="none" marker-end="url(#ar4)"/>

        <!-- 下:滑动窗口动画 -->
        <text x="40" y="310" fill="#dbe4f5" font-size="14" font-weight="700">③ 窗口滑动:SWA 可见域 = 滑窗 [pos-W+1, pos] ∩ 矩形(W = 128)</text>
        <!-- 窗口外基底(暗) -->
        <g>
          <rect x="360" y="330" width="560" height="56" rx="6" fill="#101a30" stroke="#263352"/>
          <g fill="#22345a">
            <rect x="372" y="338" width="16" height="40" rx="2"/><rect x="392" y="338" width="16" height="40" rx="2"/>
            <rect x="412" y="338" width="16" height="40" rx="2"/><rect x="432" y="338" width="16" height="40" rx="2"/>
            <rect x="452" y="338" width="16" height="40" rx="2"/><rect x="472" y="338" width="16" height="40" rx="2"/>
            <rect x="492" y="338" width="16" height="40" rx="2"/><rect x="512" y="338" width="16" height="40" rx="2"/>
            <rect x="532" y="338" width="16" height="40" rx="2"/><rect x="552" y="338" width="16" height="40" rx="2"/>
            <rect x="572" y="338" width="16" height="40" rx="2"/><rect x="592" y="338" width="16" height="40" rx="2"/>
            <rect x="612" y="338" width="16" height="40" rx="2"/><rect x="632" y="338" width="16" height="40" rx="2"/>
            <rect x="652" y="338" width="16" height="40" rx="2"/><rect x="672" y="338" width="16" height="40" rx="2"/>
            <rect x="692" y="338" width="16" height="40" rx="2"/><rect x="712" y="338" width="16" height="40" rx="2"/>
            <rect x="732" y="338" width="16" height="40" rx="2"/><rect x="752" y="338" width="16" height="40" rx="2"/>
            <rect x="772" y="338" width="16" height="40" rx="2"/><rect x="792" y="338" width="16" height="40" rx="2"/>
            <rect x="812" y="338" width="16" height="40" rx="2"/><rect x="832" y="338" width="16" height="40" rx="2"/>
            <rect x="852" y="338" width="16" height="40" rx="2"/><rect x="872" y="338" width="16" height="40" rx="2"/>
            <rect x="892" y="338" width="16" height="40" rx="2"/>
          </g>
          <!-- 窗口内亮条(clip + 平移动画):模拟 token 流过固定窗口 -->
          <g clip-path="url(#winclip)">
            <g class="strip-slide">
              <g fill="#22d3ee">
                <rect x="480" y="338" width="16" height="40" rx="2"/><rect x="500" y="338" width="16" height="40" rx="2"/>
                <rect x="520" y="338" width="16" height="40" rx="2"/><rect x="540" y="338" width="16" height="40" rx="2"/>
                <rect x="560" y="338" width="16" height="40" rx="2"/><rect x="580" y="338" width="16" height="40" rx="2"/>
                <rect x="600" y="338" width="16" height="40" rx="2"/><rect x="620" y="338" width="16" height="40" rx="2"/>
                <rect x="640" y="338" width="16" height="40" rx="2"/><rect x="660" y="338" width="16" height="40" rx="2"/>
                <rect x="680" y="338" width="16" height="40" rx="2"/><rect x="700" y="338" width="16" height="40" rx="2"/>
                <rect x="720" y="338" width="16" height="40" rx="2"/><rect x="740" y="338" width="16" height="40" rx="2"/>
                <rect x="760" y="338" width="16" height="40" rx="2"/><rect x="780" y="338" width="16" height="40" rx="2"/>
                <rect x="800" y="338" width="16" height="40" rx="2"/><rect x="820" y="338" width="16" height="40" rx="2"/>
                <rect x="840" y="338" width="16" height="40" rx="2"/><rect x="860" y="338" width="16" height="40" rx="2"/>
                <rect x="880" y="338" width="16" height="40" rx="2"/><rect x="900" y="338" width="16" height="40" rx="2"/>
                <rect x="920" y="338" width="16" height="40" rx="2"/><rect x="940" y="338" width="16" height="40" rx="2"/>
                <rect x="960" y="338" width="16" height="40" rx="2"/><rect x="980" y="338" width="16" height="40" rx="2"/>
              </g>
            </g>
          </g>
          <!-- 窗框 -->
          <rect x="600" y="330" width="192" height="56" rx="6" fill="none" stroke="#ffcb6b" stroke-width="2.5"/>
          <text x="606" y="326" fill="#ffcb6b" font-size="12" font-weight="700">滑窗 W=128</text>
          <text x="606" y="404" fill="#8ea0c2" font-size="11">窗口固定、token 左移 ⇔ 窗口沿序列向右滑动;窗外 key 展开为整行 -1</text>
        </g>

        <!-- 左下:可见域公式卡 -->
        <g>
          <rect x="40" y="330" width="290" height="120" rx="10" fill="#141d33" stroke="#a78bfa" stroke-width="1.4"/>
          <text x="58" y="356" fill="#a78bfa" font-size="12.5" font-weight="700">yoco_swa_visibility(cpp:155)</text>
          <text x="58" y="382" fill="#dbe4f5" font-size="12" font-family="JetBrains Mono,Consolas,monospace">abs_lo = clamp(max(</text>
          <text x="82" y="400" fill="#89ddff" font-size="12" font-family="JetBrains Mono,Consolas,monospace">pos-W+1, rect_lo, valid_start),</text>
          <text x="82" y="418" fill="#89ddff" font-size="12" font-family="JetBrains Mono,Consolas,monospace">0, pos+1)</text>
          <text x="58" y="440" fill="#8ea0c2" font-size="11">section1:state ring 内 [start_slot, W)</text>
        </g>

        <!-- 底:section1/section2 说明 -->
        <g>
          <rect x="40" y="466" width="880" height="66" rx="10" fill="#0e1729" stroke="#263352"/>
          <text x="60" y="492" fill="#dbe4f5" font-size="12.5" font-weight="700">注意力输入 kv = [ section1: swa_cache 历史 ring(每序列 W 个) | section2: 本 chunk 新 kv | 压缩 KV ]</text>
          <text x="60" y="514" fill="#8ea0c2" font-size="11.5">pivots 四元组 [sec1_start+start_slot, sec1_len, sec2_start+(k_lo-clip_prefix), new_len] 由 C++ 逐行写入,展开成 [total_q, W] 的稠密 index(-1 = 不可见),csrc/.../prepare_tensor_input_v4.cpp:274-280</text>
        </g>
      </svg>
      <div class="cap">图 4-1 · 有界重放三步动画:① 长 prompt 中只有绿色矩形 [N-KEEP_TOKENS, N) 存活;② clip_prefix 把矩形外的行从 compact 布局移除;③ 矩形内叠加滑窗 W(亮色 token 在 clipPath 窗口内滑动),可见域 = 滑窗 ∩ 矩形</div>
    </div>
    <div class="note good">
      <b>「有界」的直观读法</b>:不管 prompt 多长,consumer 层在 prefill 里要处理的行数被钳制在 <code>min(N, KEEP_TOKENS + 每 chunk 1 个占位)</code> 以内;且这 KEEP_TOKENS 里还要预留 B 个 token 的回退余量——回退之后,窗口里依然是满的 W 个 key。
    </div>
  </section>

  <!-- ================================================================ 5 -->
  <section>
    <h2 class="sec"><span class="num">5</span>C++ 侧:截断元数据如何构建(prepare_prompt_v4)</h2>
    <p class="lede">所有截断语义在 CPU 上的 <code>prepare_prompt_v4</code> 一次性算清:每请求的 clip_prefix、每行的可见域 pivots、compact 版 varlen 边界与 ks/ke、ring 写入槽位。</p>
    <p>入口函数先做硬校验,再填元数据;<code>mode == OFF</code> 时是 no-op(csrc/engine/input_metadata/prepare_tensor_input_v4.cpp:348-360):</p>
    <pre class="code"><span class="filepath">csrc/engine/input_metadata/prepare_tensor_input_v4.cpp:349-360</span>
<span class="k">static void</span> <span class="f">update_yoco_prompt_v4</span>(<span class="k">const</span> PrepareArgs &amp;args, py::dict &amp;result) {
    <span class="k">if</span> (args.yoco_prefill_truncation_mode == YocoPrefillTruncationMode::OFF)
        <span class="k">return</span>;
    <span class="k">const int32_t</span> keep_tokens = args.yoco_prefill_keep_tokens;
    TORCH_CHECK_GT(keep_tokens, <span class="n">0</span>);
    <span class="c">// 截断范围要&gt;=window size + 回退 B,要保证回退后仍然有 window size 个</span>
    TORCH_CHECK_GE(keep_tokens, args.window_size + args.max_backtracking_tokens)
        &lt;&lt; <span class="s">"DEEPINFER_YOCO_PREFILL_KEEP_TOKENS must be &gt;= window_size ("</span> &lt;&lt; args.window_size
        &lt;&lt; <span class="s">") + DEEPINFER_MAX_BACKTRACKING_TOKENS ("</span> &lt;&lt; args.max_backtracking_tokens &lt;&lt; <span class="s">")"</span>;
    fill_yoco_truncation_metadata(args, result);
}</pre>
    <p>注意这里的 <code>data_len</code> 是 <strong>整个序列的当前长度</strong>(含 chunked prefill 尚未算到的部分,以及重算场景下已生成的 token),所以矩形锚定在序列末端而非 chunk 末端:</p>
    <pre class="code"><span class="filepath">csrc/engine/input_metadata/prepare_tensor_input_v4.cpp:217-231</span>
<span class="k">for</span> (<span class="k">int</span> i_seq = <span class="n">0</span>, full_base = <span class="n">0</span>; i_seq &lt; n_seq; ++i_seq) {
    <span class="k">auto</span> p_seq = seq_metadata_list[i_seq];
    int32_t q_len = p_seq-&gt;seqlen_q;
    int32_t q_start = p_seq-&gt;seqlen_k - q_len;
    int32_t data_len = p_seq-&gt;seq_data-&gt;get_len();
    <span class="c">// 逻辑保留区间 = [max(0, data_len - keep_tokens), data_len) ∩ [q_start, q_end)。clip_prefix 即 chunk 开头被截断</span>
    <span class="c">// 的 token 数;上界 q_len - 1 即 整个 chunk 在保留区间之前时仍保留 chunk 最后 1 个 token 占位。</span>
    <span class="c">// mask 模式不截行,clip_prefix 恒为 0(全部 token 照常计算,只是矩形之外的可见域为空)。</span>
    int32_t clip_prefix = compact ? std::clamp(data_len - keep_tokens - q_start, <span class="n">0</span>, q_len - <span class="n">1</span>) : <span class="n">0</span>;
    clip_prefixes[i_seq] = clip_prefix;
    full_bases[i_seq] = full_base;
    int32_t keep_len = q_len - clip_prefix;
    p_cu_c[i_seq + <span class="n">1</span>] = p_cu_c[i_seq] + keep_len;   <span class="c">// compact varlen 边界 cumsum(keep_len)</span>
    full_base += q_len;
}</pre>
    <p>可见域的核心是三下界取 max 再 clamp(<code>rect_lo = data_len - keep_tokens</code>;<code>valid_start</code> 是 zero-state 重算时 ring 的有效下界,正常路径为 0):</p>
    <pre class="code"><span class="filepath">csrc/engine/input_metadata/prepare_tensor_input_v4.cpp:149-168</span>
<span class="k">static</span> YocoSwaVisibility <span class="f">yoco_swa_visibility</span>(
    int32_t pos, int32_t q_start, int32_t j, int32_t window_size, int32_t rect_lo, int32_t valid_start) {
    <span class="c">// 组合下界(seq 中的位置):滑窗下界、矩形下界与 state 有效下界取 max,再 clamp 到 [0, pos + 1];</span>
    <span class="c">// abs_lo == pos + 1 表示空可见域(该 token 完全在矩形之外)。</span>
    int32_t abs_lo = std::clamp(std::max({pos - window_size + <span class="n">1</span>, rect_lo, valid_start}), <span class="n">0</span>, pos + <span class="n">1</span>);
    int32_t sec1_lo_abs = std::min(abs_lo, q_start);          <span class="c">// sec1 右边界为 q_start</span>
    int32_t start_slot = sec1_lo_abs - (q_start - window_size);
    TORCH_CHECK_GE(start_slot, <span class="n">0</span>) &lt;&lt; <span class="s">"yoco start_slot out of range"</span>;
    TORCH_CHECK_LE(start_slot, window_size) &lt;&lt; <span class="s">"yoco start_slot out of range"</span>;
    int32_t k_lo = std::max(abs_lo - q_start, <span class="n">0</span>);          <span class="c">/// sec2 的左边界为 q_start</span>
    int32_t new_len = j - k_lo + <span class="n">1</span>;
    TORCH_CHECK_GE(new_len, <span class="n">0</span>) &lt;&lt; <span class="s">"yoco section2 new_len is negative"</span>;
    <span class="k">return</span> {start_slot, window_size - start_slot, k_lo, new_len};
}</pre>
    <p>每行的 ring 写入规则同样在 C++ 里定死——<b>矩形内 + chunk 尾部 swa_block_size 段</b>才写,其余(包括整段被截的占位 token)一律 <code>-1</code>:</p>
    <pre class="code"><span class="filepath">csrc/engine/input_metadata/prepare_tensor_input_v4.cpp:261-271</span>
<span class="k">for</span> (int32_t j = clip_prefix; j &lt; q_len; ++j, ++i_qc) {
    int32_t pos = q_start + j;
    <span class="k">if</span> (compact) {
        p_qi[i_qc] = full_bases[i_seq] + j;      <span class="c">// full → compact 的正向映射</span>
        p_pos_c[i_qc] = pos;
        <span class="c">// 占位 token 不写 ring;其余保留 token 的 ring slot。由绝对位置决定。</span>
        <span class="k">bool</span> in_rect = pos &gt;= data_len - keep_tokens;
        <span class="k">if</span> (in_rect &amp;&amp; q_len - j &lt;= swa_block_size)
            p_slot_c[i_qc] = p_seq-&gt;state_id * swa_block_size + pos % swa_block_size;
        <span class="k">else</span>
            p_slot_c[i_qc] = -<span class="n">1</span>;
    }
    <span class="k">auto</span> vis = yoco_swa_visibility(pos, q_start, j, window_size, data_len - keep_tokens, valid_start);
    ...  <span class="c">// pivots 写入:sec1 起点/长度 + sec2 起点/长度</span>
}</pre>
    <p>两种模式的产出物在 C++ 尾部分道:mask 模式只写 <code>yoco_mask_swa_index_pivots</code> 就返回(cpp:285-289);compact 模式继续生成 compact 版 <code>ks/ke</code>(稀疏压缩)与 <code>kv_ca_index_offset_len</code>(dense 压缩)——注意这两个的 <code>klen</code> 仍按<strong>绝对位置</strong> <code>(q_start + j + 1) / ratio</code> 计算(cpp:292-304),即压缩可见域不截断,这与「main/index KV 必须全量」一脉相承。最终产出 9 个 <code>yoco_consumer_*</code> 字段(cpp:334-342),CP&gt;1 时附加上「先截断再切 CP」的标量(cpp:344-345)。</p>
    <table class="tbl">
      <tr><th style="width:34%">compact 模式产出字段</th><th>语义(全部为 compact 布局)</th></tr>
      <tr><td><code>yoco_consumer_query_indices</code></td><td>full varlen 下标的 gather 列表(full → compact 正向映射),<code>[total_q_c]</code></td></tr>
      <tr><td><code>yoco_consumer_cu_seqlens_q / total_q / positions</code></td><td>compact varlen 边界 <code>cumsum(keep_len)</code>、总行数、截断后 positions</td></tr>
      <tr><td><code>yoco_consumer_swa_index_pivots</code></td><td>SWA 可见域 pivots(装入视图的 <code>kv_swa_full_index_pivots</code> 槽位),<code>[total_q_c, 4]</code></td></tr>
      <tr><td><code>yoco_consumer_ks / ke / kv_ca_index_offset_len</code></td><td>压缩 index attention 的行偏移(compact 行号、绝对 key 语义)</td></tr>
      <tr><td><code>yoco_consumer_slot_mapping_store_swa</code></td><td>ring 写入槽位;占位 token 显式 <code>-1</code>,不写 ring</td></tr>
      <tr><td><code>yoco_consumer_cp_mirror_len / cp_contrib_pad_len</code></td><td>CP&gt;1 时「先 compact 再 CP」的长度与贡献缓冲 pad</td></tr>
    </table>
    <p style="font-size:12.5px;color:var(--muted)">字段文档见 deepinfer/model_executor/input_metadata/yoco.py:35-64。</p>
  </section>

  <!-- ================================================================ 6 -->
  <section>
    <h2 class="sec"><span class="num">6</span>Python 侧:边界层切换与 compact 边界</h2>
    <p class="lede">模型主循环在「第一个 consumer 层」的位置切 metadata 视图;层内部再把 hidden / residual / topk 切到 compact 布局,同时保留 full 副本用于补写 KV。</p>
    <p>deepseek.py 在构造期确定 <code>yoco_boundary_layer_idx = cfg.n_prefill_layer</code> 并校验 DFlash/Engram 兼容性(deepseek.py:118-138);forward 的层循环在边界层做切换——两种模式都切,只是切成的视图不同:</p>
    <pre class="code"><span class="filepath">deepinfer/model_executor/models/deepseek.py:190-207</span>
<span class="k">for</span> i <span class="k">in</span> range(<span class="k">self</span>.num_layers):
    <span class="k">if</span> input_metadata.is_prompt <span class="k">and</span> i == <span class="k">self</span>.yoco_boundary_layer_idx:
        <span class="k">if</span> envs.DEEPINFER_YOCO_PREFILL_TRUNCATION_MODE == <span class="s">"compact"</span>:
            <span class="c"># yoco 截断,metadata 的布局从 full 切换到 compact,hiddens 在第一个 yoco consumer layer 内部切换。</span>
            <span class="c"># 原则:需要算到底的(compact)作为 input_metadata,full metadata 经 cross layer runtime 传给 full-source 路径。</span>
            consumer_metadata = input_metadata.<span class="f">get_consumer_view</span>()
            cross_layer_runtime.consumer_full_metadata = input_metadata
            input_metadata = consumer_metadata
            ...
        <span class="k">else</span>:
            input_metadata = input_metadata.<span class="f">get_mask_view</span>()</pre>
    <p><code>get_consumer_view()</code> 是一次浅拷贝换槽位(deepinfer/model_executor/input_metadata/yoco.py:94-118):<code>total_q / cu_seqlens_q / positions / slot_mapping_store_swa / ks / ke / kv_ca_index_offset_len</code> 全部换成 compact 版,SWA pivots 换成 <code>yoco_consumer_swa_index_pivots</code>,并把 forward 期展开结果(<code>kv_swa_full_index / kv_ca_index / klen</code>)清空,让 <code>compute_attn_info</code> 按 compact 元数据重新展开(input_metadata.py:353-357)。层内第一个 consumer 层真正执行切换:</p>
    <pre class="code"><span class="filepath">deepinfer/model_executor/models/decoder_layer.py:134-141</span>
<span class="k">if</span> cross_layer_runtime.consumer_full_metadata <span class="k">is not</span> <span class="k">None</span> <span class="k">and</span> cross_layer_runtime.consumer_full_hidden <span class="k">is</span> <span class="k">None</span>:
    <span class="k">assert</span> isinstance(input_metadata, YocoMetadataMixin), <span class="s">"YOCO compaction requires YOCO metadata"</span>
    <span class="k">assert</span> <span class="k">self</span>.engram <span class="k">is</span> <span class="k">None</span>, <span class="s">"yoco 层不能是 engram 层"</span>
    compact_inputs, full_inputs = <span class="f">compact_yoco_boundary</span>(
        hidden_states, residual, input_metadata, cross_layer_runtime, hc_enabled=<span class="k">self</span>.hc_enabled
    )
    cross_layer_runtime.consumer_full_hidden = <span class="k">self</span>.<span class="f">attn_norm_forward</span>(*full_inputs)[<span class="n">1</span>]  <span class="c"># full 版 shared hidden</span>
    hidden_states, residual = compact_inputs</pre>
    <p><code>compact_yoco_boundary</code>(deepinfer/model_executor/models/v4_modules/yoco.py:93-123)做四件事:</p>
    <ul class="feat">
      <li>把 hidden 切到 compact 布局:<code>yoco_boundary_compact</code> = <code>gather(x, query_indices)</code>;CP&gt;1 时先按本 rank 贡献 gather、再 all-gather 拼接、再选出本 rank 的 compact-mirror 行(yoco.py:55-76)。</li>
      <li>residual 分三种:普通 tensor 直接 gather;<code>HCLazyPostData</code>(hyper-connection 逐 token 的 residual / post_layer_mix / comb_res_mix / pre_layer_mix)逐字段 gather(yoco.py:79-90);engram 清空过的 lazy 数据禁止到达边界(yoco.py:108)。</li>
      <li>跨层路由状态同步压缩:<code>topk_indices / block_candidate_idxs</code> gather 到 compact 布局,候选块查询行布局变化后派生缓存全部作废重建(yoco.py:116-122)。</li>
      <li>返回 <b>(compact 副本, full 原件)</b> 成对结果:full 原件马上用于计算 <code>consumer_full_hidden</code>(供后续层补写 KV)。</li>
    </ul>
    <p>切换完成后,首个 consumer 层的 attn-norm bf16 hidden 被 clone 进 <code>cross_layer_runtime.shared_hidden</code>,供本层及后续 consumer 层长期消费(decoder_layer.py:146-152);compact 下拿到的是 compact 版,full 版走 <code>consumer_full_hidden</code>。这两个跨层字段定义在 CrossLayerRuntime(deepinfer/model_executor/models/v4_modules/cross_layer.py:310-321)。</p>
    <div class="note warn">
      <b>MoE 通信的隐藏开关</b>:compact 模式下 DeepEP dispatch 会关闭 <code>do_cpu_sync</code>——「do_sync=True makes yoco compaction a cpu bottleneck, while =False costs extra GPU memory」,mask 模式不省算力、CPU 不是瓶颈,故只在 compact 关(deepinfer/model_executor/models/v4_modules/mlp.py:482-485)。
    </div>
  </section>

  <!-- ================================================================ 7 -->
  <section>
    <h2 class="sec"><span class="num">7</span>Attention 内部:full-KV 补写与 SWA ring 写入</h2>
    <p class="lede">compact 截断只裁 query;压缩 KV 仍覆盖全上下文。consumer 层 forward 里有一条专门的「full-KV 补写」旁路,随后主路径按 compact 元数据算注意力并写 SWA ring。</p>
    <pre class="code"><span class="filepath">deepinfer/model_executor/models/v4_modules/attn.py:769-774</span>
yoco_full_kv_stored = cross_layer_runtime.consumer_full_metadata <span class="k">is not</span> <span class="k">None</span>
<span class="k">if</span> yoco_full_kv_stored:
    <span class="c"># YOCO compact prefill: the query has been trimmed, but the KV still has to cover the full context.</span>
    <span class="c"># Here the full shared hidden is used to generate and write the main/index KV, and the later main path skips the KV update.</span>
    <span class="k">self</span>.<span class="f">_store_yoco_full_kv</span>(cross_layer_runtime, kv_cache)</pre>
    <p><code>_store_yoco_full_kv</code>(attn.py:672-721)的分工:</p>
    <ul class="feat">
      <li><b>纯 SWA consumer 层直接返回</b>(<code>not self.has_packed_kv</code>)——它没有 main/index KV 需要全量更新(attn.py:684-685)。</li>
      <li><b>kv-source 层</b>:用 <code>shared_hidden_kv_proj(consumer_full_hidden)</code> 只做 KV 投影(不走常规合并投影,省掉用不到的 index 权重计算),再以 <code>full_metadata</code> 为布局写入压缩 cache(attn.py:692-709)。</li>
      <li><b>index 层</b>:<code>index_attn.store_index_kv(..., full_metadata)</code> 全量落 ica_cache(attn.py:714-721)。</li>
      <li>之后主路径的压缩 KV 写入与 topk 存储全部跳过(<code>store_kv=not yoco_full_kv_stored</code>,attn.py:565),只算 compact query 的 topk(attn.py:537-540 注释)。</li>
    </ul>
    <p>主路径的 prefill 注意力输入拼装为三段(<b>[SWA 历史 ring | 本 chunk 新 kv | 压缩 cache]</b>,attn.py:813-818),SWA 段的读取与写入顺序有讲究:</p>
    <pre class="code"><span class="filepath">deepinfer/model_executor/models/v4_modules/attn.py:846-855</span>
<span class="k">if</span> input_metadata.is_prompt:
    <span class="f">load_paged_kv_cache</span>(
        kv_cache.swa_cache,
        input_metadata.load_segments_swa,
        total_k_swa_cached,
        out=kv[:total_k_swa_cached],
    )  <span class="c"># [num_seqs * window_size, 1, qk_head_dim]</span>
    kv_swa_full_index = input_metadata.kv_swa_full_index  <span class="c"># [total_q, window_size]</span>
    <span class="c"># The SWA store slots may overlap the ranges loaded above, so prefill must store only after the cache load.</span>
    <span class="f">store_kv_cache</span>(kv_swa, kv_cache.swa_cache, input_metadata.slot_mapping_store_swa)</pre>
    <p>这里有两处「截断感知」的细节:</p>
    <ul class="feat">
      <li><b>先 load 后 store</b>:SWA 的写入槽位可能与加载区段重叠(环形缓冲的特性),必须先加载历史再写入新 token,否则本 chunk 自己的历史会被覆盖(attn.py:854 注释)。</li>
      <li><b>index 与 metadata 同源</b>:consumer 视图上 <code>kv_swa_full_index</code> 是从 <code>yoco_consumer_swa_index_pivots</code> 展开来的,展开函数与 full 完全同一条(<code>_expand_kv_swa_full_index</code>,deepinfer/model_executor/input_metadata/input_metadata.py:336-341:full 与 YoCo-windowed index「only differ in how P was built」),因此截断语义只存在于 pivots 构建期。</li>
    </ul>
    <p><code>store_kv_cache</code> 本身是通用的分页写入原语:把 bf16 token 按格式(MXFP8/FP4 等)量化后按 <code>slot_mapping</code> 散写进 paged cache,<code>-1</code> 表示 padding 不写;NPU 与 GPU 走不同的 TileLang kernel(deepinfer/model_executor/layers/tilelang_ops/store_kv_cache.py:26-80)。compact 模式下传入的 <code>slot_mapping_store_swa</code> 已经是 compact 版(占位 <code>-1</code>),这就是「矩形外不写 ring」在 Python 侧的落点。</p>
  </section>

  <!-- ================================================================ 8 -->
  <section>
    <h2 class="sec"><span class="num">8</span>KV cache 与重放的交互:状态槽位、dropped region 与落盘</h2>
    <p class="lede">SWA 不走 paged KV cache,而是每个序列独占一个「状态槽位」里的环形缓冲(ring)。这个 ring 的长度、以及 consumer SWA 落在哪个分区,都由回退与重放共同决定。</p>
    <div class="grid c3">
      <div class="card reveal">
        <h3><span class="ico">◎</span>ring 长度 = W + B</h3>
        <p><code>get_inference_swa_block_size = window_size + DEEPINFER_MAX_BACKTRACKING_TOKENS</code>(deepinfer/worker/cache_engine.py:88-93):回退 B 个 token 后 ring 里仍留满 W 个有效 key。槽位地址 = <code>state_id * swa_block_size + pos % swa_block_size</code>。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">▤</span>kvstore 视角再加余量</h3>
        <p>落盘只能在 <code>KVSTORE_GRAIN=128</code> 的整倍数处命中,开启 <code>DEEPINFER_PREFILL_STORE_EXTRA_STATE</code> 时 ring 再加 <code>EXTRA_SIZE(128) + KEEP_TOKENS</code>(cache_engine.py:96-110、32)——YoCo 截断的保留后缀本身就是「落盘重排的锚点回退余量」。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">⌘</span>consumer SWA 不落盘</h3>
        <p>状态块布局为 <code>[stored: producer SWA | dropped: consumer SWA | compression state]</code>;consumer SWA「恢复依赖 prefill 重算」(cache_engine.py:229-235)——也就是本篇的有界重放。</p>
      </div>
    </div>
    <div class="figure">
      <svg viewBox="0 0 980 470" xmlns="http://www.w3.org/2000/svg" font-family="'PingFang SC','Microsoft YaHei',sans-serif">
        <defs>
          <marker id="ar8" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#4f8cff"/>
          </marker>
          <marker id="ar8g" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#34d399"/>
          </marker>
          <marker id="ar8p" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#a78bfa"/>
          </marker>
        </defs>
        <!-- 标题 -->
        <text x="40" y="34" fill="#dbe4f5" font-size="14" font-weight="700">state block(单个序列槽位,StateBlock 布局,cache_engine.py:229-241)</text>
        <!-- state block 条 -->
        <g>
          <rect x="40" y="52" width="380" height="64" rx="8" fill="#0f2b22" stroke="#34d399" stroke-width="2"/>
          <text x="58" y="78" fill="#a7f3d0" font-size="13" font-weight="700">stored region</text>
          <text x="58" y="98" fill="#8ea0c2" font-size="11">producer SWA ring(inference 窗口 W+B)→ 落盘</text>
          <rect x="424" y="52" width="300" height="64" rx="8" fill="#2b1f0f" stroke="#fbbf24" stroke-width="2"/>
          <text x="442" y="78" fill="#fde68a" font-size="13" font-weight="700">dropped region(不落盘)</text>
          <text x="442" y="98" fill="#8ea0c2" font-size="11">YOCO consumer SWA | compression state</text>
          <!-- 括注 -->
          <path d="M40 128 q0 12 12 12 h640 q12 0 12 -12" stroke="#5a6b92" stroke-width="1.2" fill="none"/>
          <text x="360" y="156" fill="#5a6b92" font-size="11">total_bytes_kvstore(单 state slot,swa_cache.stride(0) 继承整个槽)</text>
        </g>
        <!-- 落盘箭头:仅 stored -->
        <path class="flowline" d="M230 124 L230 208" stroke="#34d399" stroke-width="2.2" fill="none" marker-end="url(#ar8g)"/>
        <g>
          <rect x="120" y="212" width="220" height="56" rx="10" fill="#141d33" stroke="#34d399" stroke-width="1.6"/>
          <text x="140" y="236" fill="#a7f3d0" font-size="13" font-weight="700">Disk(kvstore 落盘)</text>
          <text x="140" y="256" fill="#8ea0c2" font-size="10.5">state_size_to_disk = stored SWA 推理窗口</text>
        </g>
        <text x="256" y="180" fill="#34d399" font-size="11">只取 stored(按长度截断排除 dropped)</text>
        <!-- PE→CE 箭头:整个槽 -->
        <path class="flowline" d="M574 124 L574 208" stroke="#a78bfa" stroke-width="2.2" fill="none" marker-end="url(#ar8p)"/>
        <g>
          <rect x="470" y="212" width="250" height="56" rx="10" fill="#141d33" stroke="#a78bfa" stroke-width="1.6"/>
          <text x="490" y="236" fill="#c4b5fd" font-size="13" font-weight="700">CE(decode 引擎,TO_CE)</text>
          <text x="490" y="256" fill="#8ea0c2" font-size="10.5">传输完整 state;consumer SWA 按 ring 重排</text>
        </g>
        <text x="600" y="180" fill="#a78bfa" font-size="11">两部分全传(TO_CE=True 含 dropped 视图)</text>
        <!-- disk 命中 → 重放重建 -->
        <path class="flowline" d="M230 268 C230 330 420 340 560 300" stroke="#22d3ee" stroke-width="2" fill="none" marker-end="url(#ar8)"/>
        <g>
          <rect x="330" y="348" width="420" height="88" rx="10" fill="#0e2230" stroke="#22d3ee" stroke-width="1.8"/>
          <text x="350" y="374" fill="#67e8f9" font-size="13.5" font-weight="700">disk 命中恢复:consumer SWA 缺失 → 由重放重建</text>
          <text x="350" y="396" fill="#8ea0c2" font-size="11.5">load_state_from_store_to_prefill_cache 断言:存在 dropped SWA 层时</text>
          <text x="350" y="414" fill="#8ea0c2" font-size="11.5">必须 DEEPINFER_YOCO_PREFILL_TRUNCATION_MODE != "off"(cache_engine.py:836-838)</text>
          <text x="350" y="432" fill="#67e8f9" font-size="11.5">→ 从命中点重放的后缀会重写 ring 尾段(W+B 足够)</text>
        </g>
        <!-- 右侧:slot 说明 -->
        <g>
          <rect x="760" y="52" width="190" height="238" rx="10" fill="#141d33" stroke="#263352"/>
          <text x="776" y="80" fill="#dbe4f5" font-size="12.5" font-weight="700">state 槽位池</text>
          <text x="776" y="102" fill="#8ea0c2" font-size="10.5">num_state_slots =</text>
          <text x="776" y="118" fill="#8ea0c2" font-size="10.5">max_num_seqs × 1.2 + 1</text>
          <text x="776" y="140" fill="#8ea0c2" font-size="10.5">(environ.py:169,</text>
          <text x="776" y="156" fill="#8ea0c2" font-size="10.5">cache_engine.py:201-202)</text>
          <text x="776" y="182" fill="#8ea0c2" font-size="10.5">swa_cache 形状:</text>
          <text x="776" y="198" fill="#8ea0c2" font-size="10.5">[num_state_seqs,</text>
          <text x="776" y="214" fill="#8ea0c2" font-size="10.5"> swa_block_size, 1, 528]</text>
          <text x="776" y="236" fill="#8ea0c2" font-size="10.5">(cache_engine.py:216-218)</text>
          <text x="776" y="262" fill="#67e8f9" font-size="10.5">抢占/重算:fork 克隆 state,</text>
          <text x="776" y="278" fill="#67e8f9" font-size="10.5">zero_states 清零由重放重建</text>
        </g>
        <!-- 底部测试标注 -->
        <g>
          <rect x="40" y="348" width="260" height="88" rx="10" fill="#141d33" stroke="#263352"/>
          <text x="58" y="374" fill="#dbe4f5" font-size="12" font-weight="700">单测:test_yoco_swa_disk_and_ce</text>
          <text x="58" y="396" fill="#8ea0c2" font-size="10.5">PE(compact)与 CE(off)布局一致性:</text>
          <text x="58" y="412" fill="#8ea0c2" font-size="10.5">落盘仅 stored 区、传输含 dropped 区、</text>
          <text x="58" y="428" fill="#8ea0c2" font-size="10.5">恢复后 dropped 区不被写</text>
          <text x="58" y="444" fill="#5a6b92" font-size="10">tests/worker/test_state_cache_ops.py:656-720</text>
        </g>
      </svg>
      <div class="cap">图 8-1 · 状态槽位分区与三条数据流:落盘(仅 stored)、PE→CE 迁移(全量)、disk 命中后的重放重建(consumer SWA)——虚线为流动画</div>
    </div>
    <p>把图中的机制翻译成语言:</p>
    <ul class="feat">
      <li><b>分区由模型结构决定,与模式无关</b>:<code>_is_dropped_swa_layer</code> 只看 <code>layer_id &gt;= n_prefill_layer</code>(cache_engine.py:113-116);StateBlock 据此算出 <code>swa_store_num_layer / swa_drop_num_layer</code> 两组 ring 的字节数(cache_engine.py:265-283)。</li>
      <li><b>落盘粒度对齐</b>:压缩窗口结束于 KVSTORE_GRAIN 边界,「only SWA is persisted」(cache_engine.py:285);<code>state_size_to_disk</code> 只含需落盘 SWA 的 inference 窗口(cache_engine.py:306)。</li>
      <li><b>disk 命中 + YOCO ⇒ 截断必须开</b>:<code>load_state_from_store_to_prefill_cache</code> 里的断言(cache_engine.py:836-838)说明:落盘 state 里没有 consumer SWA,唯一能重建它的就是从命中点开始的有界重放。</li>
      <li><b>重算(swa_valid_start)</b>:序列被抢占后 <code>reset_for_recompute()</code> 清零 <code>swa_valid_start</code>(csrc/engine/sequence.hpp:223-227);zero-state 重算时 <code>[0, valid_start)</code> 的 ring 被清零,可见域左边界必须 clamp 到 valid_start,避免 attend 到清零 slot(cpp:153-155、499-503)。开启 yoco 截断时引擎明确「允许抢占导致的结果变化」(llm_engine.py:888)。</li>
    </ul>
  </section>

  <!-- ================================================================ 9 -->
  <section>
    <h2 class="sec"><span class="num">9</span>分块 prefill:逐块重放、占位 token 与 ring 不变量</h2>
    <p class="lede">长 prompt 被切成多个 chunk。每个 chunk 在 consumer 层只重放「尾部与矩形相交」的部分;被完全截断的 chunk 仍保留 1 个占位 token 过采样。</p>
    <div class="figure">
      <svg viewBox="0 0 980 520" xmlns="http://www.w3.org/2000/svg" font-family="'PingFang SC','Microsoft YaHei',sans-serif">
        <defs>
          <marker id="ar9" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#22d3ee"/>
          </marker>
        </defs>
        <!-- chunk 行 -->
        <text x="40" y="34" fill="#dbe4f5" font-size="14" font-weight="700">分块 prefill:每个 chunk 只重放与矩形相交的尾部(占位 token = chunk 最后 1 个)</text>
        <g>
          <!-- chunk0 -->
          <rect x="40" y="56" width="250" height="46" rx="6" fill="#141d33" stroke="#3a4a70"/>
          <text x="56" y="84" fill="#8ea0c2" font-size="12">chunk 0 [0, 2048)</text>
          <text x="170" y="84" fill="#f87171" font-size="11">全截断</text>
          <rect class="winpulse" x="272" y="62" width="12" height="34" rx="2" fill="#fbbf24"/>
          <text x="240" y="118" fill="#fbbf24" font-size="10.5">占位 ×1</text>
          <!-- chunk1 -->
          <rect x="310" y="56" width="250" height="46" rx="6" fill="#141d33" stroke="#3a4a70"/>
          <text x="326" y="84" fill="#8ea0c2" font-size="12">chunk 1 [2048, 4096)</text>
          <text x="445" y="84" fill="#f87171" font-size="11">全截断</text>
          <rect class="winpulse" x="542" y="62" width="12" height="34" rx="2" fill="#fbbf24"/>
          <!-- chunk2 -->
          <rect x="580" y="56" width="170" height="46" rx="6" fill="#141d33" stroke="#3a4a70"/>
          <text x="592" y="84" fill="#8ea0c2" font-size="12">chunk 2</text>
          <rect x="662" y="62" width="76" height="34" rx="4" fill="#0f766e" stroke="#34d399"/>
          <text x="666" y="84" fill="#a7f3d0" font-size="10.5">跨界部分</text>
          <!-- chunk3 final -->
          <rect x="770" y="56" width="176" height="46" rx="6" fill="#0f2b22" stroke="#34d399" stroke-width="2"/>
          <text x="780" y="76" fill="#a7f3d0" font-size="12" font-weight="700">final chunk</text>
          <text x="780" y="94" fill="#8ea0c2" font-size="10.5">keep_len = 140 行全算</text>
          <!-- 矩形竖线 -->
          <line class="winpulse" x1="662" y1="44" x2="662" y2="112" stroke="#34d399" stroke-width="2.5"/>
          <text x="600" y="40" fill="#34d399" font-size="11" font-weight="700">rect_lo = N-140</text>
        </g>

        <!-- 尾段 → ring 箭头 -->
        <path class="flowline" d="M740 102 C740 170 620 190 560 216" stroke="#22d3ee" stroke-width="2" fill="none" marker-end="url(#ar9)"/>
        <path class="flowline" d="M700 102 C700 150 590 175 545 210" stroke="#22d3ee" stroke-width="1.4" fill="none" opacity=".6"/>
        <text x="700" y="170" fill="#67e8f9" font-size="11">chunk 尾部 ∩ 矩形 → 写 ring(pos % swa_block_size)</text>

        <!-- ring -->
        <g transform="translate(430,340)">
          <!-- 外圈槽位 -->
          <g fill="#16233f" stroke="#26352">
          </g>
          <g fill="#16233f" stroke="#3a4a70">
            <circle cx="0" cy="-86" r="11"/><circle cx="43" cy="-75" r="11"/><circle cx="75" cy="-43" r="11"/>
            <circle cx="86" cy="0" r="11"/><circle cx="75" cy="43" r="11"/><circle cx="43" cy="75" r="11"/>
            <circle cx="0" cy="86" r="11"/><circle cx="-43" cy="75" r="11"/><circle cx="-75" cy="43" r="11"/>
            <circle cx="-86" cy="0" r="11"/><circle cx="-75" cy="-43" r="11"/><circle cx="-43" cy="-75" r="11"/>
            <circle cx="22" cy="-83" r="11"/><circle cx="61" cy="-61" r="11"/><circle cx="83" cy="-22" r="11"/>
            <circle cx="83" cy="22" r="11"/><circle cx="61" cy="61" r="11"/><circle cx="22" cy="83" r="11"/>
            <circle cx="-22" cy="83" r="11"/><circle cx="-61" cy="61" r="11"/><circle cx="-83" cy="22" r="11"/>
            <circle cx="-83" cy="-22" r="11"/><circle cx="-61" cy="-61" r="11"/><circle cx="-22" cy="-83" r="11"/>
          </g>
          <!-- 窗口弧:绿(约 17/24 圈 ≈ W/(W+B) 比例示意) -->
          <path d="M -22 -83 A 86 86 0 1 1 -22 83" fill="none" stroke="#34d399" stroke-width="7" opacity=".85"/>
          <!-- 回退弧:琥珀 -->
          <path d="M -22 83 A 86 86 0 0 1 -43 75" fill="none" stroke="#fbbf24" stroke-width="7" opacity=".9"/>
          <!-- 旋转写头 -->
          <g class="ringwrite">
            <circle cx="0" cy="-86" r="13" fill="none" stroke="#22d3ee" stroke-width="2.5"/>
            <circle cx="0" cy="-86" r="4" fill="#22d3ee"/>
          </g>
          <text x="-160" y="-104" fill="#34d399" font-size="12" font-weight="700">窗口 W=128</text>
          <text x="-160" y="-86" fill="#8ea0c2" font-size="10.5">回退后仍满 W 个 key</text>
          <text x="-160" y="96" fill="#fbbf24" font-size="12" font-weight="700">回退余量 B(≥ nextn+1)</text>
          <text x="-160" y="114" fill="#8ea0c2" font-size="10.5">draft 被拒 → 最多回退 B</text>
          <text x="-160" y="0" fill="#67e8f9" font-size="11">写头:pos % (W+B) 环形推进</text>
          <text x="-160" y="18" fill="#5a6b92" font-size="10">占位 token 槽位 = -1,不触碰 ring</text>
        </g>

        <!-- 右侧:不变量卡 -->
        <g>
          <rect x="700" y="220" width="246" height="180" rx="10" fill="#141d33" stroke="#4f8cff" stroke-width="1.6"/>
          <text x="718" y="248" fill="#dbe4f5" font-size="13" font-weight="700">ring 不变量(逐块成立)</text>
          <text x="718" y="274" fill="#8ea0c2" font-size="11">下一 chunk 的 section1 只读:</text>
          <text x="718" y="292" fill="#8ea0c2" font-size="11">[max(q_start-W, rect_lo), q_start)</text>
          <text x="718" y="310" fill="#8ea0c2" font-size="11">⊆ 上一 chunk 尾部写入区;</text>
          <text x="718" y="332" fill="#8ea0c2" font-size="11">final chunk 写满 [N-(W+B), N);</text>
          <text x="718" y="350" fill="#8ea0c2" font-size="11">decode / 回退读的窗口 ⊆ 该区。</text>
          <text x="718" y="378" fill="#67e8f9" font-size="10.5">矩形外 key 的可见域为空,</text>
          <text x="718" y="394" fill="#67e8f9" font-size="10.5">陈旧 ring 内容永远不被读。</text>
        </g>

        <!-- 底部代码引注 -->
        <g>
          <rect x="40" y="440" width="620" height="58" rx="10" fill="#0d1424" stroke="#26352"/>
          <text x="58" y="464" fill="#89ddff" font-size="11" font-family="JetBrains Mono,Consolas,monospace">clip_prefix = clamp(data_len - keep - q_start, 0, q_len-1)  // 全截断 chunk 仍留 1 个占位</text>
          <text x="58" y="484" fill="#5d7294" font-size="10.5" font-family="JetBrains Mono,Consolas,monospace">csrc/engine/input_metadata/prepare_tensor_input_v4.cpp:222-229 · prepare_sample.cpp:173-179</text>
        </g>
      </svg>
      <div class="cap">图 9-1 · 逐块重放与环形 SWA buffer:青色写头沿 ring 旋转写入(CSS 动画);绿色弧 = 窗口 W,琥珀弧 = 回退余量 B;全截断 chunk 仅 1 个占位 token(脉冲高亮)</div>
    </div>
    <p>「占位 token」是这个设计里最容易被忽略的一环。为什么整个 chunk 都在矩形之前还要保留 1 行?</p>
    <pre class="code"><span class="filepath">csrc/engine/prepare_sample.cpp:170-179</span>
<span class="k">int</span> out_len = seqlen_q;
<span class="k">if</span> (yoco_compaction) {
    <span class="k">const int</span> q_start = seq_metadata-&gt;seqlen_k - seqlen_q;
    <span class="k">const int</span> data_len = seq_metadata-&gt;seq_data-&gt;get_len();
    <span class="c">// 上界 seqlen_q - 1 即 keep_len &gt;= 1:每个 prefill chunk 都要用最后一个 token 过 sampling(非最终 chunk 结果随后丢弃),</span>
    <span class="c">// 因此即使整个 chunk 被截断也保留 1 个占位 token,保证下方 selected_token_indices 恒有合法的 model output 行可寻址。</span>
    <span class="k">const int</span> clip_prefix = std::clamp(data_len - yoco_prefill_keep_tokens - q_start, <span class="n">0</span>, seqlen_q - <span class="n">1</span>);
    out_len = seqlen_q - clip_prefix;
    TORCH_CHECK(!seq_metadata-&gt;sampling.need_prompt_logprobs, ...);
    TORCH_CHECK(out_len &gt;= <span class="n">1</span>, <span class="s">"sampling positions must reside in the yoco consumer keep range"</span>);
}</pre>
    <p>占位行的数值是「全 masked」的:<code>abs_lo == pos+1</code> 时该行可见域为空,pivots 展开后整行 <code>-1</code>(deepinfer/model_executor/input_metadata/yoco.py:36-37)。它不写 ring(槽位 <code>-1</code>)、输出只用来喂采样然后被丢弃;而压缩 KV 全量写由 full-KV 旁路独立完成,所以占位行的存在不会污染任何缓存。等价性测试专门覆盖了这些边界:<code>chunked_c0_all_clipped / chunked_c1_all_clipped / rect_at_chunk_start / rect_inside_chunk / rect_cuts_history / mixed_batch</code> 等场景(examples/yoco/yoco_equiv.py:88-113)。</p>
    <div class="note good">
      <b>逐块重放的自洽性</b>:第 k 个 chunk 对 ring 的写入集合是「本 chunk 尾部 swa_block_size 段 ∩ 矩形」;第 k+1 个 chunk 的 section1 读取集合是「窗口左界、矩形下界与 q_start 的 max 决定的区间」——恰好落在上一 chunk 的写入集合内。因此无论切成多少个 chunk、从哪个 disk 命中点恢复,ring 内容总是「该有的都有,没有的永远读不到」。
    </div>
  </section>

  <!-- ================================================================ 10 -->
  <section>
    <h2 class="sec"><span class="num">10</span>约束推导:KEEP ≥ window_size + MAX_BACKTRACKING_TOKENS</h2>
    <p class="lede">这条不等式在四处被独立强制(Python 启动断言 ×1、元数据断言 ×2、C++ 运行时检查 ×1),它的物理来源是 DSpark 投机解码的验证回退。</p>
    <div class="figure">
      <svg viewBox="0 0 980 470" xmlns="http://www.w3.org/2000/svg" font-family="'PingFang SC','Microsoft YaHei',sans-serif">
        <defs>
          <marker id="ar10" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#4f8cff"/>
          </marker>
        </defs>
        <!-- 条形图 -->
        <text x="40" y="36" fill="#dbe4f5" font-size="14" font-weight="700">① 尺寸关系:W + B ≤ KEEP(V4.1 默认 128 + 6 ≤ 140)</text>
        <g>
          <text x="40" y="76" fill="#8ea0c2" font-size="12">window_size W(SWA 窗口)</text>
          <rect x="40" y="86" width="14" height="26" fill="#0d1424" stroke="#26352"/>
          <rect class="growbar" x="40" y="86" width="560" height="26" rx="4" fill="#1d4ed8" opacity=".9" style="animation-duration:2.2s"/>
          <text x="610" y="105" fill="#93c5fd" font-size="12" font-weight="700">128</text>

          <text x="40" y="140" fill="#8ea0c2" font-size="12">MAX_BACKTRACKING_TOKENS B = max(设置值, USE_NEXTN_DECODE+1)</text>
          <rect x="40" y="150" width="14" height="26" fill="#0d1424" stroke="#26352"/>
          <rect class="growbar" x="40" y="150" width="26" height="26" rx="4" fill="#b45309" style="animation-duration:2.2s;animation-delay:.3s"/>
          <text x="78" y="169" fill="#fcd34d" font-size="12" font-weight="700">≥6(nextn=5)</text>

          <text x="40" y="204" fill="#8ea0c2" font-size="12">KEEP_TOKENS(保留后缀)</text>
          <rect x="40" y="214" width="14" height="26" fill="#0d1424" stroke="#26352"/>
          <rect class="growbar" x="40" y="214" width="613" height="26" rx="4" fill="#0f766e" style="animation-duration:2.2s;animation-delay:.6s"/>
          <text x="662" y="233" fill="#6ee7b7" font-size="12" font-weight="700">140</text>
          <!-- 对齐标尺线 -->
          <line x1="600" y1="80" x2="600" y2="180" stroke="#93c5fd" stroke-width="1" stroke-dasharray="3 3"/>
          <line x1="66" y1="144" x2="66" y2="212" stroke="#fcd34d" stroke-width="1" stroke-dasharray="3 3"/>
          <text x="330" y="262" fill="#34d399" font-size="12.5" font-weight="700">W + B = 134 ⊆ [N-140, N) ✓(三根条均为生长动画)</text>
        </g>

        <!-- 回退时序 -->
        <text x="40" y="306" fill="#dbe4f5" font-size="14" font-weight="700">② 回退时序:验证失败 → 回退 B 后窗口仍完整落在保留后缀内</text>
        <g>
          <line x1="60" y1="360" x2="920" y2="360" stroke="#26352" stroke-width="2"/>
          <g stroke="#3a4a70" stroke-width="1">
            <line x1="100" y1="352" x2="100" y2="368"/><line x1="180" y1="352" x2="180" y2="368"/>
            <line x1="260" y1="352" x2="260" y2="368"/><line x1="340" y1="352" x2="340" y2="368"/>
            <line x1="420" y1="352" x2="420" y2="368"/><line x1="500" y1="352" x2="500" y2="368"/>
            <line x1="580" y1="352" x2="580" y2="368"/><line x1="660" y1="352" x2="660" y2="368"/>
            <line x1="740" y1="352" x2="740" y2="368"/><line x1="820" y1="352" x2="820" y2="368"/>
            <line x1="900" y1="352" x2="900" y2="368"/>
          </g>
          <!-- 保留后缀底色 -->
          <rect x="628" y="330" width="272" height="60" rx="6" fill="#0f2b22" opacity=".8"/>
          <text x="640" y="352" fill="#34d399" font-size="11" font-weight="700">保留后缀 [N-140, N)</text>
          <!-- draft tokens -->
          <g>
            <rect x="828" y="374" width="13" height="20" rx="2" fill="#a78bfa"/>
            <rect x="843" y="374" width="13" height="20" rx="2" fill="#a78bfa"/>
            <rect x="858" y="374" width="13" height="20" rx="2" fill="#a78bfa"/>
            <rect x="873" y="374" width="13" height="20" rx="2" fill="#a78bfa"/>
            <rect x="888" y="374" width="13" height="20" rx="2" fill="#a78bfa"/>
          </g>
          <text x="826" y="416" fill="#a78bfa" font-size="10.5">nextn=5 个 draft(验证失败即回退)</text>
          <!-- 滑窗(rewind 动画) -->
          <g class="rewind">
            <rect x="436" y="336" width="184" height="30" rx="5" fill="none" stroke="#ffcb6b" stroke-width="2.5"/>
            <text x="446" y="356" fill="#ffcb6b" font-size="11" font-weight="700">窗口 W(解码位置)</text>
          </g>
          <!-- 回退箭头 -->
          <path class="marchdash" d="M820 340 L640 340" stroke="#fbbf24" stroke-width="2" fill="none" marker-end="url(#ar10)"/>
          <text x="680" y="328" fill="#fbbf24" font-size="11">拒收 → 回退 ≤ B</text>
          <text x="60" y="440" fill="#8ea0c2" font-size="11.5">回退后的解码位置 p ≥ N-B;其窗口 [p-W+1, p] ⊆ [N-(W+B), N] ⊆ 保留后缀 ⇒ ring 中键值完整、且都在重放写入区内</text>
        </g>
      </svg>
      <div class="cap">图 10-1 · 约束的几何解释:上三根生长条展示 W+B ≤ KEEP;下方时间轴展示 draft 回退后窗口(往返滑动的黄框)始终留在绿色保留后缀内</div>
    </div>
    <p>推导链条逐环如下:</p>
    <ol style="font-size:14px;color:var(--text);padding-left:22px;line-height:2">
      <li><b>B 的下界来自投机深度</b>:<code>DEEPINFER_USE_NEXTN_DECODE</code> 默认 5(deepinfer/environ.py:136);<code>DEEPINFER_MAX_BACKTRACKING_TOKENS = max(设置值, nextn+1)</code>(environ.py:139)——一轮验证中 draft 加上被推翻的 bonus token 最多让序列回退 nextn+1 = 6 个位置。</li>
      <li><b>ring 的长度就是 W+B</b>:<code>get_inference_swa_block_size = window_size + MAX_BACKTRACKING_TOKENS</code>(cache_engine.py:88-93),压缩状态 ring 同理 <code>ratio + max(0, B-1)</code>(cache_engine.py:130-133)。回退不擦除 ring,只是重写——ring 必须长到「回退后还剩满窗」。</li>
      <li><b>重放写入区必须覆盖 ring 需要的全部内容</b>:final chunk 在 compact 模式下写入「chunk 尾部 swa_block_size 段 ∩ 矩形」。要让 [N-(W+B), N) 全部落进矩形,必须 <code>KEEP ≥ W+B</code>——否则回退后窗口左端伸进矩形之外,那里要么从未写入、要么是陈旧数据。</li>
      <li><b>四处强制</b>:启动断言(deepinfer/worker/model_runner.py:106-113)、元数据断言(deepinfer/model_executor/model_metadata_utils.py:90-92)、C++ 每次构造输入的 TORCH_CHECK(csrc/engine/input_metadata/prepare_tensor_input_v4.cpp:355-357)、等价性脚本的入参检查(examples/yoco/yoco_equiv.py:384-385)。</li>
    </ol>
    <pre class="code"><span class="filepath">deepinfer/worker/model_runner.py:106-113</span>
<span class="k">self</span>.yoco_prefill_truncation_mode = envs.DEEPINFER_YOCO_PREFILL_TRUNCATION_MODE
<span class="k">if</span> <span class="k">self</span>.yoco_prefill_truncation_mode != <span class="s">"off"</span>:
    <span class="c"># 要保证截断长度至少有 window_size + backtracking,保证回退后仍然有足够 window size 的 swa 给到 decoder</span>
    <span class="k">assert</span> <span class="k">self</span>.window_size &gt; <span class="n">0</span>
    <span class="k">assert</span> <span class="k">self</span>.window_size + envs.DEEPINFER_MAX_BACKTRACKING_TOKENS &lt;= envs.DEEPINFER_YOCO_PREFILL_KEEP_TOKENS, (
        <span class="s">f"DEEPINFER_YOCO_PREFILL_KEEP_TOKENS ({envs.DEEPINFER_YOCO_PREFILL_KEEP_TOKENS}) must be &gt;= "</span>
        <span class="s">f"window_size ({self.window_size}) + DEEPINFER_MAX_BACKTRACKING_TOKENS ({envs.DEEPINFER_MAX_BACKTRACKING_TOKENS})"</span>
    )</pre>
    <div class="note">
      <b>数值自查(V4.1 默认)</b>:W=128(examples/yoco/yoco_equiv.py:1009 的 <code>--window 128「模型 SWA window_size (Wa)」</code>)、B≥6、KEEP=140 ⇒ 128+6=134 ≤ 140,余量 6。若把 <code>USE_NEXTN_DECODE</code> 调到 8,B 变 9,134 仍成立;但想缩 KEEP 就必须同步缩投机深度。benchmark 脚本纯测 prefill 时显式设 <code>DEEPINFER_MAX_BACKTRACKING_TOKENS=1</code>(examples/benchmark.py:164)即配合 <code>USE_NEXTN_DECODE=0</code> 的纯 prefill 场景。
    </div>
  </section>

  <!-- ================================================================ 11 -->
  <section>
    <h2 class="sec"><span class="num">11</span>CP 并行:「先 compact 再 CP」</h2>
    <p class="lede">Context Parallel 与截断的顺序问题是本特性最精巧的部分:DeepInfer 选择先在全局做 compact,再对 compact 序列做 zigzag mirror 切分。</p>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">⇄</span>为什么不能先切 CP</h3>
        <p>full CP-mirror 布局下每个 rank 持有的行交错;若先切再截,边界处 rank 间的行会撕裂,full→compact 映射无法用单一 gather 表达。先 compact 后,序列变短,zigzag 均衡性反而更好。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">⇉</span>边界重分布三步</h3>
        <p>CP&gt;1 时 <code>yoco_boundary_compact</code> 走三步:按 <code>yoco_cp_contrib_index</code> 选出本 rank 在 full-mirror 中仍存活的行(-1 为 pad)→ all-gather 拼接 → 用 <code>yoco_cp_boundary_index</code> 重排成本 rank 的 compact-mirror 顺序(deepinfer/model_executor/models/v4_modules/yoco.py:66-76)。</p>
      </div>
    </div>
    <p>配套的两个 CPU 标量由 <code>fill_yoco_consumer_cp_scalars</code> 计算(csrc/engine/input_metadata/prepare_tensor_input_v4.cpp:170-201):</p>
    <ul class="feat">
      <li><code>yoco_consumer_cp_mirror_len</code>:每序列 <code>2 * ceil(keep_len / 2cp)</code> 累加——compact 后再切 CP+pad 的总长;</li>
      <li><code>yoco_consumer_cp_contrib_pad_len</code>:各 rank「full CP-mirror 中存活行数」的最大值,即贡献缓冲的 pad 长度(per-rank kept 计数按 zigzag 的 <code>b ∈ {r, 2cp-1-r}</code> 两段区间与 clip 区间求交,cpp:184-193)。</li>
      <li>consumer 视图里还会用 compact cu_seqlens_q + 原始 cu_seqlens_k 复用 mirror kernel 重新 zigzag,得到 compact 行的 ks/ke(deepinfer/model_executor/input_metadata/yoco.py:136-157);该推导没有单元测试,由端到端等价性覆盖(<code>examples/yoco/run_yoco_equiv_l2.sh --cp N</code>,yoco.py:138-139 注释)。</li>
    </ul>
    <p>另一个 CP 相关的内存细节:compact + mirror CP 需要把 HC residual 传进层内,因此 userbuffer 的 per-token all-gather 上限要按 <code>hc_mult * hidden * 2</code> 抬高(deepinfer/model_executor/models/deepseek.py:417-418);mask 模式不做边界 gather,无此开销。此外 compact 视图会重建 <code>valid_token_mask = mirror_cp_index_c != -1</code>,pad 行经 gather OOB 得到垃圾值,与既有 CP pad 行语义一致(yoco.py:170-180)。</p>
  </section>

  <!-- ================================================================ 12 -->
  <section>
    <h2 class="sec"><span class="num">12</span>调度与成本感知:FlopsEstimator 的截断建模</h2>
    <p class="lede">截断不仅改变计算,也改变调度器看到的成本。FlopsEstimator 把「full 行 / consumer 行」分成两套每行系数,让 chunked prefill 的预算估算贴近真实。</p>
    <p>引擎把模式与 keep_tokens 直接喂给 estimator(deepinfer/engine/llm_engine.py:318-322),调度器在构造每请求元数据时逐个调用 <code>calc_flops(seqlen_q, seqlen_k, is_prompt, full_len, swa_valid_start)</code>(csrc/engine/scheduler.hpp:716)。核心的行区间收缩逻辑:</p>
    <pre class="code"><span class="filepath">csrc/engine/flops_estimator.hpp:259-277(query_ranges)</span>
<span class="k">const</span> QueryRange full{start, k, window_size &gt; <span class="n">0</span> ? pairs(start - swa_valid_start, k - swa_valid_start, <span class="n">1</span>, window_size) : <span class="n">0</span>};
QueryRange consumer = full;
<span class="k">if</span> (is_prompt &amp;&amp; (compact || has_truncated_swa)) {
    <span class="k">const int</span> cutoff = full_len - keep_tokens;
    <span class="c">// A fully clipped compact chunk still executes its last query row.</span>
    <span class="k">if</span> (compact)
        consumer.begin = std::clamp(cutoff, start, k - <span class="n">1</span>);      <span class="c">// ← 与 C++ clip_prefix 完全同式</span>
    <span class="k">const int</span> swa_start = std::max(swa_valid_start, cutoff);
    consumer.swa_pairs =
        window_size &gt; <span class="n">0</span> ? pairs(std::max(<span class="n">0</span>, consumer.begin - swa_start), std::max(<span class="n">0</span>, k - swa_start), <span class="n">1</span>, window_size) : <span class="n">0</span>;
}
<span class="k">return</span> {full, consumer};</pre>
    <ul class="feat">
      <li><b>两套每行系数</b>:Q/KV 投影按 <code>full_attn_per_row / consumer_attn_per_row</code> 分账——compact 时 consumer 的 Q 系数记到 consumer 侧(flops_estimator.hpp:183-199);MLP/router/HC/engram 亦按 producer/consumer 半区分(hpp:66-71)。</li>
      <li><b>边界层的额外 HC 开销被显式建模</b>:「The compact boundary adds (q - consumer_rows) * pre」——边界层对 full 输入多做一次 attn-norm(hpp:116-119),对应 decoder_layer.py:140 的 <code>consumer_full_hidden</code> 捕获。</li>
      <li><b>mask 模式也有 swa_pairs 收缩</b>(<code>has_truncated_swa</code> 覆盖 mask):可见域收窄省掉的 attention 对数被计入,虽然 MLP 等每行成本照付——这正是「mask 不省计算」的精确含义。</li>
      <li><b>调度器还接收 truncate_len</b>:llm_engine 把 <code>KEEP_TOKENS(compact 时,否则 0)</code> 传给 Scheduler 构造函数(deepinfer/engine/llm_engine.py:259-260、315),C++ 侧保存为成员(csrc/engine/scheduler.hpp:83-88、1167),用于调度期参考。</li>
    </ul>
  </section>

  <!-- ================================================================ 13 -->
  <section>
    <h2 class="sec"><span class="num">13</span>等价性验证:yoco_equiv 的 L1 / L2 双层防线</h2>
    <p class="lede">截断改动横跨 C++ 元数据、Python 视图、attention 与 cache 写入,仓库提供了从 metadata 到端到端 logprob 的完整验证链。</p>
    <table class="tbl">
      <tr><th style="width:10%">层级</th><th style="width:26%">命令</th><th style="width:22%">成本</th><th>验证内容</th></tr>
      <tr><td><b>L1</b></td><td><code>python examples/yoco/yoco_equiv.py mask-compact</code></td><td>单卡秒级、不加载权重</td><td>比较 SWA pivots、可见 key、store slot、压缩 key 范围;场景矩阵覆盖 N 与 keep 的大小关系、chunk 跨界、矩形切进历史窗口、多请求混长(yoco_equiv.py:79-113)</td></tr>
      <tr><td><b>L2</b></td><td><code>examples/yoco/run_yoco_equiv_l2.sh --model_name &lt;v41-hf&gt; [--cp N]</code></td><td>8 卡 + V4.1 HF ckpt</td><td>固定 teacher-forcing 轨迹,mask 与 compact 的 logprob / top-K 逐位比较;<code>--mtp N</code> 额外逐位比较 DFlash confidence(直接探测 main cache 写入等价性)</td></tr>
    </table>
    <p style="font-size:12.5px;color:var(--muted)">表格依据 examples/yoco/README.md。L1 的解析参考把语义钉死:<code>可见域 = 滑窗 [pos-W+1, pos] ∩ 矩形 [N-keep, N)</code>(yoco_equiv.py:116-119);并断言 compaction 单行可见 key 数不超过 window(index 宽度收窄到 W,yoco_equiv.py:355-357)、占位与矩形外 token 的 store slot 为 -1(yoco_equiv.py:361-367)。CLI 默认值即 V4.1 语义:<code>--keep-tokens 140 --window 128 --backtracking 1</code>(yoco_equiv.py:1008-1010)。</p>
    <p>benchmark 侧则提供了生产用法与对照开关:<code>--yoco_clip</code>(裸给即 140,0=off)、<code>--yoco_clip_mask</code>(mask 模式:「可见域与 compact 完全相同,但 consumer 层照常算全部 token,不省计算。用于数值对齐/排查」,examples/benchmark.py:43-49);截断开启时强制 <code>DEEPINFER_PREFILL_STORE_EXTRA_STATE=1</code>(benchmark.py:154-157)。状态槽位侧另有单测 <code>test_yoco_swa_disk_and_ce</code>:PE(compact)与 CE(off)布局一致、落盘只保留 stored 区、传输含 dropped 区(tests/worker/test_state_cache_ops.py:656-720)。</p>
  </section>

  <!-- ================================================================ 14 -->
  <section>
    <h2 class="sec"><span class="num">14</span>配置项与推荐值</h2>
    <p class="lede">与本特性直接相关的全部环境变量(定义集中在 deepinfer/environ.py)。</p>
    <table class="tbl">
      <tr><th style="width:34%">环境变量</th><th style="width:14%">默认</th><th>含义与推荐</th></tr>
      <tr>
        <td><code>DEEPINFER_YOCO_PREFILL_TRUNCATION_MODE</code></td><td><code>off</code></td>
        <td>三态:<code>off / mask / compact</code>(environ.py:195)。<b>推荐 <code>compact</code></b>(V4.1 默认生产配置,README.md:25);<code>mask</code> 仅用于对齐排查;非 YOCO 模型必须 <code>off</code>(启用需 <code>n_prefill_layer &lt; n_layer</code> 且 <code>&gt; 0</code>,model_metadata_utils.py:90-91)</td>
      </tr>
      <tr>
        <td><code>DEEPINFER_YOCO_PREFILL_KEEP_TOKENS</code></td><td><code>0</code>(必须显式设)</td>
        <td>保留的末尾 query token 数(environ.py:198)。<b>推荐 140</b>;硬约束 <code>≥ window_size + MAX_BACKTRACKING_TOKENS</code>(= 128+6 = 134)。无对齐要求(两种模式的 SWA index 都按 W 宽度展开,yoco_equiv.py:384)</td>
      </tr>
      <tr>
        <td><code>DEEPINFER_USE_NEXTN_DECODE</code></td><td><code>5</code></td>
        <td>投机解码最大深度(environ.py:136)。它通过回退下界间接决定 KEEP 的最小值;调大深度要复核 128+(nextn+1) ≤ KEEP</td>
      </tr>
      <tr>
        <td><code>DEEPINFER_MAX_BACKTRACKING_TOKENS</code></td><td><code>max(设置值, nextn+1)</code></td>
        <td>最大回退 token 数(environ.py:139)。同时决定 SWA ring 长度 W+B(cache_engine.py:93)与压缩 ring <code>ratio+B-1</code>(cache_engine.py:133);修改后需 <code>clear_compress_block_size_cache()</code>(cache_engine.py:136-138)</td>
      </tr>
      <tr>
        <td><code>DEEPINFER_PREFILL_STORE_EXTRA_STATE</code></td><td>关</td>
        <td>kvstore ring 额外多存以对齐落盘粒度(environ.py:170)。截断开启时建议开(benchmark 强制开,benchmark.py:156-157);开启后 ring = W+B+128+KEEP</td>
      </tr>
      <tr>
        <td><code>DEEPINFER_PREFILL_STORE_EXTRA_SIZE</code></td><td><code>128</code></td>
        <td>EXTRA_STATE 的基础余量(environ.py:171),等于 <code>KVSTORE_GRAIN</code>(cache_engine.py:32)</td>
      </tr>
      <tr>
        <td><code>DEEPINFER_NUM_STATE_SLOTS_RATIO</code></td><td><code>1.2</code></td>
        <td>状态槽位池放大系数:<code>max_num_seqs × 1.2 + 1</code>(environ.py:169、cache_engine.py:201-202)。SWA ring 与压缩 state 都住在这里</td>
      </tr>
      <tr>
        <td><code>DEEPINFER_PROMPT_LOGPROBS</code>(行为)</td><td>—</td>
        <td>截断开启时请求级 <code>prompt_logprobs</code> 被强制关闭并告警(llm_engine.py:529-536);C++ 侧同样 TORCH_CHECK(prepare_sample.cpp:177-179)</td>
      </tr>
    </table>
    <div class="note good">
      <b>V4.1-Flash 一行配置</b>:<code>DEEPINFER_YOCO_PREFILL_TRUNCATION_MODE=compact DEEPINFER_YOCO_PREFILL_KEEP_TOKENS=140</code>(其余保持默认即可满足 140 ≥ 128+6)。对应 benchmark 用法 <code>examples/benchmark.py --yoco_clip</code>(裸给即 140)。
    </div>
  </section>

  <!-- ================================================================ 15 -->
  <section>
    <h2 class="sec"><span class="num">15</span>限制与注意事项</h2>
    <p class="lede">从代码断言与注释中整理的边界条件,接手调参或排障前值得通读。</p>
    <ul class="feat">
      <li><b>prompt_logprobs 不可用</b>:mask 与 compact 均强制关闭——「compaction cannot compute clipped rows; mask returns degenerate logp for pre-rectangle tokens」(deepinfer/engine/llm_engine.py:529-536)。</li>
      <li><b>Engram 不能落在 consumer 半区</b>:「yoco consumer compaction does not support Engram in consumer layers yet」(deepseek.py:136-138);边界层也断言 <code>self.engram is None</code>(decoder_layer.py:136)。</li>
      <li><b>DFlash target 层必须同侧</b>:要么全在 consumer 半区、要么全不在(deepseek.py:129-135);全在 consumer 半区时 dflash_input 同步切 compact 行(deepseek.py:199-205)。</li>
      <li><b>抢占结果允许变化</b>:「NOTE 开启 yoco 截断时,允许抢占导致的结果变化」(llm_engine.py:888)——重算路径 swa_valid_start clamp 语义正确,但数值不保证与未抢占一致。</li>
      <li><b>disk 命中依赖截断</b>:存在 dropped SWA 层的模型从 store 恢复时必须开截断(cache_engine.py:836-838),因为 consumer SWA 只能靠重放重建。</li>
      <li><b>compact 的 CPU/显存权衡</b>:DeepEP dispatch 关闭 do_cpu_sync 避免 CPU 瓶颈,代价是额外 GPU 显存(mlp.py:482-485);边界 gather 的 HC lazy 数据同样要求 residual 未被 engram 清空(yoco.py:108)。</li>
      <li><b>等价性验证的约束</b>:L2 要求兼容的 V4.1 YoCo HF ckpt(<code>n_prefill_layer &lt; n_layer</code>)、两轮运行除模式外所有 <code>DEEPINFER_*</code> 一致(examples/yoco/README.md)。</li>
      <li><b>keep_tokens 无对齐要求</b>:两种模式的 SWA index 都以 window_size 宽度展开(yoco_equiv.py:384),不必凑 2 的幂;但增大 KEEP 会线性增加 consumer prefill 行数与 EXTRA_STATE ring 长度。</li>
    </ul>
  </section>

  <!-- ================================================================ 16 -->
  <section>
    <h2 class="sec"><span class="num">16</span>总结</h2>
    <p class="lede">一个「只重放有界后缀」的想法,把 YOCO 解码器的 prefill 成本从 O(N) 压到 O(KEEP),代价是必须同时伺候好滑动窗口与投机回退两套语义。</p>
    <div class="timeline">
      <div class="tl-item reveal">
        <div class="tl-date">配置层 · environ.py:194-201</div>
        <div class="tl-body">两个环境变量:三态模式 + 保留长度;默认关闭、显式启用;约束写进 docstring。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">元数据层 · prepare_tensor_input_v4.cpp:129-360</div>
        <div class="tl-body">每请求算 clip_prefix(锚定序列末端矩形),每行算「滑窗 ∩ 矩形 ∩ valid_start」的 pivots;compact 版 varlen 边界、ks/ke、ring 槽位(-1 占位)一次产出;约束 TORCH_CHECK 兜底。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">模型层 · deepseek.py:190-207 → decoder_layer.py:134-152 → yoco.py:55-123</div>
        <div class="tl-body">边界层切 consumer 视图;hidden / residual(HC lazy)/ topk 全部 gather 到 compact 布局;full 副本产出 shared hidden。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">attention 层 · attn.py:537-855</div>
        <div class="tl-body">压缩 KV 走 _store_yoco_full_kv 全量补写(query 裁了、KV 没裁);SWA 先 load 后 store,占位行整行 -1、不写 ring。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">缓存层 · cache_engine.py:88-306, 836-838</div>
        <div class="tl-body">ring = W+B(+落盘余量);consumer SWA 住 dropped 区、不落盘,恢复完全依赖重放——这正是「有界重放」名字的另一半含义。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">约束闭环 · W+B ≤ KEEP</div>
        <div class="tl-body">DSpark 回退 B(nextn+1)后窗口仍满 W;四处断言联动,调投机深度必须复核 KEEP。</div>
      </div>
    </div>
    <div class="grid c3">
      <div class="card reveal">
        <h3><span class="ico">✓</span>收益</h3>
        <p>consumer 半区的 prefill 行数从 N 收缩到 ≤ KEEP+占位;attention 对数、Q/KV 投影、MoE/HC/router 全部按行缩减;FlopsEstimator 同步感知,调度预算不失真。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">=</span>正确性</h3>
        <p>mask/compact 同一可见域公式,可逐位对齐;L1 场景矩阵 + L2 端到端 logprob(含 CP、含 MTP confidence)双层验证;状态槽位落盘/迁移有专项单测。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">!</span>代价</h3>
        <p>prompt_logprobs 失去支持;Engram/DFlash 半区限制;抢占结果允许漂移;compact 关闭 DeepEP CPU sync 换来额外显存;调参必须维护 W+B ≤ KEEP 不等式。</p>
      </div>
    </div>
  </section>

  <div class="pgnav">
    <span>DeepInfer 代码分析系列 · 由 ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/deepinfer/">← 返回系列总览</a></span>
  </div>
<script>
// 滚动显现动画
const io=new IntersectionObserver(es=>{es.forEach(e=>{if(e.isIntersecting){e.target.classList.add('on');io.unobserve(e.target)}})},{threshold:.12});
document.querySelectorAll('.reveal').forEach(el=>io.observe(el));
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>异步调度:零开销批调度器</title><link>https://hccl.club/docs/inference-engines/deepinfer/05-async-scheduling/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/05-async-scheduling/</guid><description><![CDATA[<div class="fwdoc">
<style>
.fwdoc{--bg:#0b1020; --bg2:#0f1729; --panel:#141d33; --panel2:#1a2440;
  --border:#263352; --text:#dbe4f5; --muted:#8ea0c2;
  --accent:#4f8cff; --accent2:#22d3ee; --good:#34d399; --warn:#fbbf24; --bad:#f87171; --purple:#a78bfa;
  --code-bg:#0d1424; --radius:14px;
  --serif:"Noto Serif SC","Songti SC",serif;}
.fwdoc *{box-sizing:border-box;margin:0;padding:0}
.fwdoc{background:linear-gradient(160deg,var(--bg) 0%,var(--bg2) 60%,#0a0f1e 100%);color:var(--text);
  font-family:"PingFang SC","Microsoft YaHei","Segoe UI",system-ui,sans-serif;line-height:1.75;}
.fwdoc{flex:1;min-width:0;padding:36px 48px 80px}
@media(max-width:960px){.fwdoc{padding:24px 18px 60px}}
.fwdoc .hero{position:relative;border-radius:var(--radius);overflow:hidden;padding:46px 44px;margin-bottom:34px;
  background:radial-gradient(1200px 400px at 15% -20%,rgba(79,140,255,.28),transparent 60%),
             radial-gradient(900px 380px at 95% 0%,rgba(167,139,250,.20),transparent 55%),
             linear-gradient(135deg,#16213e,#101a30);border:1px solid var(--border)}
.fwdoc .hero .crumb{font-size:12px;color:var(--accent2);letter-spacing:1px;margin-bottom:12px}
.fwdoc .hero h1{font-size:34px;color:#fff;font-weight:800;letter-spacing:.5px;margin-bottom:10px}
.fwdoc .hero p.desc{color:var(--muted);max-width:760px;font-size:15px}
.fwdoc .hero .tags{margin-top:18px;display:flex;gap:10px;flex-wrap:wrap}
.fwdoc .hero .tag{font-size:12px;padding:4px 14px;border-radius:999px;border:1px solid var(--border);
  background:rgba(79,140,255,.10);color:var(--accent2)}
.fwdoc .tag.good{border-color:rgba(52,211,153,.4);color:var(--good);background:rgba(52,211,153,.08)}
.fwdoc .tag.warn{border-color:rgba(251,191,36,.4);color:var(--warn);background:rgba(251,191,36,.08)}
.fwdoc section{margin-bottom:44px;scroll-margin-top:20px}
.fwdoc h2.sec{display:flex;align-items:center;gap:12px;font-size:23px;color:#fff;margin-bottom:6px;padding-bottom:10px;border-bottom:1px solid var(--border)}
.fwdoc h2.sec .num{display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:10px;flex-shrink:0;
  background:linear-gradient(135deg,var(--accent),var(--purple));color:#fff;font-size:15px;font-weight:800}
.fwdoc .lede{color:var(--muted);font-size:14px;margin-bottom:20px}
.fwdoc .grid{display:grid;gap:18px}
.fwdoc .grid.c2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}
.fwdoc .grid.c3{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}
.fwdoc .card{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:var(--radius);padding:22px 24px;transition:transform .3s,border-color .3s,box-shadow .3s}
.fwdoc .card:hover{transform:translateY(-3px);border-color:rgba(79,140,255,.55);box-shadow:0 12px 34px -14px rgba(79,140,255,.35)}
.fwdoc .card h3{font-size:16.5px;color:#fff;margin-bottom:8px;display:flex;align-items:center;gap:9px}
.fwdoc .card h3 .ico{width:26px;height:26px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;
  background:rgba(79,140,255,.16);font-size:14px;flex-shrink:0}
.fwdoc .card p{font-size:13.5px;color:var(--muted)}
.fwdoc .card p code,.fwdoc .inline-code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1.5px 7px;border-radius:6px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px}
.fwdoc ul.feat{list-style:none}
.fwdoc ul.feat li{padding:9px 0 9px 30px;position:relative;font-size:14px;color:var(--text);border-bottom:1px dashed rgba(38,51,82,.6)}
.fwdoc ul.feat li:last-child{border-bottom:none}
.fwdoc ul.feat li::before{content:"▸";position:absolute;left:8px;color:var(--accent);font-weight:700;animation:fw-blink 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
@keyframes fw-blink{0%,100%{opacity:.35}50%{opacity:1}}
.fwdoc pre.code{background:var(--code-bg);border:1px solid var(--border);border-radius:12px;padding:18px 20px;
  overflow-x:auto;font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px;line-height:1.65;margin:14px 0;position:relative}
.fwdoc pre.code::before{content:"● ● ●";display:block;color:#3a4a70;font-size:10px;letter-spacing:3px;margin-bottom:10px}
.fwdoc pre.code .k{color:#c792ea}
.fwdoc pre.code .s{color:#89ddff}
.fwdoc pre.code .c{color:#5d7294;font-style:italic}
.fwdoc pre.code .f{color:#82aaff}
.fwdoc pre.code .n{color:#f78c6c}
.fwdoc pre.code .h{color:#ffcb6b}
.fwdoc .filepath{font-family:"JetBrains Mono",Consolas,monospace;font-size:11.5px;color:var(--accent2);
  background:rgba(34,211,238,.08);border:1px solid rgba(34,211,238,.25);border-radius:6px;padding:2px 10px;display:inline-block;margin-bottom:4px}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border)}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px}
.fwdoc table.tbl td{padding:10px 14px;border-top:1px solid var(--border);color:var(--text);vertical-align:top}
.fwdoc table.tbl tr{transition:background .2s}
.fwdoc table.tbl tr:nth-child(even) td{background:rgba(20,29,51,.5)}
.fwdoc table.tbl tr:hover td{background:rgba(79,140,255,.10)}
.fwdoc table.tbl td code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;font-family:Consolas,monospace;font-size:12px}
.fwdoc .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px}
.fwdoc .badge.merged{background:rgba(52,211,153,.15);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.open{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.closed{background:rgba(248,113,113,.13);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.nccl{background:rgba(251,191,36,.12);color:var(--warn);border:1px solid rgba(251,191,36,.4)}
.fwdoc .badge.hccl{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .badge.deepep{background:rgba(34,211,238,.12);color:var(--accent2);border:1px solid rgba(34,211,238,.4)}
.fwdoc .reveal{opacity:0;transform:translateY(26px);transition:opacity .7s cubic-bezier(.2,.7,.3,1),transform .7s cubic-bezier(.2,.7,.3,1)}
.fwdoc .reveal.on{opacity:1;transform:none}
.fwdoc .reveal.d1{transition-delay:.12s}
.fwdoc .reveal.d2{transition-delay:.24s}
.fwdoc .reveal.d3{transition-delay:.36s}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:20px;margin:18px 0;position:relative;overflow:hidden}
.fwdoc .figure .cap{text-align:center;font-size:12.5px;color:var(--muted);margin-top:10px}
.fwdoc .figure svg{width:100%;height:auto;display:block}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-flow 1.2s linear infinite}
@keyframes fw-flow{to{stroke-dashoffset:-14}}
.fwdoc .pulse{animation:fw-pulse 2s ease-in-out infinite;transform-origin:center}
@keyframes fw-pulse{0%,100%{opacity:.45;transform:scale(1)}50%{opacity:1;transform:scale(1.06)}}
.fwdoc .node-gpu{fill:#16233f;stroke:#4f8cff;stroke-width:1.6;rx:10}
.fwdoc .node-gpu-title{fill:#dbe4f5;font-size:13px;font-weight:700}
.fwdoc .token-dot{fill:#22d3ee}
.fwdoc .barrow{filter:drop-shadow(0 0 6px rgba(34,211,238,.7))}
.fwdoc .timeline{position:relative;padding-left:34px}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .tl-item{position:relative;margin-bottom:20px}
.fwdoc .tl-item::before{content:"";position:absolute;left:-30px;top:7px;width:12px;height:12px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.18);animation:fw-pulse 2.4s infinite}
.fwdoc .tl-item .tl-date{font-size:11.5px;color:var(--accent2);letter-spacing:.5px}
.fwdoc .tl-item .tl-body{font-size:13.5px;color:var(--text);margin-top:3px}
.fwdoc .note{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13px;color:var(--text);margin:16px 0}
.fwdoc .note.warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .note.good{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .note b{color:#fff}
.fwdoc .pgnav{margin-top:60px;padding-top:20px;border-top:1px solid var(--border);color:#5a6b92;font-size:12px;
  display:flex;justify-content:space-between;flex-wrap:wrap;gap:10px}
.fwdoc .pgnav a{color:var(--accent2);text-decoration:none}
.fwdoc .beltA{animation:fw-beltA 7s linear infinite}
.fwdoc .beltB{animation:fw-beltB 5s linear infinite}
@keyframes fw-beltA{to{transform:translateX(-460px)}}
@keyframes fw-beltB{to{transform:translateX(-380px)}}
.fwdoc .btxt{fill:#0b1020;font-size:11.5px;font-weight:700;font-family:"PingFang SC","Microsoft YaHei",sans-serif}
.fwdoc .btxt2{fill:#062024;font-size:11.5px;font-weight:700;font-family:"PingFang SC","Microsoft YaHei",sans-serif}
.fwdoc .bubble{animation:fw-bub 2.2s ease-in-out infinite}
@keyframes fw-bub{0%,100%{opacity:.45}50%{opacity:1}}
.fwdoc .softglow{animation:fw-sg 3.5s ease-in-out infinite}
@keyframes fw-sg{0%,100%{opacity:.88}50%{opacity:1}}
.fwdoc .lanelbl{fill:#8ea0c2;font-size:12px;font-weight:700}
.fwdoc .modttl{fill:#fff;font-size:15px;font-weight:800}
.fwdoc .ann{fill:#f87171;font-size:11px;font-weight:700}
.fwdoc .ann2{fill:#34d399;font-size:11px;font-weight:700}
.fwdoc .tick{stroke:#263352;stroke-width:1}
.fwdoc .mqcell{animation:fw-cellcyc 8s infinite}
@keyframes fw-cellcyc{0%{fill:#182742;stroke:#263352}
            1.5%{fill:#0e4a5c;stroke:#22d3ee}
            12%{fill:#0e4a5c;stroke:#22d3ee}
            50%{fill:#14382b;stroke:#34d399}
            82%{fill:#182742;stroke:#263352}
            100%{fill:#182742;stroke:#263352}}
.fwdoc .wfl{animation:fw-wfl 8s infinite}
@keyframes fw-wfl{0%{fill:#0d1424}1.5%{fill:#22d3ee}50%{fill:#0e7490}82%{fill:#0d1424}100%{fill:#0d1424}}
.fwdoc .rfl0{animation:fw-rfl0 8s infinite}
.fwdoc .rfl1{animation:fw-rfl1 8s infinite}
.fwdoc .rfl2{animation:fw-rfl2 8s infinite}
@keyframes fw-rfl0{0%,50%{fill:#0d1424}52%,66%{fill:#34d399}72%,100%{fill:#0d1424}}
@keyframes fw-rfl1{0%,56%{fill:#0d1424}58%,72%{fill:#34d399}78%,100%{fill:#0d1424}}
@keyframes fw-rfl2{0%,62%{fill:#0d1424}64%,78%{fill:#34d399}84%,100%{fill:#0d1424}}
.fwdoc .wcur{animation:fw-wmove 8s infinite}
.fwdoc .rcur{animation:fw-wmove 8s infinite}
@keyframes fw-wmove{0%,12.4%{transform:translateX(0)}
            12.5%,24.9%{transform:translateX(82px)}
            25%,37.4%{transform:translateX(164px)}
            37.5%,49.9%{transform:translateX(246px)}
            50%,62.4%{transform:translateX(328px)}
            62.5%,74.9%{transform:translateX(410px)}
            75%,87.4%{transform:translateX(492px)}
            87.5%,99.9%{transform:translateX(574px)}
            100%{transform:translateX(0)}}
.fwdoc .mqflow{stroke-dasharray:7 7;animation:fw-mqf 1.1s linear infinite}
@keyframes fw-mqf{to{stroke-dashoffset:-14}}
.fwdoc .drv{animation:fw-drvp 2.4s ease-in-out infinite}
@keyframes fw-drvp{0%,100%{opacity:.75}50%{opacity:1}}
.fwdoc .sm{fill:#8ea0c2;font-size:10.5px}
.fwdoc .smw{fill:#dbe4f5;font-size:11px;font-weight:700}
.fwdoc .zmqbox{animation:fw-zq 4s ease-in-out infinite}
@keyframes fw-zq{0%,100%{opacity:.55}50%{opacity:1}}
.fwdoc .h2df{stroke-dasharray:8 6;animation:fw-h2a 1s linear infinite}
@keyframes fw-h2a{to{stroke-dashoffset:-14}}
.fwdoc .d2hf{stroke-dasharray:8 6;animation:fw-d2a 1.4s linear infinite}
@keyframes fw-d2a{to{stroke-dashoffset:14}}
.fwdoc .kbox{animation:fw-kb 2.6s ease-in-out infinite}
@keyframes fw-kb{0%,100%{opacity:.6}50%{opacity:1}}
.fwdoc .evt{animation:fw-ev 4s ease-in-out infinite}
@keyframes fw-ev{0%,55%{opacity:.25}60%,80%{opacity:1}90%,100%{opacity:.25}}
.fwdoc .sweep{animation:fw-sw 6s linear infinite}
@keyframes fw-sw{to{transform:translateX(660px)}}
.fwdoc .boxT{fill:#dbe4f5;font-size:12px;font-weight:700}
.fwdoc .boxS{fill:#8ea0c2;font-size:10.5px}
.fwdoc .banner{animation:fw-bn 3s ease-in-out infinite}
@keyframes fw-bn{0%,100%{opacity:.7}50%{opacity:1}}
.fwdoc .fl2{stroke-dasharray:8 6;animation:fw-fa 1.1s linear infinite}
@keyframes fw-fa{to{stroke-dashoffset:-14}}
.fwdoc .kn{animation:fw-kn 2.8s ease-in-out infinite}
@keyframes fw-kn{0%,100%{opacity:.45}50%{opacity:1}}
.fwdoc .pad{animation:fw-pd 2s ease-in-out infinite}
@keyframes fw-pd{0%,100%{opacity:.35}50%{opacity:1}}
.fwdoc .ovl{animation:fw-ov 2.4s ease-in-out infinite}
@keyframes fw-ov{0%,100%{opacity:.25}50%{opacity:.7}}
.fwdoc .t1{fill:#dbe4f5;font-size:12px;font-weight:700}
.fwdoc .t2{fill:#8ea0c2;font-size:10.5px}
.fwdoc .hdr{fill:#fff;font-size:14px;font-weight:800}
/* ===== 导入面板附加样式 ===== */
.fwdoc{border-radius:14px;margin:18px 0}
.fwdoc table.tbl{display:block;overflow-x:auto;max-width:100%}
@media (prefers-reduced-motion:reduce){
.fwdoc *,.fwdoc *::before,.fwdoc *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
.fwdoc .reveal{opacity:1!important;transform:none!important}
}

</style>

<!-- ============================================================ -->
  <section id="s1">
    <h2 class="sec"><span class="num">1</span>概述:异步调度解决什么问题</h2>
    <p class="lede">在大批量 decode 场景下单步 GPU 计算可能只有几毫秒到几十毫秒,而 Python 侧的批调度(选 batch、构造元数据、H2D 拷贝、处理上一步输出)同样要花毫秒级——同步引擎里这两段串行执行,GPU 会在每个 step 之间出现"空泡"(bubble)。</p>

    <div class="figure">
      <svg viewBox="0 0 920 500" role="img" aria-label="同步模式与 ZOS 模式的 CPU/GPU 时间线对比动画">
        <defs>
          <linearGradient id="gBlue" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#2b5fd9"/><stop offset="1" stop-color="#4f8cff"/></linearGradient>
          <linearGradient id="gPurp" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#7c5fd9"/><stop offset="1" stop-color="#a78bfa"/></linearGradient>
          <linearGradient id="gCyan" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#0e7490"/><stop offset="1" stop-color="#22d3ee"/></linearGradient>
          <linearGradient id="gDim" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#243350"/><stop offset="1" stop-color="#2c3f66"/></linearGradient>
          <pattern id="hatch" width="10" height="10" patternTransform="rotate(45)" patternUnits="userSpaceOnUse">
            <rect width="10" height="10" fill="#2a1620"/><line x1="0" y1="0" x2="0" y2="10" stroke="#f87171" stroke-width="2.4" opacity=".55"/>
          </pattern>
          <clipPath id="winA"><rect x="112" y="58" width="790" height="140" rx="10"/></clipPath>
          <clipPath id="winB"><rect x="112" y="300" width="790" height="140" rx="10"/></clipPath>
        </defs>

        <!-- ============ 模式 A:同步 ============ -->
        <text class="modttl" x="20" y="36">同步模式(传统引擎)</text>
        <text x="230" y="36" fill="#5a6b92" font-size="11.5">CPU 调度与 GPU 计算串行,GPU 每步出现空泡</text>
        <text class="lanelbl" x="24" y="102">CPU 泳道</text>
        <text class="lanelbl" x="24" y="102" opacity="0">.</text>
        <text class="lanelbl" x="24" y="168">GPU 泳道</text>
        <rect x="112" y="78" width="790" height="46" rx="9" fill="#101a30" stroke="#1d2946"/>
        <rect x="112" y="140" width="790" height="46" rx="9" fill="#101a30" stroke="#1d2946"/>
        <g clip-path="url(#winA)">
          <g class="beltA">
            <!-- 第 1 份周期(460 宽) -->
            <g>
              <rect class="softglow" x="118" y="84" width="164" height="34" rx="7" fill="url(#gBlue)"/>
              <text class="btxt" x="152" y="105">CPU 调度 schedule</text>
              <rect class="softglow" x="300" y="84" width="140" height="34" rx="7" fill="url(#gPurp)"/>
              <text class="btxt" x="322" y="105">处理输出</text>
              <rect class="bubble" x="118" y="146" width="176" height="34" rx="7" fill="url(#hatch)" stroke="#f87171" stroke-width="1.2"/>
              <text class="ann" x="152" y="167">GPU 空泡 ▂▂▂</text>
              <rect class="softglow" x="298" y="146" width="268" height="34" rx="7" fill="url(#gCyan)"/>
              <text class="btxt2" x="356" y="167">forward + sample</text>
            </g>
            <!-- 第 2 份周期,保证循环无缝 -->
            <g transform="translate(460,0)">
              <rect class="softglow" x="118" y="84" width="164" height="34" rx="7" fill="url(#gBlue)"/>
              <text class="btxt" x="152" y="105">CPU 调度 schedule</text>
              <rect class="softglow" x="300" y="84" width="140" height="34" rx="7" fill="url(#gPurp)"/>
              <text class="btxt" x="322" y="105">处理输出</text>
              <rect class="bubble" x="118" y="146" width="176" height="34" rx="7" fill="url(#hatch)" stroke="#f87171" stroke-width="1.2"/>
              <text class="ann" x="152" y="167">GPU 空泡 ▂▂▂</text>
              <rect class="softglow" x="298" y="146" width="268" height="34" rx="7" fill="url(#gCyan)"/>
              <text class="btxt2" x="356" y="167">forward + sample</text>
            </g>
          </g>
        </g>
        <text class="ann" x="120" y="228">▲ 空泡 = 调度 + H2D + 输出处理的 CPU 时间,批量 decode 下可占单步 20%~40%</text>

        <!-- ============ 模式 B:ZOS ============ -->
        <text class="modttl" x="20" y="278">ZOS 异步模式(DeepInfer 默认)</text>
        <text x="300" y="278" fill="#5a6b92" font-size="11.5">step N 在 GPU 计算时,step N+1 已在 CPU 调度;两条泳道任务块交错,GPU 连续执行</text>
        <text class="lanelbl" x="24" y="344">CPU 泳道</text>
        <text class="lanelbl" x="24" y="410">GPU 泳道</text>
        <rect x="112" y="320" width="790" height="46" rx="9" fill="#101a30" stroke="#1d2946"/>
        <rect x="112" y="382" width="790" height="46" rx="9" fill="#101a30" stroke="#1d2946"/>
        <g clip-path="url(#winB)">
          <g class="beltB">
            <!-- 第 1 份周期(380 宽) -->
            <g>
              <rect class="softglow" x="118" y="326" width="132" height="34" rx="7" fill="url(#gBlue)"/>
              <text class="btxt" x="146" y="347">调度 N+1</text>
              <rect class="softglow" x="254" y="326" width="122" height="34" rx="7" fill="url(#gPurp)"/>
              <text class="btxt" x="274" y="347">处理 N 输出</text>
              <rect class="softglow" x="380" y="326" width="104" height="34" rx="7" fill="url(#gDim)"/>
              <text class="btxt" x="398" y="347" fill="#9fb3d9">GC/统计</text>
              <rect class="softglow" x="118" y="388" width="236" height="34" rx="7" fill="url(#gCyan)"/>
              <text class="btxt2" x="190" y="409">forward N</text>
              <rect class="softglow" x="356" y="388" width="128" height="34" rx="7" fill="url(#gCyan)" opacity=".82"/>
              <text class="btxt2" x="386" y="409">sample N</text>
            </g>
            <!-- 第 2 份周期 -->
            <g transform="translate(380,0)">
              <rect class="softglow" x="118" y="326" width="132" height="34" rx="7" fill="url(#gBlue)"/>
              <text class="btxt" x="146" y="347">调度 N+1</text>
              <rect class="softglow" x="254" y="326" width="122" height="34" rx="7" fill="url(#gPurp)"/>
              <text class="btxt" x="274" y="347">处理 N 输出</text>
              <rect class="softglow" x="380" y="326" width="104" height="34" rx="7" fill="url(#gDim)"/>
              <text class="btxt" x="398" y="347" fill="#9fb3d9">GC/统计</text>
              <rect class="softglow" x="118" y="388" width="236" height="34" rx="7" fill="url(#gCyan)"/>
              <text class="btxt2" x="190" y="409">forward N</text>
              <rect class="softglow" x="356" y="388" width="128" height="34" rx="7" fill="url(#gCyan)" opacity=".82"/>
              <text class="btxt2" x="386" y="409">sample N</text>
            </g>
          </g>
        </g>
        <text class="ann2" x="120" y="468">▲ GPU 泳道被 forward/sample 完全填满:调度、输出处理、GC 全部被推到 CPU 泳道与 GPU 计算重叠的时间窗内</text>
        <line x1="112" y1="248" x2="902" y2="248" stroke="#263352" stroke-width="1" stroke-dasharray="4 4"/>
      </svg>
      <div class="cap">图 1 · 引擎时间线:上为同步模式(CPU 调度期间 GPU 空泡),下为 ZOS 模式(两条泳道任务块交错滑动,GPU 连续执行)——时间轴向右,任务块随传送带左移表示时间流逝</div>
    </div>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🕳️</span>问题:CPU 调度停顿 GPU</h3>
        <p>同步引擎的一个 step 是严格串行的:<code>scheduler.schedule()</code>(纯 CPU)→ 构造 <code>InputMetadata</code> 并 H2D → launch forward → launch sample → <b>同步等 GPU 完成</b> → CPU 处理输出 → 进入下一个 step。每一段 CPU 工作都是 GPU 的空闲时间。DSpark 投机解码(<code>DEEPINFER_USE_NEXTN_DECODE</code> 默认 5,environ.py:136)把单步 token 数放大数倍后,这个问题反而被稀释;但在大批量纯 decode 下,调度停顿直接吃掉百分之几到几十的吞吐。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧩</span>解法:三根支柱</h3>
        <p>DeepInfer 的答案是把"调度"从 GPU 的关键路径上整个拿走:<b>(1) launch 即返回</b>——forward/sample 只异步提交 kernel,两处函数都注明 "must NOT contain any cuda synchronize"(model_runner.py:317、344-346),并用 <code>forbid_cuda_sync()</code> 守卫强制(utils.py:119);<b>(2) 后处理延后一步</b>——decode 步的输出处理被存进 <code>prev_step_state</code>,挪到下一步 forward 之后做(worker.py:182-187);<b>(3) 控制面全 CPU</b>——调度器 DP 投票走 gloo CPU 组(llm_engine.py:313),driver→worker 的方法分发走共享内存(base.py:298-300)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">✅</span>默认开启,按引擎类型分流</h3>
        <p><code>EngineArgs.__post_init__</code> 用 <code>os.environ.setdefault</code> 注入默认值(arg_utils.py:51-55),依据是 <code>EngineType.default_zero_overhead_scheduling</code>:<code>NORMAL</code>/<code>COMPLETION</code> 引擎默认 <code>1</code>,<code>PROMPT</code> 引擎默认 <code>0</code>(engine_type.py:15-17)。原因在 worker.py:183 的分支里:prompt 步总是当场 post-process,延迟处理对 prefill 无收益。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">⚖️</span>代价:元数据滞后一步</h3>
        <p>CPU 调度 step N+1 时,step N 的采样 token 还在 GPU 上——CPU 侧的 <code>seqlens_q/k</code> 因此滞后一步,需要在 GPU 上用上一步的采样输出"修正"(<code>_correct_seqlens_qk</code>,worker.py:191-245);模型的最大位置预算也要为在途 step 预留 <code>nextn + (nextn+1)</code> 个 token(config.py:14)。这些代价换来的就是 GPU 泳道上的零空泡。</p>
      </div>
    </div>

    <div class="note">
      <b>术语约定:</b>代码注释与文件名中使用 <b>ZOS</b>(zero-overhead scheduling)作为缩写——C++ 侧有专门的 <code>csrc/engine/zos.cpp / zos.hpp</code>,Python 侧有 <code>deepinfer/worker/zos_status.py</code>;开关环境变量为 <code>DEEPINFER_ZERO_OVERHEAD_SCHEDULING</code>(environ.py:186)。引擎虚函数 <code>process_output</code> 的 docstring 直接写明了语义差异:"ZOS=False: 处理当前 step;ZOS=True: 处理上一个 step 输出的 token"(llm_engine.py:824-828)。
    </div>
  </section>

  <!-- ============================================================ -->
  <section id="s2">
    <h2 class="sec"><span class="num">2</span>driver-worker 架构:进程模型与主循环</h2>
    <p class="lede">先回答一个架构问题:DeepInfer 是"单进程多线程"还是"多进程"?答案是<b>多进程 + driver 进程内联</b>——LLMEngine 与 driver Worker(cp_rank=0)在同一进程的同一 Python 线程里顺序调用;每个额外的 CP rank 才是独立守护进程。零开销不是靠后台线程抢时间,而是靠"异步 launch + 延迟后处理 + 纯 CPU 控制面"三件事在单线程内流水线化。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🏗️</span>进程拓扑</h3>
        <p><code>_init_workers</code>(llm_engine.py:368-414)为 <code>cp_rank ∈ [1, cp_size)</code> 各 spawn 一个 <code>SpawnProcessWithCrashHeader</code> 守护进程(llm_engine.py:389-395),入口是 <code>_spawn_worker</code>(llm_engine.py:122-127);driver Worker 则直接在引擎进程内构造(llm_engine.py:402-413),并注入 <code>EngineCallbacks</code>(llm_engine.py:398-400)。子 worker 构造函数末尾进入 <code>start_slave_worker_loop</code> 死循环(base.py:120-123),并设置 <code>PR_SET_PDEATHSIG</code> 保证父进程死亡时被内核 SIGKILL(base.py:42-45、130)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧵</span>"driver 线程"其实是函数调用</h3>
        <p><code>LLMEngine._run_workers</code>(llm_engine.py:1017-1025)委托给 <code>driver_worker.run_workers</code>,后者在 CP 组上广播方法名后直接 <code>getattr(self, method)(...)</code> 本地调用(base.py:302)——引擎与 driver worker 之间<b>没有任何线程或 RPC</b>。真正的后台线程只有辅助角色:统计日志线程(stats_logger.py:185-187)、结构化输出 matcher 线程池(llm_engine.py:334-342)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">📌</span>CPU 亲和性与 GC 抑制</h3>
        <p>为让调度线程的时延可预测:worker 进程按 GPU 拓扑做 NUMA 绑定(<code>_bind_numa</code>,base.py:347-357)与 CPU 绑核(<code>bind_cpu</code>,utils.py:143-151),限制 <code>torch.set_num_threads(8)</code>(base.py:178-179);同时 <code>gc.disable()</code>(base.py:102),改为每 <code>DEEPINFER_GC_INTERVAL_STEP</code>(默认 1000,environ.py:192)步在 <code>pre_sampler_sync</code> 窗口内主动 <code>gc.collect()</code>(base.py:153-157,worker.py:165)——GC 停顿也被挪进了与 GPU 重叠的时间窗。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">🔁</span>CP 从 rank 如何跟上</h3>
        <p>从 rank 的循环只有两行:<code>method, kwargs = cp_broadcast_object(None)</code> 然后 <code>getattr(self, method)(**kwargs)</code>(base.py:131-133)。它收到的每条消息都是 driver 在 <code>run_workers</code> 里 enqueue 的 <code>(method, kwargs)</code> 元组(base.py:298-302);元数据张量本身则通过 <code>broadcast_tensor_dict</code> 走 device 侧集合通信(model_runner.py:200-212),保证 forward 输入在 CP 组内一致。</p>
      </div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:26px 0 6px">engine.step():调度与执行的重叠点</h3>
    <p style="font-size:13.5px;color:var(--muted)">主循环(<code>LLMEngine.step</code>,llm_engine.py:860-959)把一个 step 切成三段:纯 CPU 的 schedule 段、与 GPU 重叠的收尾段、以及异步执行段。注意最后对 <code>_execute_model_async_step</code> 的调用是<b>唯一</b>触碰 GPU 的地方。</p>

    <div class="filepath">deepinfer/engine/llm_engine.py:881-905(节选)</div>
    <pre class="code"><span class="k">with</span> <span class="f">cpu_timer</span>.<span class="f">record</span>(<span class="s">"schedule"</span>):
    seq_metadata_list: <span class="k">list</span>[SequenceMetadata]
    scheduler_outputs: SchedulerOutputs
    <span class="k">with</span> <span class="f">cpu_timer</span>.<span class="f">record</span>(<span class="s">"schedule:cpp"</span>):
        <span class="c"># C++ Scheduler:选 batch、分配 KV 块,纯 CPU</span>
        seq_metadata_list, scheduler_outputs = self.scheduler.<span class="f">schedule</span>(self.sequence_metadata_pool)
    <span class="k">with</span> <span class="f">cpu_timer</span>.<span class="f">record</span>(<span class="s">"schedule:clone"</span>):
        clone_states, clone_blocks, zero_states = (...)
        <span class="k">if</span> clone_states.size &gt; <span class="n">0</span> <span class="k">or</span> clone_blocks.size &gt; <span class="n">0</span> <span class="k">or</span> zero_states.size &gt; <span class="n">0</span>:
            to_release, to_release2 = self.<span class="f">_run_workers</span>(<span class="s">"clone_and_zero_states_and_blocks_on_default_stream"</span>, ...)
            <span class="c"># Unpinned in this step's pre_sampler_sync.</span>
            self.deferred_release.<span class="f">collect_clone_unpins</span>(to_release, to_release2)</pre>

    <div class="filepath">deepinfer/engine/llm_engine.py:951-975</div>
    <pre class="code"><span class="c"># model execution</span>
request_outputs = self.<span class="f">_execute_model_async_step</span>(seq_metadata_list, scheduler_outputs)   <span class="c"># ← 唯一的执行入口</span>
...
<span class="k">def</span> <span class="f">_execute_model_async_step</span>(self, seq_metadata_list, scheduler_outputs):
    <span class="k">with</span> <span class="f">cpu_timer</span>.<span class="f">record</span>(<span class="s">"run_workers"</span>):
        request_outputs = self.<span class="f">_run_workers</span>(
            <span class="s">"execute_model_step"</span>,
            driver_kwargs=<span class="k">dict</span>(seq_metadata_list=seq_metadata_list,
                            scheduler_outputs=scheduler_outputs),
            is_prompt=scheduler_outputs.prompt_run,
            is_placeholder=scheduler_outputs.<span class="f">is_empty</span>(),   <span class="c"># 空调度也照跑,保持 CP 步型一致</span>
        )
    self.deferred_release.<span class="f">collect_request_outputs</span>(request_outputs)
    <span class="k">return</span> request_outputs</pre>

    <div class="note good">
      <b>关键洞察:</b><code>step()</code> 返回时,GPU 上的 forward/sample <b>尚未完成</b>——它们只是被提交进了 CUDA stream。返回给调用方的 <code>request_outputs</code> 来自<b>上一个</b> step 的后处理(见下一节)。当没有未完成请求时,entrypoint 会调用 <code>flush_inflight_reqs</code>(llm_engine.py:977-982)把最后一个在途 step 的输出排干——离线推理主循环正是这样写的:<code>step_outputs = self.llm_engine.step() if unfinished else self.llm_engine.flush_inflight_reqs()</code>(llm.py:176-186)。
    </div>

    <div class="note">
      <b>离线循环的 clone 语义:</b>RequestOutput 由 <code>RequestOutputPool</code> 管理,会在下一次 <code>step()</code> 中被释放(<code>step</code> docstring,llm_engine.py:866-870);调用方需要跨步保留时必须 <code>RequestOutput.clone(raw_output)</code>(llm.py:180-181)。这正是"延迟一步释放"设计在 API 层面的投影。
    </div>
  </section>

  <!-- ============================================================ -->
  <section id="s3">
    <h2 class="sec"><span class="num">3</span>driver-worker 通信:shm broadcast MessageQueue</h2>
    <p class="lede">控制面消息((method, kwargs) 元组、CP 组的非张量字段)绝不能走 NCCL——NCCL broadcast 会向 device stream 插入 collective kernel,与 CUDA Graph replay 争用 GPU,且阻塞时长取决于组内最慢 rank 的 GPU 进度。DeepInfer 用"共享内存环形缓冲 + 标志位"替代:单写多读、无锁、纯 CPU、微秒级时延。</p>

    <h3 style="color:#fff;font-size:17px;margin:20px 0 6px">广播入口与队列建立</h3>
    <div class="filepath">deepinfer/model_executor/parallel_utils/parallel_state.py:17-23、122-124</div>
    <pre class="code"><span class="k">def</span> <span class="f">cp_broadcast_object</span>(obj: Any) -&gt; Any:
    <span class="k">assert</span> PG.mq <span class="k">is not</span> <span class="k">None</span>
    <span class="k">if</span> PG.mq._is_writer:
        PG.mq.<span class="f">enqueue</span>(obj)          <span class="c"># driver:写共享内存</span>
        <span class="k">return</span> obj
    <span class="k">else</span>:
        <span class="k">return</span> PG.mq.<span class="f">dequeue</span>()         <span class="c"># CP 从 rank:自旋读共享内存</span>

<span class="c"># ParallelProcessGroup.create_process_groups 内:</span>
<span class="k">if</span> cp_size &gt; <span class="n">1</span>:
    self.mq = MessageQueue.<span class="f">create_from_process_group</span>(self.cpu_cp_group, <span class="n">1</span> &lt;&lt; <span class="n">20</span>, <span class="n">10</span>)
    <span class="c"># ↑ 1 MiB/chunk × 10 chunks,gloo CPU 组上交换 handle</span></pre>

    <p style="font-size:13.5px;color:var(--muted)">队列在 <code>init_parallel_groups</code> 时建立:rank 0(写者)先创建 <code>ShmRingBuffer</code>,把含共享内存名字的 <code>Handle</code> 通过 <code>dist.broadcast_object_list</code>(gloo)发给组内其它 rank,随后 <code>wait_until_ready()</code> 在 ZMQ pub-sub 上完成一次握手(shm_broadcast.py:431-461、286-306)。</p>

    <div class="figure">
      <svg viewBox="0 0 920 585" role="img" aria-label="MessageQueue 共享内存环形缓冲动画">
        <defs>
          <marker id="arr" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#22d3ee"/>
          </marker>
          <marker id="arrg" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#34d399"/>
          </marker>
        </defs>

        <!-- Driver -->
        <rect class="drv" x="18" y="150" width="168" height="96" rx="12" fill="#16233f" stroke="#4f8cff" stroke-width="1.6"/>
        <text class="smw" x="40" y="180">Driver Worker</text>
        <text class="sm" x="40" y="198">engine 同进程 · rank 0</text>
        <text class="sm" x="40" y="214">cp_broadcast_object</text>
        <text class="sm" x="40" y="230">pickle.dumps → enqueue</text>

        <!-- driver -> ring -->
        <path class="mqflow" d="M186,198 L246,198" stroke="#22d3ee" stroke-width="2" fill="none" marker-end="url(#arr)"/>
        <text class="sm" x="186" y="188" fill="#22d3ee">acquire_write</text>

        <!-- Ring cells -->
        <g>
          <rect class="mqcell" x="250" y="170" width="74" height="54" rx="8" stroke-width="1.4"/>
          <rect class="mqcell" x="332" y="170" width="74" height="54" rx="8" stroke-width="1.4" style="animation-delay:-1s"/>
          <rect class="mqcell" x="414" y="170" width="74" height="54" rx="8" stroke-width="1.4" style="animation-delay:-2s"/>
          <rect class="mqcell" x="496" y="170" width="74" height="54" rx="8" stroke-width="1.4" style="animation-delay:-3s"/>
          <rect class="mqcell" x="578" y="170" width="74" height="54" rx="8" stroke-width="1.4" style="animation-delay:-4s"/>
          <rect class="mqcell" x="660" y="170" width="74" height="54" rx="8" stroke-width="1.4" style="animation-delay:-5s"/>
          <rect class="mqcell" x="742" y="170" width="74" height="54" rx="8" stroke-width="1.4" style="animation-delay:-6s"/>
          <rect class="mqcell" x="824" y="170" width="74" height="54" rx="8" stroke-width="1.4" style="animation-delay:-7s"/>
          <text class="sm" x="270" y="201">chunk0</text><text class="sm" x="352" y="201">chunk1</text>
          <text class="sm" x="434" y="201">chunk2</text><text class="sm" x="516" y="201">chunk3</text>
          <text class="sm" x="598" y="201">chunk4</text><text class="sm" x="680" y="201">chunk5</text>
          <text class="sm" x="762" y="201">chunk6</text><text class="sm" x="844" y="201">chunk7</text>
        </g>
        <text x="250" y="158" fill="#5a6b92" font-size="10.5">ShmRingBuffer:数据区 max_chunks × max_chunk_bytes(1 MiB × 10)</text>

        <!-- metadata flags -->
        <g>
          <!-- chunk0 flags -->
          <rect class="wfl" x="250" y="232" width="13" height="13" rx="2"/><rect class="rfl0" x="266" y="232" width="13" height="13" rx="2"/><rect class="rfl1" x="282" y="232" width="13" height="13" rx="2"/><rect class="rfl2" x="298" y="232" width="13" height="13" rx="2"/>
          <rect class="wfl" x="332" y="232" width="13" height="13" rx="2" style="animation-delay:-1s"/><rect class="rfl0" x="348" y="232" width="13" height="13" rx="2" style="animation-delay:-1s"/><rect class="rfl1" x="364" y="232" width="13" height="13" rx="2" style="animation-delay:-1s"/><rect class="rfl2" x="380" y="232" width="13" height="13" rx="2" style="animation-delay:-1s"/>
          <rect class="wfl" x="414" y="232" width="13" height="13" rx="2" style="animation-delay:-2s"/><rect class="rfl0" x="430" y="232" width="13" height="13" rx="2" style="animation-delay:-2s"/><rect class="rfl1" x="446" y="232" width="13" height="13" rx="2" style="animation-delay:-2s"/><rect class="rfl2" x="462" y="232" width="13" height="13" rx="2" style="animation-delay:-2s"/>
          <rect class="wfl" x="496" y="232" width="13" height="13" rx="2" style="animation-delay:-3s"/><rect class="rfl0" x="512" y="232" width="13" height="13" rx="2" style="animation-delay:-3s"/><rect class="rfl1" x="528" y="232" width="13" height="13" rx="2" style="animation-delay:-3s"/><rect class="rfl2" x="544" y="232" width="13" height="13" rx="2" style="animation-delay:-3s"/>
          <rect class="wfl" x="578" y="232" width="13" height="13" rx="2" style="animation-delay:-4s"/><rect class="rfl0" x="594" y="232" width="13" height="13" rx="2" style="animation-delay:-4s"/><rect class="rfl1" x="610" y="232" width="13" height="13" rx="2" style="animation-delay:-4s"/><rect class="rfl2" x="626" y="232" width="13" height="13" rx="2" style="animation-delay:-4s"/>
          <rect class="wfl" x="660" y="232" width="13" height="13" rx="2" style="animation-delay:-5s"/><rect class="rfl0" x="676" y="232" width="13" height="13" rx="2" style="animation-delay:-5s"/><rect class="rfl1" x="692" y="232" width="13" height="13" rx="2" style="animation-delay:-5s"/><rect class="rfl2" x="708" y="232" width="13" height="13" rx="2" style="animation-delay:-5s"/>
          <rect class="wfl" x="742" y="232" width="13" height="13" rx="2" style="animation-delay:-6s"/><rect class="rfl0" x="758" y="232" width="13" height="13" rx="2" style="animation-delay:-6s"/><rect class="rfl1" x="774" y="232" width="13" height="13" rx="2" style="animation-delay:-6s"/><rect class="rfl2" x="790" y="232" width="13" height="13" rx="2" style="animation-delay:-6s"/>
          <rect class="wfl" x="824" y="232" width="13" height="13" rx="2" style="animation-delay:-7s"/><rect class="rfl0" x="840" y="232" width="13" height="13" rx="2" style="animation-delay:-7s"/><rect class="rfl1" x="856" y="232" width="13" height="13" rx="2" style="animation-delay:-7s"/><rect class="rfl2" x="872" y="232" width="13" height="13" rx="2" style="animation-delay:-7s"/>
        </g>
        <text class="sm" x="250" y="262">metadata 区:每个 chunk 1+n_reader 个字节</text>
        <text class="sm" x="250" y="277" fill="#22d3ee">■ written_flag</text>
        <text class="sm" x="350" y="277" fill="#34d399">■■■ reader0/1/2_flag</text>

        <!-- writer cursor -->
        <g class="wcur">
          <path d="M287,140 L287,156 L281,148 L293,148 Z" fill="#4f8cff"/>
          <text x="266" y="134" fill="#4f8cff" font-size="11" font-weight="700">writer ▼</text>
        </g>
        <!-- reader cursors -->
        <g class="rcur" style="animation-delay:.45s">
          <path d="M287,292 L287,308 L281,300 L293,300 Z" fill="#34d399"/>
          <text x="252" y="286" fill="#34d399" font-size="10">reader ▲</text>
        </g>

        <!-- readers -->
        <g>
          <rect x="300" y="330" width="150" height="46" rx="10" fill="#16233f" stroke="#34d399" stroke-width="1.4"/>
          <text class="smw" x="328" y="348">CP worker 1</text><text class="sm" x="328" y="366">acquire_read 自旋</text>
          <rect x="490" y="330" width="150" height="46" rx="10" fill="#16233f" stroke="#34d399" stroke-width="1.4"/>
          <text class="smw" x="518" y="348">CP worker 2</text><text class="sm" x="518" y="366">acquire_read 自旋</text>
          <rect x="680" y="330" width="150" height="46" rx="10" fill="#16233f" stroke="#34d399" stroke-width="1.4"/>
          <text class="smw" x="708" y="348">CP worker 3</text><text class="sm" x="708" y="366">acquire_read 自旋</text>
        </g>
        <path class="mqflow" d="M375,326 L375,306" stroke="#34d399" stroke-width="1.6" fill="none" marker-end="url(#arrg)"/>
        <path class="mqflow" d="M565,326 L565,306" stroke="#34d399" stroke-width="1.6" fill="none" marker-end="url(#arrg)"/>
        <path class="mqflow" d="M755,326 L755,306" stroke="#34d399" stroke-width="1.6" fill="none" marker-end="url(#arrg)"/>
        <text class="sm" x="300" y="400">n_reader = cp_size − 1(示例 cp_size=4);reader 只把自己的 flag 从 0 置 1,writer 负责复位</text>

        <!-- overflow path -->
        <rect class="zmqbox" x="18" y="300" width="230" height="76" rx="10" fill="#1c1830" stroke="#a78bfa" stroke-width="1.4"/>
        <text class="smw" x="34" y="326" fill="#a78bfa">ZMQ XPUB/SUB 溢出通道</text>
        <text class="sm" x="34" y="344">payload ≥ 1 MiB 时:</text>
        <text class="sm" x="34" y="360">chunk 首字节置 overflow,</text>
        <text class="sm" x="34" y="376">大数据走 tcp://127.0.0.1</text>
        <path class="mqflow" d="M102,246 L102,300" stroke="#a78bfa" stroke-width="1.6" fill="none"/>

        <!-- state legend -->
        <g font-size="11" font-family="'JetBrains Mono',Consolas,monospace">
          <rect x="18" y="440" width="200" height="120" rx="10" fill="#101a30" stroke="#263352"/>
          <text x="34" y="464" fill="#fff" font-weight="700">metadata 状态机</text>
          <text x="34" y="486" fill="#8ea0c2">0???  未写 → 可写</text>
          <text x="34" y="506" fill="#22d3ee">1000  已写 → 可读</text>
          <text x="34" y="526" fill="#fbbf24">1???  部分已读</text>
          <text x="34" y="546" fill="#34d399">1111  全读 → 可复写</text>
        </g>
        <g font-size="11">
          <text x="250" y="452" fill="#5a6b92">写者顺序(顺序不可反,shm_broadcast.py:347-355):</text>
          <text x="250" y="474" fill="#dbe4f5">① written_flag 置 0(锁定块) → ② 写入数据 → ③ 复位全部 reader_flag → ④ written_flag 置 1</text>
          <text x="250" y="496" fill="#5a6b92">若先 ④ 后 ③,会瞬时经过 1???(case 3),reader 可能误判"已读过"——原注释明确警告这一点。</text>
          <text x="250" y="524" fill="#5a6b92">等待策略:os.sched_yield() 自旋,每 DEEPINFER_RINGBUFFER_WARNING_INTERVAL(60s)打一次 debug 日志,</text>
          <text x="250" y="544" fill="#5a6b92">超时抛 TimeoutError(_spin_wait,shm_broadcast.py:308-318)。</text>
        </g>
      </svg>
      <div class="cap">图 2 · MessageQueue 共享内存广播:writer 游标沿 ring 逐块推进,chunk 依次点亮(写入→被读→复用);metadata 标志位 W/R0/R1/R2 驱动单写多读的无锁同步;超大 payload 经 ZMQ pub-sub 溢出</div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:20px 0 6px">acquire_write:写者的等待与发布</h3>
    <div class="filepath">deepinfer/distributed/shm_broadcast.py:320-357(节选)· acquire_read:359-387</div>
    <pre class="code"><span class="k">@contextmanager</span>
<span class="k">def</span> <span class="f">acquire_write</span>(self, timeout=<span class="k">None</span>):
    <span class="k">while</span> <span class="k">True</span>:
        <span class="k">with</span> self.buffer.<span class="f">get_metadata</span>(self.current_idx) <span class="k">as</span> metadata_buffer:
            read_count = <span class="f">sum</span>(metadata_buffer[<span class="n">1</span>:])
            written_flag = metadata_buffer[<span class="n">0</span>]
            <span class="k">if</span> written_flag <span class="k">and</span> read_count != self.buffer.n_reader:
                <span class="c"># 块已写且未被所有 reader 读走 → 自旋等待</span>
                n_warning = self.<span class="f">_spin_wait</span>(start_time, n_warning, timeout)
                <span class="k">continue</span>
            metadata_buffer[<span class="n">0</span>] = <span class="n">0</span>                 <span class="c"># ① 标记为未写(独占)</span>
            <span class="k">with</span> self.buffer.<span class="f">get_data</span>(self.current_idx) <span class="k">as</span> buf:
                <span class="k">yield</span> buf                          <span class="c"># ② 调用方写入(含 overflow 首字节)</span>
            <span class="k">for</span> i <span class="k">in</span> <span class="f">range</span>(<span class="n">1</span>, self.buffer.n_reader + <span class="n">1</span>):
                metadata_buffer[i] = <span class="n">0</span>             <span class="c"># ③ 先复位 reader 标志</span>
            metadata_buffer[<span class="n">0</span>] = <span class="n">1</span>                 <span class="c"># ④ 再置 written(顺序关键!)</span>
            self.current_idx = (self.current_idx + <span class="n">1</span>) % self.buffer.max_chunks
            <span class="k">break</span></pre>

    <p style="font-size:13.5px;color:var(--muted)"><code>enqueue</code> 把对象 pickle 后写入当前块;超过 <code>max_chunk_bytes</code> 时把块首字节置为 overflow 标志,本体改走 ZMQ socket(shm_broadcast.py:389-404);reader 端 <code>dequeue</code> 看到溢出标志就从 socket 收(shm_broadcast.py:406-422)。<code>broadcast_object</code> 则是二者按角色分发的一行封装(shm_broadcast.py:424-429)。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🧊</span>gloo:默认 PG 就是 CPU 后端</h3>
        <p><code>_init_distributed_environment</code> 用 <code>backend="gloo"</code> 初始化默认进程组,超时取 <code>DEEPINFER_GLOO_TIMEOUT</code>(默认 14400s = 4 小时,environ.py:117;base.py:334-340)。随后 <code>create_process_groups</code> 为 DP/CP/EP 各建一组<b>CPU 镜像组</b>:<code>cpu_dp_group</code>、<code>cpu_cp_group</code>、<code>cpu_ep_in_dp</code>(parallel_state.py:94、99、118)。device 侧 NCCL/HCCL 子组因此失去 eager 初始化,由 <code>init_device_groups</code> 用一次 dummy all_reduce 逐组预热(parallel_state.py:173-188)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🗳️</span>调度器投票也在 CPU 上</h3>
        <p>ZOS 开启时,C++ Scheduler 拿到的是 <code>PG.cpu_data_parallel_group()</code> 而非 device 组(llm_engine.py:313)。scheduler.hpp 据此设 <code>use_cpu_dp_group = dp_group-&gt;getBackendName() == "gloo"</code>(scheduler.hpp:109),<code>_dp_allreduce</code> 在 CPU tensor 上做归约(scheduler.hpp:169-176)。NORMAL 引擎"本步全组做 prefill 还是 decode"的 ALL/ANY 两类投票(scheduler.hpp:307-332)因此<b>完全不占用 GPU</b>,还能与在途的 forward 并行。<code>has_unfinished_requests</code> 的 DP 归约同样切到 CPU 组(llm_engine.py:665-679)。</p>
      </div>
    </div>

    <div class="note warn">
      <b>为什么 gloo 超时要 4 小时?</b>控制面 collective(投票、广播 handle、销毁 barrier)在 ZOS 下可能与非常长的 GPU 段并行等待——例如大 batch prefill 的 forward 加上 CUDA Graph replay。gloo 默认 30 分钟超时会被偶发的长 step 误伤,因此 DeepInfer 显式放宽到 14400s。相对地,shm ring 的等待是<code>sched_yield</code> 自旋而非 collective,卡住时每 60 秒输出一条 debug 日志(environ.py:191)辅助定位。
    </div>
  </section>

  <!-- ============================================================ -->
  <section id="s4">
    <h2 class="sec"><span class="num">4</span>零开销调度的关键代码路径</h2>
    <p class="lede">核心在 <code>Worker.execute_model_step</code>(worker.py:88-189):每个 step 被重组为 "Forward 本步 → Post-process 上一步 → Sample 本步 → 存起本步状态" 的四段轮转。GPU 只认识 launch,CPU 的工作被塞进 launch 之间的空隙。</p>

    <div class="filepath">deepinfer/worker/worker.py:96-189(docstring 节选 + 主体)</div>
    <pre class="code"><span class="s">"""The unified entry for model execution: every step (prompt/decode, ZOS on/off,
placeholder) goes through this Forward-Post_process-Sample round.
  1. Forward current step (main model)
  2. Post-process previous step
  3. Sample current step
  4. Post-process current step: in place for prompt / non-ZOS steps;
     ZOS decode steps defer it to the next step to overlap with forward"""</span>
<span class="k">def</span> <span class="f">execute_model_step</span>(self, is_prompt, is_placeholder, seq_metadata_list=<span class="k">None</span>, scheduler_outputs=<span class="k">None</span>):
    <span class="c"># 1. forward curr step —— 只 launch,不同步</span>
    <span class="k">if</span> self.is_driver_worker <span class="k">and not</span> is_placeholder:
        total_q = ... ; correction = self.<span class="f">_correct_seqlens_qk</span>(seq_metadata_list, is_prompt, total_q)
    main_model_output = self.model_runner.<span class="f">execute_main_model</span>(seq_metadata_list, self.gpu_cache,
                                  metadata_zos=correction.metadata_zos <span class="k">if</span> correction <span class="k">else</span> <span class="k">None</span>, total_q=total_q)

    <span class="c"># 2. post process prev step —— CPU 工作,与上面刚 launch 的 forward 在 GPU 上的执行重叠</span>
    request_outputs = self.<span class="f">_post_process_step</span>(self.prev_step_state)

    <span class="c"># 3. sample curr step —— 只 launch;先等 D2H 回读的修正 seqlens(如果有)</span>
    <span class="k">if</span> correction <span class="k">is not</span> <span class="k">None</span>:
        <span class="k">if</span> correction.d2h_evt <span class="k">is not</span> <span class="k">None</span>:
            correction.d2h_evt.<span class="f">synchronize</span>()                     <span class="c"># 事件同步,而非流同步</span>
        scheduler_outputs.<span class="f">update_metadata_for_sampling_zos</span>(seq_metadata_list,
            correction.seqlens_q_cpu, correction.metadata_zos.remap_cpu, self.nextn)
    sampler_output = self.model_runner.<span class="f">execute_sample</span>(seq_metadata_list, input_metadata, model_output, self.gpu_cache)

    <span class="k">with</span> <span class="f">cpu_timer</span>.<span class="f">record</span>(<span class="s">"pre_sampler_sync"</span>):
        <span class="k">if</span> self.is_driver_worker:
            self.engine_callbacks.pre_sampler_sync_fn(scheduler_outputs)   <span class="c"># 引擎回调:延迟释放/存 kvcache</span>
        self.<span class="f">maybe_gc_collect</span>()                                    <span class="c"># GC 也藏进这个窗口</span>

    sample_end_evt = torch.cuda.<span class="f">Event</span>(enable_timing=<span class="k">True</span>)
    sample_end_evt.<span class="f">record</span>()                                              <span class="c"># 采样完成的"铃声"</span>
    curr_step_state = <span class="f">WorkerStepState</span>(seq_metadata_list=..., scheduler_outputs=...,
                            sampler_output=..., sample_end_evt=sample_end_evt, ...)

    <span class="c"># 4. prompt 步或配置 non-ZOS 时当场 post process;ZOS decode 步留到下一步(与 forward 重叠)</span>
    <span class="k">if</span> is_prompt <span class="k">or not</span> envs.DEEPINFER_ZERO_OVERHEAD_SCHEDULING:      <span class="c"># ← zero_overhead 分支</span>
        request_outputs = np.<span class="f">concatenate</span>([request_outputs, self.<span class="f">_post_process_step</span>(curr_step_state)])
        self.prev_step_state = <span class="k">None</span>
    <span class="k">else</span>:
        self.prev_step_state = curr_step_state                            <span class="c"># ← 延迟一步的全部秘密</span>
    <span class="k">return</span> request_outputs</pre>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🔁</span>_post_process_step:同步点只有一个事件</h3>
        <p>延迟后处理真正等待 GPU 的地方只有一处:<code>step_state.sample_end_evt.synchronize()</code>(worker.py:263)——而它等的是<b>上一步</b>采样尾部事件。由于 CPU 从调度到这里的耗时通常已覆盖上一步的 forward+sample,这个 synchronize 大概率立即返回,真正的"等待"被自然吸收。随后执行 <code>model_runner.post_process</code> 与引擎回调 <code>post_process_fn</code>(worker.py:267-271)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🪝</span>EngineCallbacks:引擎逻辑反向注入 worker</h3>
        <p>引擎在构造 driver worker 时传入 <code>EngineCallbacks(post_process_fn=self.post_process, pre_sampler_sync_fn=self.pre_sampler_sync)</code>(llm_engine.py:398-400;worker.py:43-48)。<code>post_process</code> 里做 <code>process_MTPInfo</code>、<code>scheduler.process_outputs</code>、<code>build_request_outputs</code>、用 forward/sample 事件对 <code>update_mtp_runtime</code>(llm_engine.py:984-1015);<code>pre_sampler_sync</code> 里做延迟释放与 kvcache 落盘准备(llm_engine.py:830-846)。它们全部运行在 forward launch 之后、sample launch 之前的窗口里——这就是"引擎 CPU 工作与 GPU 计算重叠"的机制本体。</p>
      </div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:26px 0 6px">4.1 滞后一步的元数据:GPU 上的修正</h3>
    <p style="font-size:13.5px;color:var(--muted)">CPU 调度 step N+1 时,延续序列的 <code>seqlens_q/k</code> 还停留在 step N 的视角(MTP 变长验证下每个序列每步的 query 长度取决于上一步的接受数)。修正不在 CPU 上做——那需要先同步等采样结果——而是把"上一步的答案"留在 GPU 上,让 kernel 直接算。</p>

    <div class="filepath">deepinfer/worker/worker.py:191-245(_correct_seqlens_qk 节选)</div>
    <pre class="code"><span class="k">def</span> <span class="f">_correct_seqlens_qk</span>(self, seq_metadata_list, is_prompt, total_q):
    <span class="s">"""CPU 侧的 seqlens_q/k 在 ZOS 下滞后一步:与上一步 batch 有交集时,
    需按上一步采样结果在 GPU 上修正。"""</span>
    prev = self.prev_step_state
    <span class="k">if</span> prev <span class="k">is</span> <span class="k">None</span> <span class="k">or</span> prev.is_placeholder:
        <span class="k">return</span> <span class="k">None</span>
    ...
    <span class="c"># C++ 在 pinned CPU 内存上算 remap:remap[i] = j 表示本步第 i 个序列对应上一步第 j 个,否则 -1</span>
    remap_cpu, seqlens_q_cpu, seqlens_k_cpu, has_overlap = <span class="f">prepare_zos_inputs</span>(
        seq_metadata_list, prev.seq_metadata_list, n_seq_with_padding, self.nextn)
    <span class="k">if</span> <span class="k">not</span> has_overlap:
        <span class="k">return</span> <span class="k">None</span>                                    <span class="c"># 批次完全换血:无需修正</span>

    <span class="c"># 异步 H2D:pinned → device,不阻塞</span>
    remap      = remap_cpu.<span class="f">cuda</span>(non_blocking=<span class="k">True</span>)
    seqlens_q  = seqlens_q_cpu.<span class="f">cuda</span>(non_blocking=<span class="k">True</span>)
    seqlens_k  = seqlens_k_cpu.<span class="f">cuda</span>(non_blocking=<span class="k">True</span>)

    <span class="k">if</span> envs.DEEPINFER_ENABLE_MTP_VARLEN:      <span class="c"># 置信度调度变长验证</span>
        <span class="f">compute_seqlens_q_by_confidence_rates</span>(total_q, remap[:n_seq],
            prev.sampler_output.confidence_rates_gpu, seqlens_q[:n_seq])     <span class="c"># ← 用上一步 GPU 输出</span>
    <span class="k">if</span> self.nextn &gt; <span class="n">0</span>:
        <span class="f">compute_seqlens_k_zos</span>(seqlens_k[:n_seq], seqlens_q[:n_seq], remap[:n_seq],
            prev.sampler_output.num_accepted_tokens_gpu, nextn=self.nextn)   <span class="c"># ← 用上一步 GPU 输出</span>

    d2h_evt = <span class="k">None</span>
    <span class="k">if</span> envs.DEEPINFER_ENABLE_MTP_VARLEN:
        <span class="c"># H2D、修正核、D2H 都排在本 stream 上;仅 varlen 会改写这个 pinned 源</span>
        seqlens_q_cpu[:n_seq].<span class="f">copy_</span>(seqlens_q[:n_seq], non_blocking=<span class="k">True</span>)   <span class="c"># 异步 D2H</span>
        d2h_evt = torch.cuda.<span class="f">Event</span>(); d2h_evt.<span class="f">record</span>()                        <span class="c"># 事件标记完成</span>
    ...
    <span class="k">return</span> <span class="f">_SeqlensCorrection</span>(metadata_zos, seqlens_q_cpu, d2h_evt)</pre>

    <p style="font-size:13.5px;color:var(--muted)">token 侧同理:C++ 侧 <code>prepare_token_inputs</code> 在无重叠时直接打包最终 H2D tensor;有重叠时<b>只填充 fresh 行</b>——注释原话:"With overlap, only fresh rows are populated; matched rows come from the previous GPU outputs."(zos.cpp:84-85,写入逻辑在 zos.cpp:111-112)。匹配行的 token 由 GPU kernel <code>gather_input_ids_zos</code> 用上一步的 <code>sampled_token_ids_gpu</code>/<code>predict_token_ids_gpu</code> 按 <code>remap</code> 现场拼出(gather_input_ids_zos.py:10-17 的签名即这五个输入)。decode 输入准备函数本身也按 ZOS 切换:<code>prepare_decode = prepare_decode_v4_zos if envs.DEEPINFER_ZERO_OVERHEAD_SCHEDULING else prepare_decode_v4</code>(model_metadata_utils.py:142-144),其内部把 pinned 产物逐个 <code>.cuda(non_blocking=True)</code> 上传(prepare_tensor_input_zos.py:70-77)。</p>

    <div class="figure">
      <svg viewBox="0 0 920 560" role="img" aria-label="异步拷贝与事件同步数据通路动画">
        <defs>
          <marker id="arr2" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#22d3ee"/></marker>
          <marker id="arr3" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#fbbf24"/></marker>
        </defs>

        <!-- 顶部横幅 -->
        <rect class="banner" x="18" y="14" width="884" height="34" rx="9" fill="#123041" stroke="#22d3ee" stroke-width="1.2"/>
        <text x="36" y="36" fill="#22d3ee" font-size="12.5" font-weight="700">execute_model_step(step N+1):forward 已异步 launch —— GPU 正忙,以下全部 CPU/异步操作与之重叠</text>

        <!-- CPU 列 -->
        <rect x="18" y="86" width="292" height="104" rx="12" fill="#16233f" stroke="#4f8cff" stroke-width="1.5"/>
        <text class="boxT" x="34" y="110">pinned CPU 缓冲(prepare_zos_inputs)</text>
        <text class="boxS" x="34" y="130">remap_cpu · seqlens_q_cpu · seqlens_k_cpu</text>
        <text class="boxS" x="34" y="148">fresh_input_ids 等 fresh token 行(zos.cpp:85)</text>
        <text class="boxS" x="34" y="166">batch 有交集才有 remap,否则短路返回</text>

        <rect x="18" y="216" width="292" height="60" rx="12" fill="#16233f" stroke="#4f8cff" stroke-width="1.5"/>
        <text class="boxT" x="34" y="240">采样前 CPU 收尾</text>
        <text class="boxS" x="34" y="258">update_metadata_for_sampling_zos</text>

        <rect x="18" y="300" width="292" height="60" rx="12" fill="#1c1830" stroke="#fbbf24" stroke-width="1.4"/>
        <text class="boxT" x="34" y="324" fill="#fbbf24">d2h_evt.synchronize()</text>
        <text class="boxS" x="34" y="342">仅等事件,不等流(worker.py:148-149)</text>

        <!-- GPU 列 -->
        <rect x="610" y="86" width="292" height="104" rx="12" fill="#152a1f" stroke="#34d399" stroke-width="1.5"/>
        <text class="boxT" x="626" y="110" fill="#34d399">上一步 GPU 采样输出(留在 device)</text>
        <text class="boxS" x="626" y="130">confidence_rates_gpu</text>
        <text class="boxS" x="626" y="148">num_accepted_tokens_gpu</text>
        <text class="boxS" x="626" y="166">sampled / predict_token_ids_gpu</text>

        <rect class="kbox" x="610" y="216" width="292" height="42" rx="10" fill="#0e2a33" stroke="#22d3ee" stroke-width="1.4"/>
        <text class="boxT" x="626" y="242" fill="#22d3ee">compute_seqlens_q_by_confidence_rates</text>
        <rect class="kbox" x="610" y="268" width="292" height="42" rx="10" fill="#0e2a33" stroke="#22d3ee" stroke-width="1.4" style="animation-delay:.4s"/>
        <text class="boxT" x="626" y="294" fill="#22d3ee">compute_seqlens_k_zos · gather_input_ids_zos</text>

        <rect x="610" y="330" width="292" height="80" rx="12" fill="#16233f" stroke="#a78bfa" stroke-width="1.5"/>
        <text class="boxT" x="626" y="354" fill="#a78bfa">当前 CUDA stream 上的顺序</text>
        <text class="boxS" x="626" y="374">H2D → 修正 kernel → forward(N+1)</text>
        <text class="boxS" x="626" y="392">→ sample → D2H(varlen 时)</text>

        <!-- H2D arrows -->
        <path class="h2df" d="M310,116 L610,116" stroke="#22d3ee" stroke-width="2.2" fill="none" marker-end="url(#arr2)"/>
        <path class="h2df" d="M310,146 L610,146" stroke="#22d3ee" stroke-width="2.2" fill="none" marker-end="url(#arr2)" style="animation-delay:.3s"/>
        <path class="h2df" d="M310,176 L610,176" stroke="#22d3ee" stroke-width="2.2" fill="none" marker-end="url(#arr2)" style="animation-delay:.6s"/>
        <text x="392" y="106" fill="#22d3ee" font-size="11" font-weight="700">cuda(non_blocking=True) ×3</text>
        <path class="h2df" d="M610,237 C 520,237 480,300 310,318" stroke="#22d3ee" stroke-width="1.8" fill="none" marker-end="url(#arr2)" style="animation-delay:.2s"/>
        <text x="430" y="288" fill="#22d3ee" font-size="10.5">修正后的 seqlens 供 forward 输入</text>

        <!-- D2H arrow -->
        <path class="d2hf" d="M610,392 C 500,470 420,470 310,440 C 260,424 240,392 240,362" stroke="#fbbf24" stroke-width="2.2" fill="none" marker-end="url(#arr3)"/>
        <text x="392" y="470" fill="#fbbf24" font-size="11" font-weight="700">copy_(non_blocking=True) + d2h_evt.record()</text>

        <!-- event flag -->
        <g class="evt">
          <circle cx="240" cy="330" r="10" fill="#fbbf24" opacity=".25"/>
          <path d="M240,320 L240,342" stroke="#fbbf24" stroke-width="2.4"/>
          <path d="M240,321 L256,326 L240,331 Z" fill="#fbbf24"/>
        </g>
        <text x="258" y="326" fill="#fbbf24" font-size="10.5">事件完成 → CPU 立即拿到修正后 seqlens</text>

        <!-- stream timeline strip -->
        <rect x="18" y="492" width="884" height="52" rx="10" fill="#101a30" stroke="#263352"/>
        <text x="34" y="512" fill="#8ea0c2" font-size="10.5">CUDA stream 时间线:</text>
        <rect x="150" y="500" width="90" height="26" rx="5" fill="#0e4a5c"/><text x="168" y="518" fill="#c9f4ff" font-size="10">H2D</text>
        <rect x="244" y="500" width="140" height="26" rx="5" fill="#0e2a33" stroke="#22d3ee"/><text x="258" y="518" fill="#a5f3fc" font-size="10">修正 kernel</text>
        <rect x="388" y="500" width="220" height="26" rx="5" fill="url(#gCyan2)"/><text x="430" y="518" fill="#062024" font-size="10" font-weight="700">forward N+1</text>
        <rect x="612" y="500" width="110" height="26" rx="5" fill="#134e4a"/><text x="630" y="518" fill="#99f6e4" font-size="10">sample</text>
        <rect x="726" y="500" width="90" height="26" rx="5" fill="#3a2c14"/><text x="744" y="518" fill="#fde68a" font-size="10">D2H</text>
        <text x="842" y="518" fill="#5a6b92" font-size="13">▶</text>
        <g class="sweep"><circle cx="150" cy="513" r="5" fill="#fff"/></g>
        <defs><linearGradient id="gCyan2" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#0e7490"/><stop offset="1" stop-color="#22d3ee"/></linearGradient></defs>
      </svg>
      <div class="cap">图 3 · 异步拷贝与事件同步:remap/seqlens 走非阻塞 H2D 上传,GPU 修正 kernel 直接消费上一步留在 device 的采样输出;varlen 场景再用非阻塞 D2H + 事件把修正结果带回 CPU 供采样元数据更新</div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:26px 0 6px">4.2 事件同步全景:整个特性只靠这几枚 CUDA Event</h3>
    <table class="tbl">
      <tr><th>事件</th><th>创建 / record 位置</th><th>同步 / 消费位置</th><th>语义</th></tr>
      <tr><td><code>sample_end_evt</code></td><td>worker.py:167-168(每步采样 launch 后)</td><td>worker.py:263(下一步 <code>_post_process_step</code>)</td><td>上一步采样完成铃声;通常在 CPU 忙完调度后早已就绪</td></tr>
      <tr><td><code>d2h_evt</code></td><td>worker.py:232-234(varlen 修正 seqlens 的 D2H 后)</td><td>worker.py:148-149(采样元数据更新前)</td><td>修正后 seqlens 回读完成;只等这一件事,不等整个流</td></tr>
      <tr><td><code>clone_done_evt</code></td><td>llm_engine.py:86、95-98(<code>collect_clone_unpins</code>)</td><td>llm_engine.py:112(下一步 <code>pre_sampler_sync</code>)</td><td>state/block 克隆 kernel 完成,此时才允许 unpin 旧块</td></tr>
      <tr><td><code>copy_state_event</code></td><td>llm_engine.py:937(<code>do_copy_state</code> 之后)</td><td>llm_engine.py:835-836(下一步 <code>pre_sampler_sync</code>)</td><td>kvcache 落盘拷贝完成,之后才保存</td></tr>
      <tr><td>cuda_timer 事件对</td><td>timer.py:243-248(每次 record)</td><td>model_runner.py:384 + timer.py:266(<code>end_event.query()</code>)</td><td>ZOS 下计时 flush 只在事件已完成时才 synchronize,不阻塞</td></tr>
      <tr><td>graph_timer 事件</td><td>timer.py:169-177(<code>flip_event_buffer</code>,replay 前)</td><td>timer.py:195-217(下一步 flush)</td><td>CUDA Graph 内核计时用乒乓双缓冲,避免与在途 replay 冲突</td></tr>
    </table>

    <div class="note good">
      <b>护栏而非同步:</b><code>forbid_cuda_sync()</code>(utils.py:119-132)在 forward/sample 的 launch 区段把 torch 的同步调试模式打开——任何阻塞式拷贝或流/设备 synchronize 都会直接 raise(model_runner.py:321-325、356-360 的 <code>with ... forbid_cuda_sync()</code>)。它是<b>开发期断言</b>,确保"launch 即返回"不被悄悄破坏;文档注明 <code>torch.cuda.Event.synchronize</code> 不在 torch 同步检测范围内,所以 ZOS 的事件式同步不受影响。可用 <code>DEEPINFER_DISABLE_SYNC_GUARD=1</code> 关闭(environ.py:205)。
    </div>

    <h3 style="color:#fff;font-size:17px;margin:26px 0 6px">4.3 DeferredRelease:资源也要"延迟一步"</h3>
    <div class="filepath">deepinfer/engine/llm_engine.py:67-71、100-119(节选)</div>
    <pre class="code"><span class="k">class</span> <span class="f">DeferredRelease</span>:
    <span class="s">"""延后一轮释放 step 产出的资源,保证调用方读完。
    回收(collect)要释放的资源;在下一次的 pre_sampler_sync 时释放(release),与 GPU 计算 overlap。"""</span>
    <span class="k">def</span> <span class="f">release</span>(self):                         <span class="c"># 在 pre_sampler_sync 调用</span>
        <span class="k">if</span> self.sequence_metadata_to_release:
            self.sequence_metadata_pool.<span class="f">release</span>(self.sequence_metadata_to_release)
        self.request_outputs_pool.<span class="f">release</span>(self.request_outputs_to_release)
        <span class="k">if</span> self.clone_unpins_to_release <span class="k">is not</span> <span class="k">None</span>:
            ...
            self.clone_done_evt.<span class="f">synchronize</span>()        <span class="c"># 克隆 kernel 确认完成后才 unpin</span>
            self.state_manager.<span class="f">unpin_blocks</span>(states_to_unpin)
            self.block_manager.<span class="f">unpin_blocks</span>(blocks_to_unpin)</pre>
    <p style="font-size:13.5px;color:var(--muted)">为什么必须延迟?<code>WorkerStepState</code> 的字段注释给出契约:"Must remain valid until the next step's _post_process_step, where engine post_process releases them back to the pool."(zos_status.py:12)。SequenceMetadata 要活到下一步后处理;RequestOutput 由池管理、下一步释放(llm_engine.py:866-870);KV 块的 unpin 要等 <code>clone_done_evt</code>。收集(collect)发生在产出当步 llm_engine.py:905、974、1013,释放(release)统一发生在下一步的 <code>pre_sampler_sync</code>(llm_engine.py:830-831)——与 forward 重叠执行。</p>

    <h3 style="color:#fff;font-size:17px;margin:26px 0 6px">4.4 边界条件:ZOS 特有的三个分支</h3>
    <ul class="feat">
      <li><b>placeholder step(空跑保同步):</b>CP 组要求所有 rank 每个 step 执行同型集合通信。调度为空时引擎仍以 <code>is_placeholder=True</code> 走完整执行(llm_engine.py:972),worker 用 <code>_placeholder_seq_metadata</code> 造一个哑序列跑 forward(worker.py:126-127;model_runner.py:386-403),哑序列的 <code>mtp_info_write_slot</code> 默认落在 0 号槽、被 store kernel 跳过。</li>
      <li><b>收尾 flush:</b>最后一个在途 step 没有下一步可以搭车,由 <code>flush_inflight_reqs</code> 显式排干(worker.py:274-283),它"可能引起 CPU-GPU 同步"(docstring 原话)——只在生成结束时付一次代价。entrypoint 循环在 <code>unfinished=False</code> 时调用它(llm.py:176-186)。</li>
      <li><b>在途被抢占:</b>seq 在本步尚在途时被 <code>_preempt</code> 抢占重算,本步输出作废。scheduler.hpp 在 <code>process_outputs</code>(scheduler.hpp:917-925)与 <code>process_MTPInfo</code>(scheduler.hpp:1214-1220)各有一个专门分支:判据为 <code>!prompt_run &amp;&amp; seq.schedule.status == SequenceStatus::WAITING</code>,跳过全部记账——否则 <code>process_cnt</code> 抢跑 <code>schedule_cnt</code>,MTPVarlen 的配对断言会崩(原注释)。</li>
      <li><b>长度预算:</b>在途 step 让单序列瞬时可见长度超过已提交长度,<code>_get_runtime_max_model_len</code> 为 ZOS 额外预留 <code>nextn + (nextn + 1)</code> 个位置(config.py:11-16)。</li>
    </ul>
  </section>

  <!-- ============================================================ -->
  <section id="s5">
    <h2 class="sec"><span class="num">5</span>与 CUDA Graph 的配合</h2>
    <p class="lede">CUDA Graph 把整个 decode forward 变成一次 <code>graph.replay()</code> 调用,是"CPU 侧每步开销趋近于零"的前提;而 ZOS 反过来改变了 graph 的输入通路——<code>input_on_device</code> 让每步省掉一次 H2D 元数据拷贝。</p>

    <div class="filepath">deepinfer/worker/model_runner.py:73-79</div>
    <pre class="code">self.use_cuda_graph = <span class="k">not</span> envs.DEEPINFER_ENFORCE_EAGER <span class="k">and</span> self.parallel_config.engine_type != EngineType.PROMPT
self.cuda_graph_runner: CudaGraphRunner | <span class="k">None</span> = <span class="k">None</span>
<span class="k">if</span> self.use_cuda_graph:
    self.cuda_graph_runner = <span class="f">CudaGraphRunner</span>(
        max_batch_size=self.scheduler_config.max_num_seqs * (<span class="n">1</span> + self.nextn),
        input_on_device=envs.DEEPINFER_ZERO_OVERHEAD_SCHEDULING,   <span class="c"># ← ZOS 专属开关</span>
    )</pre>

    <div class="filepath">deepinfer/worker/cuda_graph_runner.py:26-38、54-66</div>
    <pre class="code"><span class="s">"""Captured graph with preparation and execution buffers.
Source tensors are on CPU, or share device tensor storage under ZOS.
Metadata objects stay separate because forward populates derived fields."""</span>
<span class="k">def</span> <span class="f">_run_model</span>(model, kv_caches, input_metadata_source, input_metadata_device, copy_inputs):
    cp_group = PG.<span class="f">context_parallel_group</span>()
    <span class="k">if</span> copy_inputs <span class="k">and</span> cp_group.<span class="f">rank</span>() == <span class="n">0</span>:
        input_metadata_device.<span class="f">recursive_copy_</span>(input_metadata_source)   <span class="c"># H2D;ZOS 下 copy_inputs=False,跳过</span>
    <span class="k">if</span> cp_group.<span class="f">size</span>() &gt; <span class="n">1</span>:
        input_metadata_device.<span class="f">broadcast</span>()                                <span class="c"># CP 组内张量广播(执行面)</span>
    <span class="k">return</span> <span class="f">model</span>(kv_caches=kv_caches, input_metadata=input_metadata_device)</pre>

    <div class="figure">
      <svg viewBox="0 0 920 520" role="img" aria-label="CUDA Graph 输入通路:非 ZOS 每步 H2D 拷贝 vs ZOS 直写共享 device 缓冲">
        <defs>
          <marker id="a4" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#22d3ee"/></marker>
          <linearGradient id="gC3" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#0e7490"/><stop offset="1" stop-color="#22d3ee"/></linearGradient>
        </defs>

        <!-- Track 1 -->
        <text class="hdr" x="18" y="30">非 ZOS:每步 H2D 拷贝 → replay</text>
        <rect x="18" y="48" width="220" height="66" rx="10" fill="#16233f" stroke="#4f8cff" stroke-width="1.4"/>
        <text class="t1" x="34" y="72">input_metadata_source</text><text class="t2" x="34" y="90">CPU tensors(每步重建)</text>
        <path class="fl2" d="M238,81 L342,81" stroke="#22d3ee" stroke-width="2" fill="none" marker-end="url(#a4)"/>
        <text class="t2" x="244" y="70" fill="#22d3ee">recursive_copy_</text>
        <rect x="342" y="48" width="240" height="66" rx="10" fill="#16233f" stroke="#a78bfa" stroke-width="1.4"/>
        <text class="t1" x="358" y="72">input_metadata_device</text><text class="t2" x="358" y="90">graph 捕获的 device 缓冲</text>
        <path class="fl2" d="M582,81 L672,81" stroke="#22d3ee" stroke-width="2" fill="none" marker-end="url(#a4)"/>
        <rect x="672" y="44" width="230" height="74" rx="10" fill="#0e2a33" stroke="#22d3ee" stroke-width="1.6"/>
        <text class="t1" x="724" y="66" fill="#22d3ee">CUDA Graph</text>
        <circle class="kn" cx="700" cy="92" r="6" fill="#22d3ee"/><circle class="kn" cx="724" cy="92" r="6" fill="#4f8cff" style="animation-delay:.35s"/>
        <circle class="kn" cx="748" cy="92" r="6" fill="#a78bfa" style="animation-delay:.7s"/><circle class="kn" cx="772" cy="92" r="6" fill="#34d399" style="animation-delay:1.05s"/>
        <circle class="kn" cx="796" cy="92" r="6" fill="#fbbf24" style="animation-delay:1.4s"/><circle class="kn" cx="820" cy="92" r="6" fill="#f87171" style="animation-delay:1.75s"/>
        <text class="t2" x="700" y="112">replay()</text>
        <!-- mini timeline 1 -->
        <rect x="342" y="128" width="120" height="22" rx="5" fill="#0e4a5c"/><text x="366" y="143" fill="#c9f4ff" font-size="10">copy H2D</text>
        <rect x="466" y="128" width="160" height="22" rx="5" fill="url(#gC3)"/><text x="500" y="143" fill="#062024" font-size="10" font-weight="700">graph replay</text>
        <text class="t2" x="640" y="143">串行:拷贝完才能 replay</text>

        <!-- Track 2 -->
        <text class="hdr" x="18" y="212">ZOS(input_on_device=True):直写共享 device 缓冲,免 recursive_copy_</text>
        <rect x="18" y="230" width="220" height="66" rx="10" fill="#16233f" stroke="#4f8cff" stroke-width="1.4"/>
        <text class="t1" x="34" y="254">pinned staging</text><text class="t2" x="34" y="272">prepare_decode_v4_zos 产物</text>
        <path class="fl2" d="M238,263 L342,263" stroke="#34d399" stroke-width="2" fill="none" marker-end="url(#a4)"/>
        <text class="t2" x="240" y="252" fill="#34d399">.cuda(non_blocking=True)</text>
        <rect x="342" y="230" width="240" height="66" rx="10" fill="#152a1f" stroke="#34d399" stroke-width="1.6"/>
        <text class="t1" x="358" y="254" fill="#34d399">graph 共享 device 源缓冲</text><text class="t2" x="358" y="272">source 与 device 同存储</text>
        <path class="fl2" d="M582,263 L672,263" stroke="#34d399" stroke-width="2" fill="none" marker-end="url(#a4)"/>
        <rect x="672" y="226" width="230" height="74" rx="10" fill="#0e2a33" stroke="#22d3ee" stroke-width="1.6"/>
        <text class="t1" x="724" y="248" fill="#22d3ee">CUDA Graph</text>
        <circle class="kn" cx="700" cy="274" r="6" fill="#22d3ee"/><circle class="kn" cx="724" cy="274" r="6" fill="#4f8cff" style="animation-delay:.35s"/>
        <circle class="kn" cx="748" cy="274" r="6" fill="#a78bfa" style="animation-delay:.7s"/><circle class="kn" cx="772" cy="274" r="6" fill="#34d399" style="animation-delay:1.05s"/>
        <circle class="kn" cx="796" cy="274" r="6" fill="#fbbf24" style="animation-delay:1.4s"/><circle class="kn" cx="820" cy="274" r="6" fill="#f87171" style="animation-delay:1.75s"/>
        <text class="t2" x="700" y="294">replay()</text>
        <!-- mini timeline 2: overlap -->
        <rect x="342" y="316" width="200" height="22" rx="5" fill="url(#gC3)"/><text x="380" y="331" fill="#062024" font-size="10" font-weight="700">replay step N</text>
        <rect class="ovl" x="472" y="344" width="200" height="22" rx="5" fill="#0e4a5c" stroke="#22d3ee"/><text x="490" y="359" fill="#c9f4ff" font-size="10">upload step N+1</text>
        <text class="t2" x="686" y="331" fill="#34d399">并行:上一步 replay 期间,</text>
        <text class="t2" x="686" y="347" fill="#34d399">下一步输入已在异步上传</text>
        <text class="t2" x="686" y="363" fill="#34d399">(含 GPU 修正 kernel)</text>

        <!-- padding -->
        <text class="hdr" x="18" y="420">batch padding:真实序列 + 占位序列 = graph 档位</text>
        <g>
          <rect x="18" y="436" width="238" height="34" rx="7" fill="url(#gC3)"/>
          <text x="30" y="457" fill="#062024" font-size="11" font-weight="700">seq 0…36(真实,total_q=37)</text>
          <rect class="pad" x="260" y="436" width="52" height="34" rx="7" fill="#243350" stroke="#8ea0c2" stroke-dasharray="4 3"/>
          <rect class="pad" x="316" y="436" width="52" height="34" rx="7" fill="#243350" stroke="#8ea0c2" stroke-dasharray="4 3" style="animation-delay:.5s"/>
          <rect class="pad" x="372" y="436" width="52" height="34" rx="7" fill="#243350" stroke="#8ea0c2" stroke-dasharray="4 3" style="animation-delay:1s"/>
          <text x="266" y="457" fill="#9fb3d9" font-size="10">pad</text><text x="322" y="457" fill="#9fb3d9" font-size="10">pad</text><text x="378" y="457" fill="#9fb3d9" font-size="10">pad</text>
          <text x="438" y="457" fill="#8ea0c2" font-size="11">→ graph_size=40(select 选中的捕获档位)</text>
        </g>
        <text class="t2" x="18" y="496">padding 序列来自 padding_seq_metadata_list(model_runner.py:187);占位元数据由 _placeholder_seq_metadata 生成,valid_token_mask 标记为 False,</text>
        <text class="t2" x="18" y="512">MoE 负载均衡的门控随机(gate_force_random)同样只作用于真实行——占位行不污染路由统计。</text>
      </svg>
      <div class="cap">图 4 · CUDA Graph 输入通路对比:非 ZOS 每步 recursive_copy_ H2D 后才能 replay;ZOS 下源缓冲即 device 存储(copy_inputs=False),上一步 replay 与下一步输入上传/修正并行;batch 以占位序列补齐到捕获档位</div>
    </div>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🎚️</span>档位选择与 padding</h3>
        <p>graph 按 <code>build_graph_batch_sizes</code> 生成的档位捕获(2 的幂预热 + 固定间隔 <code>DEEPINFER_CUDAGRAPH_BATCH_SIZE_INTERVAL</code> 默认 8,cuda_graph_runner.py:41-51);每步用 <code>select(total_q)</code> 二分选中档位(cuda_graph_runner.py:143-148),再把 <code>padding_seq_metadata_list</code> 的哑序列拼到 batch 尾部补齐(model_runner.py:184-191)。ZOS 下 <code>_correct_seqlens_qk</code> 计算 padding 数时也按同一档位对齐(worker.py:203-206)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">📷</span>捕获与销毁的生命周期</h3>
        <p>捕获发生在 <code>warm_up_model</code>(base.py:274-288)→ <code>capture_model</code>(model_runner.py:514-529):先在独立 <code>graph_stream</code> 上预热,再以共享 memory pool 捕获各档位,DFlash 投机图复用主图池(model_runner.py:531-559)。销毁必须显式:NCCL 在 graph 中会持有额外依赖,直接销毁进程组会挂起,故 <code>stop()</code> 先 <code>destroy_cuda_graphs()</code> 再 destroy(base.py:135-151;model_runner.py:633-644,注释链接 pytorch#115388)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">📊</span>性能曲线反哺调度器</h3>
        <p><code>profile_decode_perf</code>(model_runner.py:561-631)实测各档位 graph 的 decode 耗时(去尾平均、EP 组内归约),经 <code>decode_perf_curve</code> 交给 C++ Scheduler(llm_engine.py:268)。于是 ZOS 下调度器在 CPU 上做决策时,手里握着的是 GPU 实测性能曲线——"调度用性能数据,执行用 CUDA Graph",两者互为放大器。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">🧭</span>replay 前后的零开销计时</h3>
        <p><code>replay</code> 只做两件事:给 graph 计时乒乓缓冲换面(<code>flip_event_buffer</code>,timer.py:169-177,防止事件被在途 replay 复写)和 <code>graph.replay()</code>(cuda_graph_runner.py:150-154)。计时结果在下一步 <code>_post_process_step</code> 里 <code>cuda_graph_timer.flush_out()</code> 收账(worker.py:264-266)——同样延迟一步,同样与 GPU 重叠。</p>
      </div>
    </div>

    <div class="note">
      <b>CP &gt; 1 时的输入广播:</b>无论是否 ZOS,graph 执行前都要把输入元数据同步给 CP 从 rank:非张量字段走 <code>cp_broadcast_object</code>(shm),张量走 <code>cp_broadcast_multi_tensor</code>(input_metadata.py:120-128 的 <code>broadcast()</code>;由 <code>_run_model</code> 在 replay 前调用,cuda_graph_runner.py:64-65)。从 rank 只需 <code>total_q</code> 即可选出同一档位、共享同一份捕获缓冲(model_runner.py:216-230)。
    </div>
  </section>

  <!-- ============================================================ -->
  <section id="s6">
    <h2 class="sec"><span class="num">6</span>配置项一览</h2>
    <p class="lede">与异步调度直接相关的环境变量(定义集中在 <code>deepinfer/environ.py</code>)与关键代码常量。</p>
    <table class="tbl">
      <tr><th>配置项</th><th>定义位置</th><th>类型 / 默认</th><th>作用</th></tr>
      <tr><td><code>DEEPINFER_ZERO_OVERHEAD_SCHEDULING</code></td><td>environ.py:186</td><td>bool / 由引擎类型决定</td><td>ZOS 总开关。<code>EngineArgs.__post_init__</code> 按类型 setdefault:NORMAL/COMPLETION→1,PROMPT→0(arg_utils.py:51-55;engine_type.py:15-17)。影响调度器通信组(llm_engine.py:313)、后处理时机(worker.py:183)、CUDA Graph 输入通路(model_runner.py:78)、decode 准备函数(model_metadata_utils.py:143)等十余处分支</td></tr>
      <tr><td><code>DEEPINFER_GLOO_TIMEOUT</code></td><td>environ.py:117</td><td>秒 / 14400(4h)</td><td>gloo 默认进程组及全部 CPU 子组的 collective 超时(base.py:339)。ZOS 下控制面等待与长 GPU 段并行,需远大于默认 30 分钟</td></tr>
      <tr><td><code>DEEPINFER_DISABLE_SYNC_GUARD</code></td><td>environ.py:205</td><td>bool / false</td><td>debug 用:关闭 <code>forbid_cuda_sync</code> 守卫(utils.py:130-132),用于在 forward 里临时加会触发同步的打印/dump</td></tr>
      <tr><td><code>DEEPINFER_RINGBUFFER_WARNING_INTERVAL</code></td><td>environ.py:191</td><td>秒 / 60</td><td>shm ring 自旋等待的 debug 日志间隔(shm_broadcast.py:313)</td></tr>
      <tr><td><code>DEEPINFER_GC_INTERVAL_STEP</code></td><td>environ.py:192</td><td>step / 1000</td><td>周期 <code>gc.collect()</code> 间隔;worker 常驻 <code>gc.disable()</code>(base.py:102-106),collect 藏在 <code>pre_sampler_sync</code> 窗口(worker.py:165)</td></tr>
      <tr><td><code>DEEPINFER_ENFORCE_EAGER</code></td><td>environ.py:161</td><td>bool / false</td><td>关闭 CUDA Graph(model_runner.py:73)。ZOS 仍生效(延迟后处理/事件同步不依赖 graph),但失去 <code>input_on_device</code> 免拷贝通路</td></tr>
      <tr><td><code>DEEPINFER_CUDAGRAPH_BATCH_SIZE_INTERVAL</code></td><td>environ.py:162</td><td>int / 8</td><td>graph 档位间隔(cuda_graph_runner.py:41-51);档位越稀,padding 浪费越多、捕获越省</td></tr>
      <tr><td><code>DEEPINFER_USE_NEXTN_DECODE</code></td><td>environ.py:136</td><td>int / 5</td><td>MTP 投机长度。决定 ZOS 的 seqlens 修正幅度与 <code>max_batch_size = max_num_seqs × (1+nextn)</code>(model_runner.py:77)</td></tr>
      <tr><td><code>DEEPINFER_ENABLE_MTP_VARLEN</code></td><td>environ.py:138</td><td>bool / false</td><td>置信度调度变长验证。开启后 ZOS 需要 GPU 修正 + D2H 回读 seqlens(worker.py:218-234)与性能曲线引导调度</td></tr>
      <tr><td><code>DEEPINFER_PREFILL_ATTEMPT_INTERVAL</code></td><td>environ.py:181</td><td>step / 70</td><td>NORMAL 引擎 ALL 点间隔:全员有 prefill 活才集体切 prefill(scheduler.hpp:307-318),投票走 CPU gloo</td></tr>
      <tr><td><code>DEEPINFER_PREFILL_ANY_ATTEMPT_INTERVAL</code></td><td>environ.py:184</td><td>step / 100</td><td>ANY 保底间隔:任一 rank 有活即集体 prefill,孤立 rank 最多等这么多 decode step</td></tr>
      <tr><td><code>DEEPINFER_LOGGING_INTERVAL_STEP</code></td><td>environ.py:189</td><td>step / 100</td><td>统计日志间隔;日志由独立线程消费(stats_logger.py:116-127),不打断引擎线程</td></tr>
      <tr><td>(常量)MessageQueue 槽参数</td><td>parallel_state.py:124</td><td>1 MiB / 10 chunks</td><td>shm 广播环缓冲容量;超过单块的 payload 走 ZMQ 溢出通道</td></tr>
    </table>

    <div class="note">
      <b>统计口径的联动:</b>ZOS 下一次 <code>step()</code> 不再包含完整 GPU 工作,单步时长改用相邻两次 <code>step()</code> 的间隔:<code>step_dur = eng.last_step_interval if (envs.DEEPINFER_ZERO_OVERHEAD_SCHEDULING and step &gt; 0) else now - eng.step_start</code>(stats_logger.py:405)。benchmark 脚本的输出标签也直接打印 ZOS 状态(examples/benchmark.py:567 的 <code>-zos{...}</code>)。等价性测试则显式关掉它:yoco_equiv.py:476 将 <code>DEEPINFER_ZERO_OVERHEAD_SCHEDULING</code> 置 0 以获得逐步对齐的参考输出。
    </div>
  </section>

  <!-- ============================================================ -->
  <section id="s7">
    <h2 class="sec"><span class="num">7</span>总结</h2>
    <p class="lede">"零开销"不是把调度做快,而是把调度挪出 GPU 的时间轴——用软件流水线把 CPU 批调度、输出后处理、资源回收、GC、日志统计全部塞进 GPU 计算的掩护之下。</p>

    <ul class="feat">
      <li><b>架构:</b>LLMEngine 与 driver Worker 同进程同线程(llm_engine.py:402-413),CP 其余 rank 为守护子进程(llm_engine.py:377-395);从 rank 靠 shm 广发的 <code>(method, kwargs)</code> 驱动(base.py:129-133)。重叠不靠线程,靠"launch 即返回 + 延迟一步"。</li>
      <li><b>执行模型:</b><code>execute_model_step</code> 的四段轮——Forward 本步 → Post-process 上一步 → Sample 本步 → ZOS 下把本步状态存入 <code>prev_step_state</code>(worker.py:88-189);唯一等待点是上一步的 <code>sample_end_evt</code>(worker.py:263),通常已被 CPU 工作自然吸收。</li>
      <li><b>滞后修正:</b>remap 在 pinned CPU 上算好、<code>non_blocking</code> H2D,由 GPU kernel 用上一步采样输出修正 seqlens 并拼装 input_ids(worker.py:191-245;zos.cpp:84-112);varlen 场景 D2H 回读配 <code>d2h_evt</code> 事件(worker.py:229-234)。</li>
      <li><b>控制面:</b>方法分发走 1 MiB×10 的共享内存环形缓冲(parallel_state.py:124),单写多读、标志位无锁(shm_broadcast.py:320-387);DP 调度投票走 gloo CPU 组(llm_engine.py:313;scheduler.hpp:109、307-332)——控制面彻底不碰 NCCL、不进 device stream。</li>
      <li><b>CUDA Graph:</b>ZOS 使能 <code>input_on_device</code>,源缓冲与捕获缓冲同存储、跳过每步 <code>recursive_copy_</code>(model_runner.py:78;cuda_graph_runner.py:54-66);上一步 replay 与下一步输入上传并行;padding 哑序列补齐档位。</li>
      <li><b>工程护栏:</b><code>forbid_cuda_sync</code> 断言 launch 路径零同步(utils.py:119);<code>DeferredRelease</code> 把池释放/unpin 推迟一轮(llm_engine.py:67-119);在途抢占有专门记账豁免(scheduler.hpp:917-925、1214-1220);NUMA 绑核 + GC 抑制压平 CPU 抖动(base.py:102、178-179、347-357)。</li>
    </ul>

    <div class="grid c3">
      <div class="card reveal">
        <h3><span class="ico">🛰️</span>控制面 / 数据面分离</h3>
        <p>调度消息(小、频繁、时延敏感)走 shm + 标志位;模型张量(大、带宽敏感)走 NCCL/userbuffer;调度投票(需要全组一致)走 gloo CPU。三类流量互不干扰,是"GPU 永不等待 CPU"的通信学基础。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🔮</span>乐观推进 + 在途修正</h3>
        <p>调度器先按"上一步视角"乐观排出 batch,把"这一步的真实长度"留给 GPU 用上一步输出现场修正。这与 SWA 有界重演、DSpark 置信度调度共享同一种设计哲学:宁可事后修正,不在关键路径上等待。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🧾</span>一切皆可延迟一步</h3>
        <p>后处理、资源释放、块 unpin、GC、计时收账、日志输出——本特性的实现手法高度一致:当步只"collect",下一歩的重叠窗口里"release/flush"。阅读任何一段 ZOS 代码,先找它的"下一步在哪里结算"就能看懂。</p>
      </div>
    </div>

    <div class="note warn">
      <b>边界与限制:</b>PROMPT 引擎默认关闭(engine_type.py:17),prefill 步总是当场后处理;<code>DEEPINFER_ENFORCE_EAGER=1</code> 时 ZOS 仍在但失去免拷贝输入通路;批次完全换血时 <code>has_overlap=False</code> 直接跳过修正(worker.py:212-213);flush 收尾与 varlen 的 D2H 等待是仅有的两个显式同步点。跨机部署时 MessageQueue 假设 CP 组不跨节点、所有 reader 都是本地 reader(shm_broadcast.py:442-444)。
    </div>

    <div class="timeline">
      <div class="tl-item">
        <div class="tl-date">STEP N(GPU 忙)</div>
        <div class="tl-body">forward(N) / sample(N) 异步 launch;<code>sample_end_evt</code> 挂在采样尾部;本步状态进入 <code>prev_step_state</code>。</div>
      </div>
      <div class="tl-item">
        <div class="tl-date">STEP N+1(CPU 与 GPU 并行)</div>
        <div class="tl-body">CPU:scheduler.schedule(N+1) → clone/zero 下发 → forward(N+1) launch → post-process(N)(等 <code>sample_end_evt</code>)→ seqlens 修正(remap H2D + GPU kernel)→ sample(N+1) launch → pre_sampler_sync(延迟释放/GC)。</div>
      </div>
      <div class="tl-item">
        <div class="tl-date">STEP N+1(GPU 侧)</div>
        <div class="tl-body">H2D(remap/seqlens)→ 修正 kernel → forward(N+1) → sample(N+1) →(varlen)D2H + <code>d2h_evt</code>;graph replay 与下一步输入上传重叠。</div>
      </div>
      <div class="tl-item">
        <div class="tl-date">调用方视角</div>
        <div class="tl-body"><code>step()</code> 每次返回的是上一步的输出;结束后 <code>flush_inflight_reqs</code> 排干最后一个在途 step(llm.py:176-186)。</div>
      </div>
    </div>
  </section>

  <div class="pgnav">
    <span>DeepInfer 代码分析系列 · 由 ZCode 生成于 2026-11 · 本文所有 file:line 引用均核对自仓库当前代码</span>
    <span><a href="/docs/inference-engines/deepinfer/">← 返回系列总览</a></span>
  </div>
<script>
// 滚动显现动画
const io=new IntersectionObserver(es=>{es.forEach(e=>{if(e.isIntersecting){e.target.classList.add('on');io.unobserve(e.target)}})},{threshold:.12});
document.querySelectorAll('.reveal').forEach(el=>io.observe(el));
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>批次不变性推理与确定性采样</title><link>https://hccl.club/docs/inference-engines/deepinfer/06-batch-invariant/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/06-batch-invariant/</guid><description><![CDATA[<div class="fwdoc">
<style>
.fwdoc{--bg:#0b1020; --bg2:#0f1729; --panel:#141d33; --panel2:#1a2440;
  --border:#263352; --text:#dbe4f5; --muted:#8ea0c2;
  --accent:#4f8cff; --accent2:#22d3ee; --good:#34d399; --warn:#fbbf24; --bad:#f87171; --purple:#a78bfa;
  --code-bg:#0d1424; --radius:14px;
  --serif:"Noto Serif SC","Songti SC",serif;}
.fwdoc *{box-sizing:border-box;margin:0;padding:0}
.fwdoc{background:linear-gradient(160deg,var(--bg) 0%,var(--bg2) 60%,#0a0f1e 100%);color:var(--text);
  font-family:"PingFang SC","Microsoft YaHei","Segoe UI",system-ui,sans-serif;line-height:1.75;}
.fwdoc{flex:1;min-width:0;padding:36px 48px 80px}
@media(max-width:960px){.fwdoc{padding:24px 18px 60px}}
.fwdoc .hero{position:relative;border-radius:var(--radius);overflow:hidden;padding:46px 44px;margin-bottom:34px;
  background:radial-gradient(1200px 400px at 15% -20%,rgba(79,140,255,.28),transparent 60%),
             radial-gradient(900px 380px at 95% 0%,rgba(167,139,250,.20),transparent 55%),
             linear-gradient(135deg,#16213e,#101a30);border:1px solid var(--border)}
.fwdoc .hero .crumb{font-size:12px;color:var(--accent2);letter-spacing:1px;margin-bottom:12px}
.fwdoc .hero h1{font-size:34px;color:#fff;font-weight:800;letter-spacing:.5px;margin-bottom:10px}
.fwdoc .hero p.desc{color:var(--muted);max-width:760px;font-size:15px}
.fwdoc .hero .tags{margin-top:18px;display:flex;gap:10px;flex-wrap:wrap}
.fwdoc .hero .tag{font-size:12px;padding:4px 14px;border-radius:999px;border:1px solid var(--border);
  background:rgba(79,140,255,.10);color:var(--accent2)}
.fwdoc .tag.good{border-color:rgba(52,211,153,.4);color:var(--good);background:rgba(52,211,153,.08)}
.fwdoc .tag.warn{border-color:rgba(251,191,36,.4);color:var(--warn);background:rgba(251,191,36,.08)}
.fwdoc section{margin-bottom:44px;scroll-margin-top:20px}
.fwdoc h2.sec{display:flex;align-items:center;gap:12px;font-size:23px;color:#fff;margin-bottom:6px;padding-bottom:10px;border-bottom:1px solid var(--border)}
.fwdoc h2.sec .num{display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:10px;flex-shrink:0;
  background:linear-gradient(135deg,var(--accent),var(--purple));color:#fff;font-size:15px;font-weight:800}
.fwdoc .lede{color:var(--muted);font-size:14px;margin-bottom:20px}
.fwdoc .grid{display:grid;gap:18px}
.fwdoc .grid.c2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}
.fwdoc .grid.c3{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}
.fwdoc .card{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:var(--radius);padding:22px 24px;transition:transform .3s,border-color .3s,box-shadow .3s}
.fwdoc .card:hover{transform:translateY(-3px);border-color:rgba(79,140,255,.55);box-shadow:0 12px 34px -14px rgba(79,140,255,.35)}
.fwdoc .card h3{font-size:16.5px;color:#fff;margin-bottom:8px;display:flex;align-items:center;gap:9px}
.fwdoc .card h3 .ico{width:26px;height:26px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;
  background:rgba(79,140,255,.16);font-size:14px;flex-shrink:0}
.fwdoc .card p{font-size:13.5px;color:var(--muted)}
.fwdoc .card p code,.fwdoc .inline-code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1.5px 7px;border-radius:6px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px}
.fwdoc ul.feat{list-style:none}
.fwdoc ul.feat li{padding:9px 0 9px 30px;position:relative;font-size:14px;color:var(--text);border-bottom:1px dashed rgba(38,51,82,.6)}
.fwdoc ul.feat li:last-child{border-bottom:none}
.fwdoc ul.feat li::before{content:"▸";position:absolute;left:8px;color:var(--accent);font-weight:700;animation:fw-blink 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
@keyframes fw-blink{0%,100%{opacity:.35}50%{opacity:1}}
.fwdoc pre.code{background:var(--code-bg);border:1px solid var(--border);border-radius:12px;padding:18px 20px;
  overflow-x:auto;font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px;line-height:1.65;margin:14px 0;position:relative}
.fwdoc pre.code::before{content:"● ● ●";display:block;color:#3a4a70;font-size:10px;letter-spacing:3px;margin-bottom:10px}
.fwdoc pre.code .k{color:#c792ea}
.fwdoc pre.code .s{color:#89ddff}
.fwdoc pre.code .c{color:#5d7294;font-style:italic}
.fwdoc pre.code .f{color:#82aaff}
.fwdoc pre.code .n{color:#f78c6c}
.fwdoc pre.code .h{color:#ffcb6b}
.fwdoc .filepath{font-family:"JetBrains Mono",Consolas,monospace;font-size:11.5px;color:var(--accent2);
  background:rgba(34,211,238,.08);border:1px solid rgba(34,211,238,.25);border-radius:6px;padding:2px 10px;display:inline-block;margin-bottom:4px}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border)}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px}
.fwdoc table.tbl td{padding:10px 14px;border-top:1px solid var(--border);color:var(--text);vertical-align:top}
.fwdoc table.tbl tr{transition:background .2s}
.fwdoc table.tbl tr:nth-child(even) td{background:rgba(20,29,51,.5)}
.fwdoc table.tbl tr:hover td{background:rgba(79,140,255,.10)}
.fwdoc table.tbl td code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;font-family:Consolas,monospace;font-size:12px}
.fwdoc .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px}
.fwdoc .badge.merged{background:rgba(52,211,153,.15);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.open{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.closed{background:rgba(248,113,113,.13);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.nccl{background:rgba(251,191,36,.12);color:var(--warn);border:1px solid rgba(251,191,36,.4)}
.fwdoc .badge.hccl{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .badge.deepep{background:rgba(34,211,238,.12);color:var(--accent2);border:1px solid rgba(34,211,238,.4)}
.fwdoc .reveal{opacity:0;transform:translateY(26px);transition:opacity .7s cubic-bezier(.2,.7,.3,1),transform .7s cubic-bezier(.2,.7,.3,1)}
.fwdoc .reveal.on{opacity:1;transform:none}
.fwdoc .reveal.d1{transition-delay:.12s}
.fwdoc .reveal.d2{transition-delay:.24s}
.fwdoc .reveal.d3{transition-delay:.36s}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:20px;margin:18px 0;position:relative;overflow:hidden}
.fwdoc .figure .cap{text-align:center;font-size:12.5px;color:var(--muted);margin-top:10px}
.fwdoc .figure svg{width:100%;height:auto;display:block}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-flow 1.2s linear infinite}
@keyframes fw-flow{to{stroke-dashoffset:-14}}
.fwdoc .pulse{animation:fw-pulse 2s ease-in-out infinite;transform-origin:center}
@keyframes fw-pulse{0%,100%{opacity:.45;transform:scale(1)}50%{opacity:1;transform:scale(1.06)}}
.fwdoc .node-gpu{fill:#16233f;stroke:#4f8cff;stroke-width:1.6;rx:10}
.fwdoc .node-gpu-title{fill:#dbe4f5;font-size:13px;font-weight:700}
.fwdoc .token-dot{fill:#22d3ee}
.fwdoc .barrow{filter:drop-shadow(0 0 6px rgba(34,211,238,.7))}
.fwdoc .svg-lbl{font-family:"JetBrains Mono",Consolas,monospace;fill:#8ea0c2}
.fwdoc .svg-lbl-strong{font-family:"JetBrains Mono",Consolas,monospace;fill:#dbe4f5;font-weight:700}
.fwdoc .svg-note{font-family:"PingFang SC","Microsoft YaHei",sans-serif;fill:#8ea0c2}
.fwdoc .mk-move{animation:fw-mkMove 3.2s cubic-bezier(.45,.05,.55,.95) infinite}
@keyframes fw-mkMove{0%{transform:translateX(0);opacity:0}12%{opacity:1}88%{opacity:1}100%{transform:translateX(150px);opacity:0}}
.fwdoc .pulseBox{animation:fw-pulseBox 2.6s ease-in-out infinite}
@keyframes fw-pulseBox{0%,100%{stroke-opacity:.35}50%{stroke-opacity:1}}
.fwdoc .neq{animation:fw-neq 1.6s ease-in-out infinite}
@keyframes fw-neq{0%,100%{opacity:.35;transform:scale(1)}50%{opacity:1;transform:scale(1.15)}}
.fwdoc .stageGlow{animation:fw-stageGlow 4.8s linear infinite}
.fwdoc .stageGlow.s2{animation-delay:1.2s}
.fwdoc .stageGlow.s3{animation-delay:2.4s}
.fwdoc .stageGlow.s4{animation-delay:3.6s}
@keyframes fw-stageGlow{0%{fill:rgba(79,140,255,.06)}6%{fill:rgba(79,140,255,.28)}16%{fill:rgba(79,140,255,.06)}100%{fill:rgba(79,140,255,.06)}}
.fwdoc .valRun{animation:fw-valRun 4.8s linear infinite}
@keyframes fw-valRun{0%{opacity:0}8%{opacity:1}30%{opacity:1}36%{opacity:0}100%{opacity:0}}
.fwdoc .slotBar{animation:fw-slotBar 3.4s ease-in-out infinite}
@keyframes fw-slotBar{0%,100%{opacity:.25}50%{opacity:1}}
.fwdoc .rankShift{animation:fw-rankShift 5s ease-in-out infinite}
@keyframes fw-rankShift{0%,40%{transform:translateX(0)}60%,90%{transform:translateX(-38px)}100%{transform:translateX(0)}}
.fwdoc .blinkSoft{animation:fw-blinkSoft 2.2s ease-in-out infinite}
@keyframes fw-blinkSoft{0%,100%{opacity:.3}50%{opacity:1}}
.fwdoc .uChip{animation:fw-uChip 3s ease-in-out infinite}
@keyframes fw-uChip{0%,100%{fill:rgba(34,211,238,.10)}50%{fill:rgba(34,211,238,.32)}}
.fwdoc .timeline{position:relative;padding-left:34px}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .tl-item{position:relative;margin-bottom:20px}
.fwdoc .tl-item::before{content:"";position:absolute;left:-30px;top:7px;width:12px;height:12px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.18);animation:fw-pulse 2.4s infinite}
.fwdoc .tl-item .tl-date{font-size:11.5px;color:var(--accent2);letter-spacing:.5px}
.fwdoc .tl-item .tl-body{font-size:13.5px;color:var(--text);margin-top:3px}
.fwdoc .note{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13px;color:var(--text);margin:16px 0}
.fwdoc .note.warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .note.good{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .note b{color:#fff}
.fwdoc .pgnav{margin-top:60px;padding-top:20px;border-top:1px solid var(--border);color:#5a6b92;font-size:12px;
  display:flex;justify-content:space-between;flex-wrap:wrap;gap:10px}
.fwdoc .pgnav a{color:var(--accent2);text-decoration:none}
/* ===== 导入面板附加样式 ===== */
.fwdoc{border-radius:14px;margin:18px 0}
.fwdoc table.tbl{display:block;overflow-x:auto;max-width:100%}
@media (prefers-reduced-motion:reduce){
.fwdoc *,.fwdoc *::before,.fwdoc *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
.fwdoc .reveal{opacity:1!important;transform:none!important}
}

</style>

<!-- ============================================================ -->
  <section>
    <h2 class="sec"><span class="num">1</span>概述:两个承诺,一个物理事实</h2>
    <p class="lede">README 对这两个特性的定义只有两行,但它们背后的工程量横跨 GEMM 内核、注意力、MoE 通信与采样器。</p>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🧊</span>批次不变性 Batch-invariant inference</h3>
        <p>「keep model results identical across different batch compositions」—— 同一请求无论单独运行、还是与任意其他请求拼成大 batch,
        模型输出(logits / logprobs)<b>逐位一致</b>。开启方式:<code>DEEPINFER_BATCH_INVARIANT=1</code>(NVIDIA only)。
        见 <code>README.md:27</code>。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🎯</span>确定性采样 Deterministic sampling</h3>
        <p>「produce identical outputs for identical input tokens and sampling parameters」—— 相同输入 + 相同采样参数 ⇒ 相同输出 token。
        需要三件套:<code>DEEPINFER_BATCH_INVARIANT=1</code> + <code>DEEPINFER_ENABLE_MTP_VARLEN=0</code> +
        向 <code>SamplingParams</code> 传入固定 <code>seq_seed</code>(NVIDIA only)。见 <code>README.md:28</code>。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">∑</span>物理事实:浮点加法不满足结合律</h3>
        <p><code>(a+b)+c ≠ a+(b+c)</code>。GPU 上的归约(GEMM 分块累加、softmax/LSE 分块、MoE top-k 贡献合并)只要<b>累加顺序</b>随 batch 形状变化,
        结果就会在最后几个 ULP 上发散——再经 60+ 层 transformer 放大,最终 token 概率完全不同。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">🔬</span>定位:验证 / 评测模式</h3>
        <p>在 <code>deepinfer/environ.py:204</code> 中,<code>DEEPINFER_BATCH_INVARIANT</code> 被归入
        <b>Profiling &amp; Debug</b> 分组;评测入口 <code>eval/run_eval.py:74</code> 将其标注为
        「results independent of batch composition <b>(slower)</b>」——它是以性能换确定性的开关,而非默认服务态。</p>
      </div>
    </div>
    <div class="note good reveal">
      <b>两者的关系:</b>批次不变性是「模型数值」层面的承诺(确定性 logits);确定性采样在其上再叠加「采样 RNG」层面的承诺
      (RNG 状态只由 <code>(seq_seed, sample_position, sample_case)</code> 决定,与 batch 大小、行顺序、CUDA graph padding 全部解耦)。
      没有前者,后者的输入本身就不稳定;没有后者,贪心之外任何温度采样都无法复现。
    </div>
  </section>

  <!-- ============================================================ -->
  <section>
    <h2 class="sec"><span class="num">2</span>不确定性从哪里来:四条路径</h2>
    <p class="lede">在 <code>DEEPINFER_BATCH_INVARIANT=0</code> 的默认态,同一条请求在不同 batch 组合下会走过四类「形状敏感」的计算路径。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">①</span>GEMM 分块与调度</h3>
        <p>MoE grouped GEMM(<code>m_grouped_fp8_fp4_gemm_nt_contiguous</code>,<code>deepinfer/model_executor/models/v4_modules/mlp.py:119-128</code>)按
        <b>每 expert 实际收到的 token 数</b>(<code>psum_num_recv_tokens_per_expert</code>)划分 m 块——这个数由 dispatch 决定,而 dispatch 结果取决于
        batch 里<b>所有请求</b>的路由。lm_head 的 <code>bf16_gemm_nt</code>(<code>deepinfer/model_executor/layers/linear.py:27-33</code>)同理:m 维即 batch 行数,
        行数变化会改变 tile 划分与 split-k 策略,进而改变 K 维归约顺序。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">②</span>MoE combine 的多次归约</h3>
        <p>一条 token 的 top-k 个 expert 输出分散在多个 EP rank 上,combine 阶段要把它们加总。DeepEP-V2 的
        <code>allow_multiple_reduction</code> 允许归约<b>分多趟/多 chunk 完成</b>以提升吞吐,但分块方式与到达顺序受 batch 内路由分布影响,
        浮点加法顺序不再固定(详见第 3.4 节,<code>deepinfer/model_executor/parallel_utils/userbuffer.py:79</code>)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">③</span>注意力的调度与融合</h3>
        <p>decode 注意力走 FlashMLA 的 tile scheduler(<code>sched_meta</code>,<code>deepinfer/model_executor/layers/attention_backend.py:131</code>),
        block 在 SM 上的分配随 total_q 变化;prefill 的 <code>fused_norm_rope_attn_rope_cast</code> 融合核把 norm+rope+attention+rope+fp8 cast 融为一体,
        其输出量化与 batch 打包相关——批次不变模式下这颗融合核在 PROMPT 引擎被直接禁用(<code>deepinfer/model_executor/models/v4_modules/attn.py:87-92</code>)。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">④</span>调度与重排的「外部性」</h3>
        <p>EPLB 周期性重排按<b>窗口内各 expert 收到的 token 计数</b>重算放置(<code>deepinfer/model_executor/eplb/__init__.py:146-165</code>),
        计数本身就是 batch 组成的函数;DSpark 的 VARLEN 置信度调度按<b>全 batch 的置信度排名</b>分配验证预算
        (<code>schedule_mtp_varlen.py:70-98</code>)。这两者让「别的请求」直接改写「本请求」的执行计划。</p>
      </div>
    </div>

    <div class="figure reveal">
      <svg viewBox="0 0 1000 600" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="同一请求在不同 batch 组合下的归约路径分歧动画">
        <defs>
          <marker id="arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#4f8cff"/>
          </marker>
          <marker id="arrR" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#f87171"/>
          </marker>
        </defs>

        <text x="500" y="30" text-anchor="middle" class="svg-lbl-strong" font-size="17">同一请求 R:batch 组合如何改写它的归约路径</text>

        <!-- ============ 运行 A ============ -->
        <g>
          <text x="30" y="72" class="svg-note" font-size="13.5">运行 A:batch = [ R ](单独运行)</text>
          <rect x="30" y="84" width="940" height="196" rx="12" fill="#101a30" stroke="#263552"/>
          <text x="52" y="112" class="svg-lbl" font-size="12">token(R)</text>
          <g class="pulse"><circle cx="72" cy="140" r="7" class="token-dot barrow"/></g>
          <line x1="86" y1="140" x2="160" y2="140" stroke="#4f8cff" stroke-width="1.8" marker-end="url(#arr)"/>

          <rect x="164" y="112" width="104" height="56" rx="9" class="node-gpu pulseBox"/>
          <text x="216" y="136" text-anchor="middle" class="node-gpu-title" font-size="12">MoE gate</text>
          <text x="216" y="153" text-anchor="middle" class="svg-lbl" font-size="10.5">top-k 路由</text>

          <!-- 三个 expert -->
          <line x1="268" y1="140" x2="330" y2="108" stroke="#4f8cff" stroke-width="1.6" class="flowline"/>
          <line x1="268" y1="140" x2="330" y2="166" stroke="#4f8cff" stroke-width="1.6" class="flowline"/>
          <rect x="334" y="86" width="118" height="42" rx="8" class="node-gpu"/>
          <text x="393" y="103" text-anchor="middle" class="node-gpu-title" font-size="11.5">Expert E5</text>
          <text x="393" y="119" text-anchor="middle" class="svg-lbl" font-size="10">GEMM m 块 ×1</text>
          <rect x="334" y="144" width="118" height="42" rx="8" class="node-gpu"/>
          <text x="393" y="161" text-anchor="middle" class="node-gpu-title" font-size="11.5">Expert E17</text>
          <text x="393" y="177" text-anchor="middle" class="svg-lbl" font-size="10">GEMM m 块 ×1</text>
          <rect x="334" y="202" width="118" height="42" rx="8" class="node-gpu"/>
          <text x="393" y="219" text-anchor="middle" class="node-gpu-title" font-size="11.5">Expert E42</text>
          <text x="393" y="235" text-anchor="middle" class="svg-lbl" font-size="10">GEMM m 块 ×1</text>
          <line x1="268" y1="140" x2="330" y2="223" stroke="#4f8cff" stroke-width="1.6" class="flowline"/>

          <!-- 归约树:固定顺序单次 -->
          <line x1="452" y1="107" x2="560" y2="140" stroke="#34d399" stroke-width="1.8" class="flowline"/>
          <line x1="452" y1="165" x2="560" y2="166" stroke="#34d399" stroke-width="1.8" class="flowline"/>
          <line x1="452" y1="223" x2="560" y2="192" stroke="#34d399" stroke-width="1.8" class="flowline"/>
          <circle cx="584" cy="166" r="26" fill="#12291f" stroke="#34d399" stroke-width="2" class="pulseBox"/>
          <text x="584" y="172" text-anchor="middle" fill="#34d399" font-size="17" font-weight="700">Σ</text>
          <text x="584" y="214" text-anchor="middle" class="svg-lbl" font-size="10.5" fill="#34d399">单次归约</text>
          <text x="584" y="228" text-anchor="middle" class="svg-lbl" font-size="10.5" fill="#34d399">(E5+E17)+E42 顺序固定</text>

          <line x1="612" y1="166" x2="740" y2="166" stroke="#34d399" stroke-width="1.8" marker-end="url(#arr)"/>
          <rect x="744" y="136" width="200" height="60" rx="9" fill="#101a30" stroke="#34d399"/>
          <text x="844" y="160" text-anchor="middle" class="svg-lbl-strong" font-size="12">logit = −2.104981</text>
          <text x="844" y="181" text-anchor="middle" class="svg-lbl" font-size="10.5">逐位稳定的输出</text>
        </g>

        <!-- ============ 运行 B ============ -->
        <g>
          <text x="30" y="316" class="svg-note" font-size="13.5">运行 B:batch = [ R, A, B ](R 与他人拼车)</text>
          <rect x="30" y="328" width="940" height="212" rx="12" fill="#101a30" stroke="#263552"/>
          <text x="52" y="356" class="svg-lbl" font-size="12">token(R)</text>
          <g class="pulse"><circle cx="72" cy="384" r="7" class="token-dot barrow"/></g>
          <text x="52" y="404" class="svg-lbl" font-size="10" fill="#fbbf24">+ A、B 的 token 也涌入</text>
          <text x="52" y="418" class="svg-lbl" font-size="10" fill="#fbbf24">同一批 expert → m 变大</text>
          <line x1="86" y1="384" x2="160" y2="384" stroke="#4f8cff" stroke-width="1.8" marker-end="url(#arr)"/>

          <rect x="164" y="356" width="104" height="56" rx="9" class="node-gpu pulseBox"/>
          <text x="216" y="380" text-anchor="middle" class="node-gpu-title" font-size="12">MoE gate</text>
          <text x="216" y="397" text-anchor="middle" class="svg-lbl" font-size="10.5">路由同 A 运行</text>

          <line x1="268" y1="384" x2="330" y2="352" stroke="#4f8cff" stroke-width="1.6" class="flowline"/>
          <line x1="268" y1="384" x2="330" y2="410" stroke="#4f8cff" stroke-width="1.6" class="flowline"/>
          <line x1="268" y1="384" x2="330" y2="467" stroke="#4f8cff" stroke-width="1.6" class="flowline"/>
          <rect x="334" y="330" width="118" height="42" rx="8" class="node-gpu"/>
          <text x="393" y="347" text-anchor="middle" class="node-gpu-title" font-size="11.5">Expert E5</text>
          <text x="393" y="363" text-anchor="middle" class="svg-lbl" font-size="10" fill="#fbbf24">m 块划分改变 ⚡</text>
          <rect x="334" y="388" width="118" height="42" rx="8" class="node-gpu"/>
          <text x="393" y="405" text-anchor="middle" class="node-gpu-title" font-size="11.5">Expert E17</text>
          <text x="393" y="421" text-anchor="middle" class="svg-lbl" font-size="10" fill="#fbbf24">split-k 策略改变 ⚡</text>
          <rect x="334" y="446" width="118" height="42" rx="8" class="node-gpu"/>
          <text x="393" y="463" text-anchor="middle" class="node-gpu-title" font-size="11.5">Expert E42</text>
          <text x="393" y="479" text-anchor="middle" class="svg-lbl" font-size="10" fill="#fbbf24">K 维归约顺序改变 ⚡</text>

          <!-- 多次归约:两个 chunk -->
          <line x1="452" y1="351" x2="560" y2="404" stroke="#f87171" stroke-width="1.8" class="flowline"/>
          <line x1="452" y1="409" x2="560" y2="410" stroke="#f87171" stroke-width="1.8" class="flowline"/>
          <line x1="452" y1="467" x2="560" y2="436" stroke="#f87171" stroke-width="1.8" class="flowline"/>
          <rect x="540" y="382" width="88" height="56" rx="9" fill="#2a1420" stroke="#f87171" class="pulseBox"/>
          <text x="584" y="404" text-anchor="middle" fill="#f87171" font-size="12" font-weight="700">Σ chunk1</text>
          <text x="584" y="422" text-anchor="middle" class="svg-lbl" font-size="10" fill="#f87171">(E17+E42)</text>
          <rect x="648" y="382" width="88" height="56" rx="9" fill="#2a1420" stroke="#f87171" class="pulseBox"/>
          <text x="692" y="404" text-anchor="middle" fill="#f87171" font-size="12" font-weight="700">Σ chunk2</text>
          <text x="692" y="422" text-anchor="middle" class="svg-lbl" font-size="10" fill="#f87171">+ E5(后到)</text>
          <text x="620" y="462" text-anchor="middle" class="svg-lbl" font-size="10.5" fill="#f87171">allow_multiple_reduction:分块/顺序随 batch 变化</text>

          <line x1="740" y1="410" x2="774" y2="410" stroke="#f87171" stroke-width="1.8" marker-end="url(#arrR)"/>
          <rect x="778" y="380" width="166" height="60" rx="9" fill="#101a30" stroke="#f87171"/>
          <text x="861" y="404" text-anchor="middle" class="svg-lbl-strong" font-size="12">logit = −2.105037</text>
          <text x="861" y="425" text-anchor="middle" class="svg-lbl" font-size="10.5">最后几个 ULP 已经不同</text>
        </g>

        <!-- 发散徽章 -->
        <g class="neq" transform="translate(500,296)">
          <circle cx="0" cy="0" r="24" fill="#2a1420" stroke="#f87171" stroke-width="2"/>
          <text x="0" y="8" text-anchor="middle" fill="#f87171" font-size="24" font-weight="800">≠</text>
        </g>
        <text x="500" y="576" text-anchor="middle" class="svg-note" font-size="12.5">
          一处 ULP 级发散 → 60+ 层放大 → token 概率位级不同 → 采样分岔。<tspan fill="#4f8cff" font-weight="700">DEEPINFER_BATCH_INVARIANT=1</tspan> 的使命:让上下两条路径重新逐位重合。
        </text>
      </svg>
      <div class="cap">图 1(动画):同一请求 R 在不同 batch 组合下的归约路径分歧——GEMM 分块随 expert 负载变化、combine 归约分块/顺序变化,导致输出位级发散</div>
    </div>

    <div class="note warn reveal">
      <b>注意:</b>「数值位级不同」不等于「数学上错误」——两种路径都是对同一数学表达式的合法浮点求值。
      问题在于<b>不可复现</b>:回归测试的 golden 无法对齐、跨引擎(prefill/decode/投机)切换的 logits 漂移、评测指标抖动,都会因此产生。
    </div>
  </section>

  <!-- ============================================================ -->
  <section>
    <h2 class="sec"><span class="num">3</span>批次不变性的实现机制</h2>
    <p class="lede">一个环境变量,在四个层面同时收紧:kernel 库全局开关、注意力内核、prefill 融合核取舍、MoE combine 归约模式。</p>

    <h3 style="color:#fff;font-size:16px;margin:18px 0 8px">3.1 总开关:让 DeepGEMM / TileKernels 进入确定性模式</h3>
    <div class="filepath">deepinfer/worker/runtime_config.py:54-69</div>
    <pre class="code"><span class="k">def</span> <span class="f">configure_worker_kernels</span>() -> <span class="k">None</span>:
    <span class="s">"""Configure process-wide kernel library behavior used by workers."""</span>
    <span class="k">import</span> deep_gemm
    <span class="k">import</span> tile_kernels

    <span class="k">from</span> deepinfer <span class="k">import</span> PLATFORM, envs

    <span class="k">if</span> PLATFORM.is_npu:
        <span class="c"># TODO(NPU): 待完整支持 batch invariant 后移除</span>
        <span class="k">assert not</span> envs.DEEPINFER_BATCH_INVARIANT          <span class="c"># ← NVIDIA only 的直接出处</span>
    <span class="k">if</span> PLATFORM.is_gpu:
        deep_gemm.set_pdl(<span class="k">True</span>)
        tile_kernels.set_pdl(<span class="k">True</span>)
    <span class="k">if</span> envs.DEEPINFER_BATCH_INVARIANT <span class="k">or</span> PLATFORM.is_npu:  <span class="c"># TODO(NPU): 防止 CI 数值不稳定</span>
        deep_gemm.use_deterministic_algorithms(<span class="k">True</span>)     <span class="c"># ← GEMM 全局确定性开关</span>
        tile_kernels.use_deterministic_algorithms(<span class="k">True</span>)  <span class="c"># ← TileLang 算子全局确定性开关</span></pre>
    <p style="font-size:13.5px;color:var(--muted)">
      <code>deep_gemm.use_deterministic_algorithms(True)</code> 与 <code>tile_kernels.use_deterministic_algorithms(True)</code> 是进程级开关:
      之后所有经 DeepGEMM / TileKernels 发射的 GEMM 与算子都被限制在「结果与 m(batch 行数)无关」的确定性实现上
      (固定 tile 划分与固定归约树,放弃按形状自适应的 split-k / 高并发归约)。这覆盖了 MoE grouped GEMM
      (<code>mlp.py:109-137</code> 的 <code>m_grouped_fp8_fp4_gemm_nt_contiguous</code> / <code>m_grouped_bf16_gemm_nt_contiguous</code>,
      均带 <code>use_psum_layout=True</code> 的 psum 布局)、lm_head 的 <code>bf16_gemm_nt</code>、量化 / swiglu 等 TileLang 算子。
      顺带一提:NPU 上虽然禁止开启 BATCH_INVARIANT,但这两个确定性开关仍会打开——注释写明是为了「防止 CI 数值不稳定」。
    </p>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">3.2 注意力:FlashMLA 的 <code>enable_batch_invariant</code></h3>
    <p style="font-size:13.5px;color:var(--muted)">
      decode 注意力(含 DFlash draft 注意力)把开关一路透传给 FlashMLA,让 LSE / softmax 的在线归约与 tile 调度与 batch 形状解耦:
    </p>
    <div class="filepath">deepinfer/model_executor/layers/attention_backend.py:125-142(decode_mla_mqa_sparse)</div>
    <pre class="code">output, lse = flash_mla_with_kvcache(
    q=query,
    k_cache=key_cache,
    <span class="c">...</span>
    tile_scheduler_metadata=sched_meta,
    extra_k_cache=key_cache_extra,
    indices_in_kvcache=indices_in_kvcache_extra.unsqueeze(<span class="n">1</span>) <span class="k">if</span> indices_in_kvcache_extra <span class="k">is not None else None</span>,
    extra_topk_length=index_length_extra,
    enable_batch_invariant=batch_invariant,   <span class="c"># ← 由 envs.DEEPINFER_BATCH_INVARIANT 透传</span>
)</pre>
    <p style="font-size:13.5px;color:var(--muted)">
      调用点有两处:主模型 decode 注意力(<code>deepinfer/model_executor/models/v4_modules/attn.py:660-669</code>)与
      DFlash 投机 draft 注意力(<code>attn.py:994-1007</code>),均传 <code>batch_invariant=envs.DEEPINFER_BATCH_INVARIANT</code>。
    </p>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">3.3 prefill 的取舍:禁用 norm+rope+attn+cast 融合核</h3>
    <p style="font-size:13.5px;color:var(--muted)">
      高性能路径中,PROMPT 引擎的稠密 packed-KV prefill 会用 <code>fused_norm_rope_attn_rope_cast</code> 把 norm、rope、attention、rope、fp8 cast
      融成单核(输出 per-32 通道量化的 fp8+sf)。批次不变模式下这条路被<b>主动关闭</b>:
    </p>
    <div class="filepath">deepinfer/model_executor/models/v4_modules/attn.py:87-92</div>
    <pre class="code">self.use_fused_norm_rope_attn_rope_cast = (
    <span class="c"># disabled in dense packed-KV decoding</span>
    ((<span class="k">not</span> envs.DEEPINFER_BATCH_INVARIANT <span class="k">and</span> cfg.engine_type == EngineType.PROMPT) <span class="k">or</span> self.is_sparse <span class="k">or not</span> self.has_packed_kv)
    <span class="k">and</span> self.num_heads <span class="k">in</span> (<span class="n">64</span>, <span class="n">128</span>)
    <span class="k">and</span> PLATFORM.is_gpu
)</pre>
    <p style="font-size:13.5px;color:var(--muted)">
      注意条件里的 <code>not envs.DEEPINFER_BATCH_INVARIANT and cfg.engine_type == EngineType.PROMPT</code>:只影响<b>prefill 引擎的稠密 packed-KV</b> 路径;
      sparse 注意力与 decode 侧融合不受影响(decode 的确定性由 §3.2 的 FlashMLA 开关保证)。这是批次不变性「性能换确定性」最直白的一处代价。
    </p>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">3.4 MoE combine:单次归约 vs 多次归约</h3>
    <p style="font-size:13.5px;color:var(--muted)">
      EPBuffer(DeepEP-V2)创建时的关键一行——批次不变 <b>且</b> EPLB 周期重排启用时,禁用多次归约:
    </p>
    <div class="filepath">deepinfer/model_executor/parallel_utils/userbuffer.py:72-80(allocate_ep)</div>
    <pre class="code">ep_kwargs = <span class="f">dict</span>(
    group=ep_group,
    num_max_tokens_per_rank=max_num_tokens,
    hidden=hidden_size,
    num_topk=num_topk,
    use_fp8_dispatch=use_fp8_act,
    allow_hybrid_mode=<span class="k">True</span>,
    allow_multiple_reduction=<span class="k">not</span> (envs.DEEPINFER_BATCH_INVARIANT <span class="k">and</span> envs.DEEPINFER_EXPERT_REARRANGEMENT_STEP_INTERVAL > <span class="n">0</span>),
)</pre>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">⚡</span><code>allow_multiple_reduction=True</code>(默认)</h3>
        <p>combine 允许把一个 token 的 top-k 贡献<b>拆成多个 chunk 分批归约</b>,通信与计算更好重叠、吞吐更高;
        但分块方式与归约顺序与 batch 内的路由分布耦合——属于图 1 中的发散源。EPLB 重排关闭时(间隔为 0)DeepInfer 仍保留此模式。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🔒</span><code>=False</code>(BATCH_INVARIANT + 重排开启)</h3>
        <p>每 token 的全部贡献在<b>一次确定顺序的归约</b>中完成。触发条件是二者同时成立
        (<code>environ.py:204</code> 与 <code>environ.py:123</code> 联合判定):EPLB 重排本身依赖窗口化的 expert 计数
        (<code>deepinfer/model_executor/eplb/__init__.py:152-154</code>),是「与批量相关的时变布局」;此时再叠加乱序多次归约,连<b>相同输入的两次运行</b>都无法对齐。
        关掉多次归约后,给定同一 expert 放置,combine 数值恢复确定。</p>
      </div>
    </div>
    <div class="note reveal">
      <b>与 EPLB 的真实关系:</b>EPLB 重排(<code>eplb/__init__.py:222-278 _rearrange_experts</code>:窗口计数 →
      <code>rebalance_experts_global</code> → <code>expert_model_parallel_shuffle_inplace</code> 权重搬迁)的决策输入是
      <code>DEEPINFER_EXPERT_COUNT_WINDOW_SIZE</code>(默认 100,<code>environ.py:122</code>)个 step 内各 expert 收到的 token 数——
      这由 batch 组成决定。因此<b>重排开启时,「跨不同 batch 组合的绝对不变」在放置层面已不成立</b>;
      DeepInfer 在此场景下保证的是「相同 batch 序列 ⇒ 相同结果」(见 <code>tests/models/test_kl.py:105-107</code> 同时开启
      <code>BATCH_INVARIANT=1</code> 与重排间隔 1000 的用法)。examples 的 EPLB 默认配置为间隔 30 步重排一次
      (<code>examples/_config.py:78-83</code>)。
    </div>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">3.5 守护机制:sync guard 与确定性初始化的时序</h3>
    <p style="font-size:13.5px;color:var(--muted)">
      批次不变模式下大量使用确定性 GEMM,而 DeepGEMM 的某些路径在<b>首次使用时</b>会探测并缓存 SM locality(伴随同步)。
      DeepInfer 的 forward / sampling 发射区是「同步禁区」,由 <code>forbid_cuda_sync</code> 守卫强制:
    </p>
    <div class="filepath">deepinfer/worker/model_runner.py:307-325(execute_main_model)与 337-360(execute_sample)</div>
    <pre class="code"><span class="s">"""Run the main model forward pass (prepare input, launch forward).

    IMPORTANT: This function must NOT contain any cuda synchronize.
    """</span>
<span class="c">...</span>
<span class="k">with</span> (
    cpu_timer.record(<span class="s">"launch_forward"</span>, record_name=...),
    cuda_timer.record(<span class="s">"device_forward"</span>, scale=<span class="n">1</span>),
    forbid_cuda_sync(),            <span class="c"># ← forward 发射期禁止 CPU-GPU 同步</span>
):
    <span class="k">if</span> run_cuda_graph:
        model_output = self.cuda_graph_runner.replay(cuda_graph_used)
    <span class="k">else</span>:
        model_output = self.model(kv_caches=kv_caches, input_metadata=input_metadata)</pre>
    <div class="filepath">deepinfer/utils.py:119-132 + deepinfer/environ.py:205-206</div>
    <pre class="code"><span class="k">def</span> <span class="f">forbid_cuda_sync</span>() -> AbstractContextManager[<span class="k">None</span>]:
    <span class="s">"""Raise on any torch-visible CPU-GPU sync ... in this scope.

    DEEPINFER_DISABLE_SYNC_GUARD=1 时整体关闭(debug 用,如在 forward 里加会触发同步的打印/dump)
    """</span>
    <span class="k">if</span> envs.DEEPINFER_DISABLE_SYNC_GUARD:
        <span class="k">return</span> _noop_guard()               <span class="c"># ← debug 逃生门:整体关闭守卫</span>
    <span class="k">return</span> _sync_debug_arbiter.scope(<span class="s">"forbid"</span>)  <span class="c"># ← 本质:torch.cuda.set_sync_debug_mode("error")</span></pre>
    <ul class="feat">
      <li>守卫实现是 <code>_SyncDebugArbiter</code>(<code>deepinfer/utils.py:72-111</code>):按线程维护 forbid/allow 栈,任一线程处于 allow 时全局解除(<code>utils.py:100-108 _apply</code>),副作用是把 <code>torch.cuda.set_sync_debug_mode</code> 设为 <code>"error"</code>。</li>
      <li>EPLB 重排是合法同步点:整个 <code>_rearrange_experts</code> 用 <code>@allow_cuda_sync()</code> 装饰(<code>eplb/__init__.py:222</code>),重排发生在 sample 之后、下一步 forward 之前。</li>
      <li>确定性 GEMM 的初始化被<b>提前</b>到 userbuffer 分配期:<code>userbuffer.py:214-220</code> 注释写明 "Newer DeepGEMM probes and caches SM locality on first use, which synchronizes. Initialize it here, <b>before guarded forward and CUDA graph capture</b>"。</li>
      <li><code>DEEPINFER_DISABLE_SYNC_GUARD=1</code>(<code>environ.py:205-206</code>)是调试开关:在 forward 里加打印 / dump 触发同步时,可整体关闭守卫,不影响数值语义。</li>
    </ul>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">3.6 机制速查表</h3>
    <table class="tbl">
      <tr><th>层面</th><th>机制</th><th>代码位置</th><th>作用</th></tr>
      <tr><td>GEMM / 算子库</td><td><code>use_deterministic_algorithms(True)</code></td><td><code>deepinfer/worker/runtime_config.py:67-69</code></td><td>DeepGEMM + TileKernels 全局切换到与 m 无关的确定性实现(固定 tile / 归约树)</td></tr>
      <tr><td>decode 注意力</td><td><code>enable_batch_invariant</code></td><td><code>attention_backend.py:141</code>;调用点 <code>attn.py:666</code>、<code>attn.py:1002</code></td><td>FlashMLA 的 LSE/softmax 在线归约与 tile 调度与 batch 解耦</td></tr>
      <tr><td>prefill 注意力</td><td>禁用 fused norm+rope+attn+cast</td><td><code>attn.py:87-92</code></td><td>PROMPT 引擎稠密 packed-KV 路径退回非融合实现,消除与打包相关的量化/归约差异</td></tr>
      <tr><td>MoE combine</td><td><code>allow_multiple_reduction=False</code></td><td><code>userbuffer.py:79</code></td><td>BATCH_INVARIANT 且 EPLB 重排开启时,combine 强制单次定序归约</td></tr>
      <tr><td>CUDA graph</td><td>graph replay + padding 隔离</td><td><code>model_runner.py:326-327</code>;<code>deepseek.py:221-223</code></td><td>padding 行写入 dummy slot 0,graph 批次补齐不污染真实行</td></tr>
      <tr><td>发射期守护</td><td><code>forbid_cuda_sync</code></td><td><code>model_runner.py:324,359</code>;<code>utils.py:119-132</code></td><td>保证 forward / sampling 发射路径无同步(异步调度与 ZOS 的前提)</td></tr>
      <tr><td>平台断言</td><td><code>assert not BATCH_INVARIANT</code></td><td><code>runtime_config.py:61-63</code></td><td>NPU 暂不支持(TODO 标注),对应 README 的 NVIDIA only</td></tr>
    </table>
  </section>

  <!-- ============================================================ -->
  <section>
    <h2 class="sec"><span class="num">4</span>确定性采样:把 RNG 锚定在「序列位置」上</h2>
    <p class="lede">批次不变性解决了「输入分布相同」,确定性采样还要解决「随机数消费相同」——DeepInfer 的答案是完全抛弃全局 generator,
    用 <code>(seq_seed, sample_position, sample_case)</code> 三元组逐行哈希出均匀数。</p>

    <h3 style="color:#fff;font-size:16px;margin:18px 0 8px">4.1 seq_seed:从请求到 kernel 的完整链路</h3>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🔑</span>请求侧:SamplingParams.seq_seed</h3>
        <p>未传入时每条请求随机取 64 位(<code>random.getrandbits(64)</code>);传入整数则截断到 uint64——这就是「固定 seed」的入口。
        定义于 <code>deepinfer/sampling_params.py:44</code>(文档串)、<code>:61</code>(形参)、<code>:74</code>(构造)、<code>:85-91</code>(<code>_make_seed</code>)、<code>:104-105</code>(uint64 范围校验)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧵</span>C++ 侧:逐请求展开</h3>
        <p>引擎在 <code>csrc/engine/sequence.hpp:96,108</code> 把 <code>sampling_params.seq_seed</code> 存进请求元数据;
        采样输入准备时逐请求写入 pinned tensor:<code>csrc/engine/prepare_sample.cpp:161</code>
        <code>seq_seeds_ptr[parameter_offset++] = seq_metadata-&gt;sampling.seq_seed;</code>,再 H2D 拷贝到 GPU(<code>:263</code>)。</p>
      </div>
    </div>
    <div class="filepath">deepinfer/sampling_params.py:85-91</div>
    <pre class="code"><span class="k">@staticmethod</span>
<span class="k">def</span> <span class="f">_make_seed</span>(seed: <span class="k">int</span> | <span class="k">None</span>) -> <span class="k">int</span>:
    <span class="k">if</span> seed <span class="k">is</span> <span class="k">None</span>:
        <span class="k">return</span> random.getrandbits(<span class="n">64</span>)          <span class="c"># 缺省:每条请求独立随机 seed</span>
    <span class="k">if</span> isinstance(seed, <span class="k">int</span>):
        <span class="k">return</span> seed &amp; <span class="n">0xFFFF_FFFF_FFFF_FFFF</span>   <span class="c"># 固定:截断到 uint64 → 可复现</span>
    <span class="k">raise</span> TypeError()</pre>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">4.2 sample_position:位置,而不是行号</h3>
    <div class="filepath">csrc/engine/prepare_sample.cpp:197-206</div>
    <pre class="code"><span class="c">// prefill:采样位置 = 生成 token 在序列中的绝对位置(seqlen_k = prompt 长度)</span>
selected_token_indices_ptr[sample_offset] = model_output_offset + out_len - <span class="n">1</span>;
sample_positions_ptr[sample_offset++] = seq_metadata-&gt;seqlen_k;
<span class="c">...</span>
<span class="c">// decode:本 step 第一条 query 行的序列位置(其后每条验证行按 local_step 哈希展开)</span>
sample_positions_ptr[i] = seq_metadata-&gt;seqlen_k - seq_metadata-&gt;seqlen_q + <span class="n">1</span>;</pre>
    <p style="font-size:13.5px;color:var(--muted)">
      关键设计:<code>sample_position</code> 是<b>token 在序列中的绝对位置</b>,与该行被排在 batch 的第几行无关。
      MTP 验证阶段一行请求会展开成多条 query 行,<code>expand_sampling_params</code> 把 <code>local_step</code> 以
      <code>DRAFT_POS_HASH_MUL = 10000019</code>(<code>tilelang_ops/common.py:52</code>)混入位置:
      <code>sample_positions_q[row] = sample_positions[req] + local_step[row] * DRAFT_POS_HASH_MUL</code>
      (<code>deepinfer/model_executor/layers/tilelang_ops/sampler.py:65</code> 及内核版 <code>:69-109</code>)——
      同一请求的每条 draft 验证行因此拥有互不冲突且可复现的 RNG 键。
    </p>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">4.3 采样内核:两级定点 CDF 反演</h3>
    <p style="font-size:13.5px;color:var(--muted)">
      语义定义(纯 PyTorch 参考实现)——把 (seed, position, case) 哈希成均匀数 u,再对 CDF 反演:
    </p>
    <div class="filepath">deepinfer/model_executor/layers/tilelang_ops/random_sampling.py:58-84</div>
    <pre class="code"><span class="k">def</span> <span class="f">_hash_to_uniform</span>(seed: torch.Tensor) -> torch.Tensor:
    <span class="s">"""SplitMix64 hash of seed -&gt; uniform f64 in [0, 1); int64 ops emulate uint64."""</span>
    z = seed.to(torch.int64)
    z = z + i64(<span class="n">0x9E3779B97F4A7C15</span>)                        <span class="c"># 黄金比例 gamma</span>
    z = (z ^ urshift(z, <span class="n">30</span>)) * i64(<span class="n">0xBF58476D1CE4E5B9</span>)
    z = (z ^ urshift(z, <span class="n">27</span>)) * i64(<span class="n">0x94D049BB133111EB</span>)
    z = z ^ urshift(z, <span class="n">31</span>)
    <span class="k">return</span> urshift(z, <span class="n">11</span>).to(torch.float64) * (<span class="n">1.0</span> / (<span class="n">1</span> &lt;&lt; <span class="n">53</span>))   <span class="c"># u ∈ [0,1)</span>

<span class="k">def</span> <span class="f">random_sampling_ref</span>(probs, seq_seeds, sample_positions, is_nextn_predict=<span class="k">False</span>):
    sample_case = <span class="n">1</span> <span class="k">if</span> is_nextn_predict <span class="k">else</span> <span class="n">0</span>              <span class="c"># 0=新采样 / 1=拒绝重采</span>
    seq = (sample_positions.to(torch.int64) * <span class="n">3</span> + sample_case) * i64(<span class="n">0x9E3779B97F4A7C15</span>)
    combined = seq_seeds.to(torch.int64) + (seq ^ (seq * (<span class="n">1</span> &lt;&lt; <span class="n">13</span>)))
    u = _hash_to_uniform(combined).unsqueeze(-<span class="n">1</span>)
    cdf = probs.double().cumsum(dim=-<span class="n">1</span>)
    target = u * cdf[:, -<span class="n">1</span>:]
    <span class="k">return</span> (cdf &gt; target).long().argmax(dim=-<span class="n">1</span>).int()</pre>
    <p style="font-size:13.5px;color:var(--muted)">
      接口契约写在 <code>random_sampling.py:19-20</code> 的 docstring 里:<b>「Deterministic in (seq_seeds, sample_positions,
      is_nextn_predict): independent of batch size and row order; zero-probability columns are never sampled.」</b>
      CUDA 实现(<code>tilelang_ops/cuda/random_sampling.py</code>)是一条 TileLang 内核:每行一个 CTA,
      概率定点化为 <code>uint32</code>(scale = 2<sup>31</sup>,<code>Config</code> 定义于 <code>:8-36</code>;<code>float_to_fixed</code> <code>:38-50</code>),
      先粗后细两级搜索:
    </p>
    <div class="filepath">deepinfer/model_executor/layers/tilelang_ops/cuda/random_sampling.py:239-256</div>
    <pre class="code"><span class="k">with</span> T.Kernel(num_tokens, threads=THREADS) <span class="k">as</span> row:
    T.pdl_sync()
    acc_frag = T.alloc_fragment((BD,), SCALE_DTYPE)
    T.fill(acc_frag, <span class="n">0</span>)
    <span class="k">for</span> chunk <span class="k">in</span> T.unroll(N_CHUNKS, unroll_factor=<span class="n">4</span>):
        pf = T.alloc_fragment((BD,), T.float)
        T.copy(probs[row, chunk * BD], pf)
        accumulate(cfg, pf, acc_frag)      <span class="c"># 定点累加:acc[k] += floor(p[k + m*BD] * 2^31)</span>
    seq = sample_positions[row] * <span class="n">3</span> + sample_case
    rt_s = T.alloc_shared((<span class="n">2</span>), SCALE_DTYPE)
    offset = sample_offset(cfg, acc_frag, seq_seeds[row], seq, rt_s)   <span class="c"># 内部 T.rng_init(seed, seq) + 二分定位 lane k0</span>
    slot_probs = T.alloc_shared((N_SLOTS,), T.float)
    <span class="k">for</span> m <span class="k">in</span> T.Parallel(N_SLOTS):                     <span class="c"># 收集 k0 + m*BD 的算术序列,精细扫描命中列</span>
        col = offset + m * BD
        slot_probs[m] = T.Select(col &lt; vocab_size, probs[row, col], T.cast(<span class="n">0</span>, T.float))
    idx = sample_select(cfg, slot_probs, offset, rt_s)</pre>
    <ul class="feat">
      <li><b>粗筛</b>(<code>sample_offset</code>,<code>:94-157</code>):把整行按 <code>BD</code> 条 lane 折叠成定点部分和,画一个 64 位均匀数 <code>r % total</code>,二分定位目标 lane <code>k0</code>;vocab ≥ 8192 时 <code>BD=2048</code>(<code>:218-222</code>)。</li>
      <li><b>细扫</b>(<code>sample_select</code>,<code>:160-195</code>):仅对 <code>k0 + m*BD</code> 的算术序列做定点 cumsum,把余数 <code>r2</code> 精确定位到列——整行只需读两遍,vocab 129280 也只需 O(BD + N_SLOTS) 工作。</li>
      <li><b>定点化消除归约顺序歧义</b>:整数累加可结合,概率以 <code>floor(p * 2^31)</code> 编码后,任何分组求和都逐位一致;<code>uint64</code> 路径直接从 f32 的尾数/指数位精确构造定点值(<code>:38-50</code>)。</li>
      <li><b>零概率列永不被采出</b>:全零 mass 会触发 device_assert(<code>:125</code>);<code>allow_zero=True</code> 的拒绝重采路径安全回退。</li>
    </ul>

    <div class="figure reveal">
      <svg viewBox="0 0 1000 640" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="确定性采样流水线动画:seed 加 position 哈希出均匀数,定点 CDF 反演采样">
        <defs>
          <marker id="arr2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#4f8cff"/>
          </marker>
        </defs>
        <text x="500" y="30" text-anchor="middle" class="svg-lbl-strong" font-size="17">确定性采样流水线:RNG 只由 (seq_seed, sample_position, sample_case) 决定</text>

        <!-- batch 大小无关提示 -->
        <g>
          <rect x="60" y="56" width="180" height="60" rx="9" class="uChip" stroke="#22d3ee"/>
          <text x="150" y="80" text-anchor="middle" class="svg-lbl-strong" font-size="12">batch = 1</text>
          <text x="150" y="99" text-anchor="middle" class="svg-lbl" font-size="10.5">R 是第 0 行</text>
          <rect x="60" y="126" width="180" height="60" rx="9" class="uChip" stroke="#22d3ee"/>
          <text x="150" y="150" text-anchor="middle" class="svg-lbl-strong" font-size="12">batch = 256</text>
          <text x="150" y="169" text-anchor="middle" class="svg-lbl" font-size="10.5">R 可能是第 173 行</text>
          <text x="150" y="212" text-anchor="middle" class="svg-note" font-size="11.5" fill="#34d399">↓ 两者哈希出完全相同的 u ↓</text>
        </g>

        <!-- 输入三元组 -->
        <g>
          <rect x="300" y="52" width="250" height="140" rx="11" fill="#101a30" stroke="#4f8cff" class="stageGlow"/>
          <text x="425" y="76" text-anchor="middle" class="node-gpu-title" font-size="13">采样输入(逐行)</text>
          <text x="318" y="102" class="svg-lbl" font-size="11.5">seq_seed     = 0x51F3…A2C7 (uint64)</text>
          <text x="318" y="124" class="svg-lbl" font-size="11.5">sample_position = 2049 (序列绝对位置)</text>
          <text x="318" y="146" class="svg-lbl" font-size="11.5">sample_case  = 0 (0新采样/1拒绝重采/2验证)</text>
          <text x="318" y="172" class="svg-lbl" font-size="10" fill="#8ea0c2">sampling_params.py:85-91 · prepare_sample.cpp:161,198,206</text>
        </g>
        <line x1="554" y1="122" x2="608" y2="122" stroke="#4f8cff" stroke-width="2" marker-end="url(#arr2)"/>

        <!-- 哈希 -->
        <g>
          <rect x="612" y="52" width="330" height="140" rx="11" fill="#101a30" stroke="#a78bfa" class="stageGlow s2"/>
          <text x="777" y="76" text-anchor="middle" class="node-gpu-title" font-size="13">键混合 + SplitMix64</text>
          <text x="628" y="100" class="svg-lbl" font-size="10.5">seq = (2049*3 + case) * 0x9E3779B97F4A7C15</text>
          <text x="628" y="118" class="svg-lbl" font-size="10.5">combined = seed + (seq ^ (seq * 2^13))</text>
          <text x="628" y="140" class="svg-lbl" font-size="10.5">z += 0x9E37…; z=(z^z&gt;&gt;30)*0xBF58…; …</text>
          <text x="628" y="162" class="svg-lbl-strong" font-size="12" fill="#22d3ee">u = (z &gt;&gt;&gt; 11) / 2^53 = 0.372514…</text>
          <text x="628" y="182" class="svg-lbl" font-size="10" fill="#8ea0c2">random_sampling.py:58-84(参考实现)</text>
        </g>

        <!-- 第二行:概率→定点→两级搜索 -->
        <line x1="777" y1="196" x2="777" y2="240" stroke="#4f8cff" stroke-width="2" marker-end="url(#arr2)"/>
        <g>
          <rect x="60" y="244" width="420" height="150" rx="11" fill="#101a30" stroke="#22d3ee" class="stageGlow s3"/>
          <text x="270" y="268" text-anchor="middle" class="node-gpu-title" font-size="13">概率行 probs[0..V)(fp32)</text>
          <!-- 概率条 -->
          <g>
            <rect x="80"  y="286" width="40" height="26" rx="3" fill="#22d3ee" opacity=".75" class="slotBar"/>
            <rect x="124" y="286" width="26" height="26" rx="3" fill="#22d3ee" opacity=".45" class="slotBar" style="animation-delay:.3s"/>
            <rect x="154" y="286" width="90" height="26" rx="3" fill="#22d3ee" opacity=".22" class="slotBar" style="animation-delay:.6s"/>
            <rect x="248" y="286" width="26" height="26" rx="3" fill="#34d399" opacity=".9"  class="slotBar" style="animation-delay:.9s"/>
            <rect x="278" y="286" width="120" height="26" rx="3" fill="#22d3ee" opacity=".22" class="slotBar" style="animation-delay:1.2s"/>
            <rect x="402" y="286" width="56" height="26" rx="3" fill="#22d3ee" opacity=".35" class="slotBar" style="animation-delay:1.5s"/>
            <text x="270" y="332" text-anchor="middle" class="svg-lbl" font-size="10.5">floor(p * 2^31) → uint32 定点(加法可结合,归约顺序无关)</text>
            <text x="270" y="352" text-anchor="middle" class="svg-lbl" font-size="10" fill="#8ea0c2">cuda/random_sampling.py:8-50 Config / float_to_fixed</text>
            <text x="270" y="378" text-anchor="middle" class="svg-lbl" font-size="10.5" fill="#34d399">命中列:token #8512(绿色段)</text>
          </g>
        </g>
        <line x1="484" y1="319" x2="540" y2="319" stroke="#4f8cff" stroke-width="2" marker-end="url(#arr2)"/>

        <!-- 两级搜索 -->
        <g>
          <rect x="544" y="244" width="398" height="150" rx="11" fill="#101a30" stroke="#fbbf24" class="stageGlow s4"/>
          <text x="743" y="268" text-anchor="middle" class="node-gpu-title" font-size="13">两级 CDF 反演(每行一个 CTA)</text>
          <text x="560" y="294" class="svg-lbl" font-size="11">① 粗筛:BD 条 lane 定点部分和 → block_cumsum</text>
          <text x="560" y="314" class="svg-lbl" font-size="11">   r = u 对应的随机数 % total → 二分定位 lane k0</text>
          <text x="560" y="340" class="svg-lbl" font-size="11">② 细扫:gather k0 + m*BD 算术序列 → cumsum → 命中列</text>
          <text x="560" y="366" class="svg-lbl" font-size="10" fill="#8ea0c2">sample_offset :94-157 · sample_select :160-195</text>
          <text x="560" y="386" class="svg-lbl" font-size="10.5" fill="#34d399">输出 int32 token id — 与行号 / batch 无关</text>
        </g>

        <!-- 底部结论 -->
        <g>
          <rect x="60" y="424" width="880" height="76" rx="11" fill="rgba(52,211,153,.06)" stroke="#34d399"/>
          <text x="500" y="454" text-anchor="middle" class="svg-lbl-strong" font-size="13" fill="#34d399">RNG 状态 = f(seq_seed, sample_position, sample_case)</text>
          <text x="500" y="478" text-anchor="middle" class="svg-note" font-size="12">与 batch 大小无关 · 与行顺序无关 · 与 CUDA graph padding 无关 · 零概率列永不被采出</text>
        </g>

        <!-- 命中动画:u 线落到概率条上 -->
        <g class="mk-move"><circle cx="497" cy="319" r="5" fill="#fbbf24"/></g>
        <g class="valRun">
          <text x="770" y="222" text-anchor="middle" class="svg-lbl-strong" font-size="12" fill="#22d3ee">u = 0.372514…</text>
        </g>
        <text x="500" y="540" text-anchor="middle" class="svg-note" font-size="12.5">
          MTP 验证行复用同一构造:local_step 以 <tspan class="svg-lbl" fill="#89ddff">DRAFT_POS_HASH_MUL=10000019</tspan> 混入位置(tilelang_ops/sampler.py:65);
        </text>
        <text x="500" y="562" text-anchor="middle" class="svg-note" font-size="12.5">
          draft 采样走独立 RNG 命名空间 <tspan class="svg-lbl" fill="#89ddff">_MTP_SEED_OFFSET=1000000007</tspan>(fused_sample.py:15),与目标分布采样流互不干扰。
        </text>
        <text x="500" y="596" text-anchor="middle" class="svg-lbl" font-size="11" fill="#5a6b92">random_sampling.py:19-20 接口契约:"Deterministic in (seq_seeds, sample_positions, is_nextn_predict)"</text>
      </svg>
      <div class="cap">图 2(动画):确定性采样流水线——(seq_seed, sample_position, sample_case) 哈希出 u,定点两级 CDF 反演命中 token;batch=1 与 batch=256 得到同一结果</div>
    </div>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">4.4 fused_sample:一个内核完成变换 + 采样 + 拒绝验证</h3>
    <p style="font-size:13.5px;color:var(--muted)">
      生产路径中,<code>process_sampling</code>(<code>deepinfer/model_executor/layers/sampler_utils.py:113-196</code>)把
      temperature / top-p / top-k / log-softmax 与采样(以及投机解码的拒绝采样)全部熔进 <code>fused_sample</code> 这一条 TileLang 内核
      (<code>tilelang_ops/fused_sample.py:18-118</code>)。seed 在内核里逐行取用:<code>cuda/fused_sample.py:227</code>
      <code>seed_val = seq_seeds[row] + seed_offset</code>,其中 <code>seed_offset = _MTP_SEED_OFFSET</code>(仅当 <code>tag="mtp"</code>,
      <code>fused_sample.py:15,93</code>)。三种 RNG 流在同一行内按 <code>position*3 + case</code> 区分:
    </p>
    <table class="tbl">
      <tr><th>case(seq)</th><th>用途</th><th>参考实现</th><th>CUDA 内核</th></tr>
      <tr><td><code>pos*3 + 0</code></td><td>全新采样(fresh sample)</td><td><code>random_sampling.py:79</code>(<code>sample_case=0</code>)</td><td><code>cuda/fused_sample.py:450</code></td></tr>
      <tr><td><code>pos*3 + 1</code></td><td>拒绝后的残差重采(<code>is_nextn_predict=True</code>)</td><td><code>random_sampling.py:78</code>(<code>sample_case=1</code>)</td><td><code>cuda/fused_sample.py:481</code></td></tr>
      <tr><td><code>pos*3 + 2</code></td><td>投机验证的接受判定(与 u 比较)</td><td><code>fused_sample.py:239-241</code></td><td><code>cuda/fused_sample.py:392-393</code></td></tr>
    </table>
    <div class="filepath">deepinfer/model_executor/layers/tilelang_ops/fused_sample.py:239-246(拒绝采样参考实现)</div>
    <pre class="code">verify_seq = sample_positions.to(torch.int64) * <span class="n">3</span> + <span class="n">2</span>
verify_combined = seed_block ^ (verify_seq * i64(<span class="n">0x9E3779B97F4A7C15</span>))
U = _hash_to_uniform(verify_combined).to(accept_lp.dtype)
accepted = (accept_lp.exp() &gt; U).masked_fill_(sentinel_mask, <span class="k">False</span>)
accept_verify = torch.where(is_verify, accepted, torch.ones_like(accepted))

reject_sample = random_sampling_ref(residual, seed_block, sample_positions, is_nextn_predict=<span class="k">True</span>)
sample_result = torch.where(is_verify, torch.where(accept_verify, draft_tids, reject_sample), sample_result)</pre>
    <p style="font-size:13.5px;color:var(--muted)">
      其中 <code>residual = max(target_prob − exp(draft_logprob − DRAFT_PROB_PENALTY), 0)</code>,
      <code>DRAFT_PROB_PENALTY = 5e-5</code>(<code>tilelang_ops/common.py:53</code>,文档串给出输出分布对 target 分布的偏差界证明)。
      接受 / 拒绝 / 重采三个随机决定各自独立哈希,任何一步都只依赖本行的 (seed, position)。
    </p>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">4.5 force_topk:固定在 top-k 子空间里采样</h3>
    <p style="font-size:13.5px;color:var(--muted)">
      <code>DEEPINFER_SAMPLER_FORCE_TOPK</code>(<code>environ.py:157</code>;examples 默认 4096,
      <code>examples/offline_inference.py:17</code>)让采样器先对每行 logits 取 top-k
      (<code>sampler_utils.py:167</code>:<code>topk(logits, force_topk, False, indices_type=torch.int32)</code>),
      之后 softmax / top-p / 采样全部发生在该 k 维子空间,token id 经 <code>token_index</code> 映射还原
      (<code>sampler.py:460-467</code> <code>map_lookup(mode="by_index")</code>;logprob 反查用 <code>by_key</code>,<code>sampler.py:494-499</code>)。
      top-k 的选择逐行独立(行内值排序),候选集合与 batch 无关;投机验证时 <code>remap_draft_topk</code>
      (<code>sampler_utils.py:172-180</code>)把上一轮 draft 的 top-k 空间对齐到本轮 fresh top-k 空间,保证拒绝比较发生在同一坐标系。
      类文档(<code>sampler.py:91</code>)总结:「force_topk: 只在 top-k 个 token 上做 softmax/采样,减少计算量,需额外维护 token_index 映射」。
    </p>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">4.6 sum_smaller_probs:给「分布正确性」提供可检验的统计量</h3>
    <div class="filepath">deepinfer/model_executor/layers/tilelang_ops/sum_smaller_probs.py:14-18</div>
    <pre class="code"><span class="s">"""Inclusive CDF after sorting tokens by ascending probability. Per row,
sum probabilities through the sampled token; equal-probability tokens are
ordered by column index."""</span></pre>
    <ul class="feat">
      <li>由 <code>DEEPINFER_COMPUTE_SUM_SMALLER_PROBS</code>(<code>environ.py:111</code>)开启,采样器在 prefill 与 decode 两条路径都计算(<code>sampler.py:104</code>;<code>:501-509</code>、<code>:616-622</code>);force_topk 开启时先在 top-k 空间定位再求和。</li>
      <li>语义:按概率升序的包含 CDF——「比采样 token 概率更小的全部概率之和(含同概率中列号更小者)」。它与 token_logprobs 一起构成随机化 PIT 检验的输入:<code>u = ssp − p·v</code> 应当服从 U(0,1)(<code>tests/models/test_sampler.py:78-94</code> pit_ks)。</li>
      <li>这是「确定性采样分布正确」的验证抓手:逐位可复现的采样器 + KS 检验通过的分布,共同支撑确定性承诺(见第 7 节)。</li>
    </ul>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">4.7 decode_token_blacklist:确定性的 token 黑名单</h3>
    <div class="filepath">deepinfer/model_executor/layers/sampler.py:107-112 与 166-169</div>
    <pre class="code"><span class="c"># __init__:解析环境变量为 GPU 上的 token id 张量</span>
<span class="k">if</span> blacklist := envs.DEEPINFER_DECODE_TOKEN_BLACKLIST:
    values = parse_values(blacklist, <span class="n">0</span>, self.vocab_size - <span class="n">1</span>, env_key=<span class="s">"DEEPINFER_DECODE_TOKEN_BLACKLIST"</span>)
    self.decode_token_blacklist = torch.tensor(values, dtype=torch.long).cuda()

<span class="c"># forward(driver 路径):屏蔽 blacklist 中的 token</span>
<span class="k">if</span> self.decode_token_blacklist <span class="k">is not None</span>:
    logits.index_fill_(-<span class="n">1</span>, self.decode_token_blacklist, -torch.inf)</pre>
    <p style="font-size:13.5px;color:var(--muted)">
      环境变量定义于 <code>environ.py:158</code>;评测入口的默认黑名单 <code>"0,2,129262..129264"</code>
      (<code>eval/run_eval.py:73</code>)。它是一个与 batch 无关的确定性屏蔽(在采样前把 logits 置 −inf),
      常用于评测时封禁特殊 token——与确定性采样天然兼容。
    </p>

    <h3 style="color:#fff;font-size:16px;margin:26px 0 8px">4.8 环境变量速查</h3>
    <table class="tbl">
      <tr><th>环境变量</th><th>类型 / 默认</th><th>作用</th><th>定义位置</th></tr>
      <tr><td><code>DEEPINFER_BATCH_INVARIANT</code></td><td>bool / 0</td><td>批次不变性总开关(Profiling &amp; Debug 分组,NVIDIA only)</td><td><code>deepinfer/environ.py:204</code></td></tr>
      <tr><td><code>DEEPINFER_DISABLE_SYNC_GUARD</code></td><td>bool / 0</td><td>关闭 forbid_cuda_sync 守卫(debug:允许 forward/sampling 发射期同步)</td><td><code>deepinfer/environ.py:205-206</code></td></tr>
      <tr><td><code>DEEPINFER_SAMPLER_FORCE_TOPK</code></td><td>int / 0</td><td>采样固定在每行 top-k 子空间进行,维护 token_index 映射</td><td><code>deepinfer/environ.py:157</code></td></tr>
      <tr><td><code>DEEPINFER_COMPUTE_SUM_SMALLER_PROBS</code></td><td>bool / 0</td><td>计算升序包含 CDF(采样分布 PIT/KS 检验用)</td><td><code>deepinfer/environ.py:111</code></td></tr>
      <tr><td><code>DEEPINFER_DECODE_TOKEN_BLACKLIST</code></td><td>str / 空</td><td>采样前将黑名单 token 的 logits 置 −inf</td><td><code>deepinfer/environ.py:158</code></td></tr>
      <tr><td><code>DEEPINFER_ENABLE_MTP_VARLEN</code></td><td>bool / 0</td><td>DSpark 置信度调度的变长验证(确定性采样需 =0)</td><td><code>deepinfer/environ.py:138</code></td></tr>
      <tr><td><code>DEEPINFER_USE_NEXTN_DECODE</code></td><td>int / 5</td><td>最大投机 draft 长度(0 关闭投机解码)</td><td><code>deepinfer/environ.py:136-137</code></td></tr>
      <tr><td><code>DEEPINFER_EXPERT_REARRANGEMENT_STEP_INTERVAL</code></td><td>int / 0</td><td>EPLB 重排周期;与 BATCH_INVARIANT 共同决定 combine 归约模式</td><td><code>deepinfer/environ.py:123</code></td></tr>
      <tr><td><code>DEEPINFER_EXPERT_COUNT_WINDOW_SIZE</code></td><td>int / 100</td><td>重排决策的 expert 计数窗口</td><td><code>deepinfer/environ.py:122</code></td></tr>
    </table>
  </section>

  <!-- ============================================================ -->
  <section>
    <h2 class="sec"><span class="num">5</span>与投机解码的交互:为什么确定性采样要求 MTP_VARLEN=0</h2>
    <p class="lede">批次不变性可以与投机解码共存;确定性采样不行——分歧点在 DSpark 的「置信度调度」把验证预算变成了全 batch 的竞争资源。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">✅</span>固定宽度验证(MTP_VARLEN=0)与 BATCH_INVARIANT 兼容</h3>
        <p><code>tests/models/test_batch_invariant.py:33</code> 的用例直接以 <code>use_nextn_decode=5</code> +
        <code>DEEPINFER_BATCH_INVARIANT=1</code> 运行:每条请求本轮验证 <code>seqlen_q = 上轮接受数 + 1</code> 条 query 行,
        完全由<b>该请求自身的接受历史</b>决定——请求局部量,与 batch 无关。验证行的 RNG 键由
        <code>(seed, position + local_step·DRAFT_POS_HASH_MUL)</code> 唯一确定(<code>tilelang_ops/sampler.py:65</code>),
        接受判定用 <code>pos*3+2</code> 流,残差重采用 <code>pos*3+1</code> 流,三者互相独立且可复现。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">⛔</span>VARLEN 置信度调度:验证数量是 batch 的函数</h3>
        <p><code>DEEPINFER_ENABLE_MTP_VARLEN=1</code> 后,每步的 <code>seqlens_q</code> 由
        <code>compute_seqlens_q_by_confidence_rates(total_q, remap, prev_confidence_rates, seqlens_q)</code>
        (<code>deepinfer/worker/worker.py:218-219</code>)计算:把全 batch 所有 (请求, draft 位) 的<b>累积置信度</b>拉平排名,
        按预算 <code>total_q − num_seqs</code> 竞争额外的验证名额(<code>schedule_mtp_varlen.py:70-98</code>)。
        换一批邻居,排名就变,本请求本轮验证的 draft 数就变——调度层面已经与 batch 组成耦合,
        「相同输入 ⇒ 相同输出」的承诺无从谈起。这就是 README 要求确定性采样必须
        <code>DEEPINFER_ENABLE_MTP_VARLEN=0</code> 的原因(<code>README.md:28</code>)。</p>
      </div>
    </div>

    <div class="filepath">deepinfer/model_executor/layers/tilelang_ops/schedule_mtp_varlen.py:70-98(参考实现摘录)</div>
    <pre class="code">extra_budget = total_q - num_seqs  <span class="c"># number of extra tokens to distribute</span>
flat_rates = cum_rates.reshape(-<span class="n">1</span>)          <span class="c"># 全 batch 的 (seq, pos) 累积置信度</span>
<span class="c"># Stable sort descending by rate; for equal rates, original order (lower index first) is preserved</span>
sorted_indices = torch.argsort(flat_rates, descending=<span class="k">True</span>, stable=<span class="k">True</span>)
<span class="c">...</span>
wins = (ranks &lt; extra_budget).to(torch.int32).sum(dim=<span class="n">1</span>)   <span class="c"># 每条请求赢得的额外验证名额</span>
<span class="c"># Each sequence gets 1 base token + number of extra positions won</span>
seqlens_q.copy_(<span class="n">1</span> + wins)</pre>

    <div class="figure reveal">
      <svg viewBox="0 0 1000 560" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="固定验证与 VARLEN 置信度竞争调度的对比动画">
        <defs>
          <marker id="arr3" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#4f8cff"/>
          </marker>
        </defs>
        <text x="500" y="30" text-anchor="middle" class="svg-lbl-strong" font-size="17">固定验证 vs VARLEN 置信度竞争:验证预算归谁?</text>

        <!-- 上:固定验证 -->
        <g>
          <text x="30" y="68" class="svg-note" font-size="13.5">上:MTP_VARLEN = 0 —— 固定验证(请求局部,batch 无关)</text>
          <rect x="30" y="80" width="940" height="150" rx="12" fill="#101a30" stroke="#263552"/>
          <g>
            <rect x="60" y="106" width="130" height="42" rx="8" class="node-gpu"/><text x="125" y="132" text-anchor="middle" class="node-gpu-title" font-size="12">请求 R1</text>
            <rect x="60" y="160" width="130" height="42" rx="8" class="node-gpu"/><text x="125" y="186" text-anchor="middle" class="node-gpu-title" font-size="12">请求 R2</text>
          </g>
          <line x1="190" y1="127" x2="360" y2="127" stroke="#34d399" stroke-width="2" class="flowline" marker-end="url(#arr3)"/>
          <line x1="190" y1="181" x2="360" y2="181" stroke="#34d399" stroke-width="2" class="flowline" marker-end="url(#arr3)"/>
          <rect x="364" y="100" width="270" height="52" rx="9" fill="#12291f" stroke="#34d399"/>
          <text x="499" y="121" text-anchor="middle" class="svg-lbl-strong" font-size="11.5" fill="#34d399">R1:验证 上轮接受数 + 1 条 draft</text>
          <text x="499" y="140" text-anchor="middle" class="svg-lbl" font-size="10">seqlen_q 只依赖 R1 自己的接受历史</text>
          <rect x="364" y="154" width="270" height="52" rx="9" fill="#12291f" stroke="#34d399"/>
          <text x="499" y="175" text-anchor="middle" class="svg-lbl-strong" font-size="11.5" fill="#34d399">R2:验证 上轮接受数 + 1 条 draft</text>
          <text x="499" y="194" text-anchor="middle" class="svg-lbl" font-size="10">与 R1 是否在 batch 里毫无关系</text>
          <text x="700" y="140" class="svg-lbl" font-size="11" fill="#34d399">✓ 每行 RNG 键 = (seed, pos+step·10000019)</text>
          <text x="700" y="162" class="svg-lbl" font-size="11" fill="#34d399">✓ 接受/重采用 pos*3+2 / pos*3+1 独立流</text>
          <text x="700" y="184" class="svg-lbl" font-size="11" fill="#34d399">✓ 与 BATCH_INVARIANT=1 完全兼容</text>
        </g>

        <!-- 下:VARLEN -->
        <g>
          <text x="30" y="266" class="svg-note" font-size="13.5">下:MTP_VARLEN = 1 —— 置信度竞争调度(全 batch 排名,batch 相关)</text>
          <rect x="30" y="278" width="940" height="212" rx="12" fill="#101a30" stroke="#263552"/>

          <!-- 预算条 -->
          <text x="60" y="306" class="svg-lbl" font-size="11">验证预算 total_q(全 batch 共享):</text>
          <rect x="250" y="292" width="600" height="22" rx="5" fill="#0d1424" stroke="#4f8cff"/>
          <rect x="252" y="294" width="150" height="18" rx="4" fill="#34d399" opacity=".85" class="slotBar"/>
          <rect x="404" y="294" width="110" height="18" rx="4" fill="#22d3ee" opacity=".7" class="slotBar" style="animation-delay:.4s"/>
          <rect x="516" y="294" width="60"  height="18" rx="4" fill="#a78bfa" opacity=".7" class="slotBar" style="animation-delay:.8s"/>
          <rect x="578" y="294" width="270" height="18" rx="4" fill="#fbbf24" opacity=".5" class="slotBar" style="animation-delay:1.2s"/>
          <text x="327" y="336" text-anchor="middle" class="svg-lbl" font-size="10">R1 赢 5</text>
          <text x="459" y="336" text-anchor="middle" class="svg-lbl" font-size="10">R2 赢 3</text>
          <text x="546" y="336" text-anchor="middle" class="svg-lbl" font-size="10">R3 赢 1</text>
          <text x="713" y="336" text-anchor="middle" class="svg-lbl" font-size="10">base(每请求 1)</text>

          <!-- 请求行与排名 -->
          <g class="rankShift">
            <rect x="70" y="356" width="150" height="36" rx="8" class="node-gpu"/><text x="145" y="379" text-anchor="middle" class="node-gpu-title" font-size="11.5">R1 (conf 0.90)</text>
            <text x="236" y="379" class="svg-lbl" font-size="10.5" fill="#34d399">rank #1 → 验证 5 条</text>
            <rect x="70" y="398" width="150" height="36" rx="8" class="node-gpu"/><text x="145" y="421" text-anchor="middle" class="node-gpu-title" font-size="11.5">R2 (conf 0.70)</text>
            <text x="236" y="421" class="svg-lbl" font-size="10.5" fill="#22d3ee">rank #2 → 验证 3 条</text>
            <rect x="70" y="440" width="150" height="36" rx="8" class="node-gpu"/><text x="145" y="463" text-anchor="middle" class="node-gpu-title" font-size="11.5">R3 (conf 0.40)</text>
            <text x="236" y="463" class="svg-lbl" font-size="10.5" fill="#a78bfa">rank #5 → 验证 1 条</text>
          </g>

          <!-- 新请求加入 -->
          <g class="blinkSoft">
            <rect x="470" y="356" width="170" height="36" rx="8" fill="#2a2410" stroke="#fbbf24"/>
            <text x="555" y="379" text-anchor="middle" class="node-gpu-title" font-size="11.5" fill="#fbbf24">新请求 R4 (conf 0.95)</text>
            <text x="470" y="346" class="svg-lbl" font-size="10" fill="#fbbf24">batch 组成变化:加入 R4 →</text>
          </g>
          <line x1="644" y1="374" x2="700" y2="374" stroke="#fbbf24" stroke-width="2" marker-end="url(#arr3)"/>
          <text x="706" y="370" class="svg-lbl" font-size="10.5" fill="#f87171">全 batch 重新排名:</text>
          <text x="706" y="388" class="svg-lbl" font-size="10.5" fill="#f87171">R4 抢走预算 → R1 只剩 4 条</text>
          <text x="706" y="406" class="svg-lbl" font-size="10.5" fill="#f87171">R2 只剩 2 条…</text>
          <text x="706" y="436" class="svg-lbl-strong" font-size="11" fill="#f87171">同一请求 R1 的验证数量</text>
          <text x="706" y="454" class="svg-lbl-strong" font-size="11" fill="#f87171">因 batch 组成而改变!</text>
          <text x="706" y="476" class="svg-lbl" font-size="10" fill="#8ea0c2">worker.py:218-219 · schedule_mtp_varlen.py:72-98</text>
        </g>

        <g class="neq" transform="translate(500,252)">
          <circle cx="0" cy="0" r="20" fill="#2a1420" stroke="#f87171" stroke-width="2"/>
          <text x="0" y="7" text-anchor="middle" fill="#f87171" font-size="20" font-weight="800">≠</text>
        </g>
        <text x="500" y="524" text-anchor="middle" class="svg-note" font-size="12.5">
          因此确定性采样要求 <tspan fill="#fbbf24" font-weight="700">DEEPINFER_ENABLE_MTP_VARLEN=0</tspan>(README.md:28):
        </text>
        <text x="500" y="546" text-anchor="middle" class="svg-note" font-size="12.5">
          调度必须先成为「请求局部」的函数,RNG 的逐位置确定性才有意义。
        </text>
      </svg>
      <div class="cap">图 3(动画):固定验证(上)每请求的验证长度只取决于自身接受历史;VARLEN 置信度调度(下)按全 batch 排名分配 total_q 预算,batch 组成一变,同一请求的验证数量随之改变</div>
    </div>

    <div class="note warn reveal">
      <b>精确边界:</b>被禁的是 <b>VARLEN 置信度调度</b>,不是投机解码本身。<code>DEEPINFER_USE_NEXTN_DECODE</code>(默认 5,
      <code>environ.py:136-137</code>)的固定宽度验证与批次不变性共存,且拒绝采样的三条 RNG 流(新采样 / 拒绝重采 / 接受判定)全部锚定在序列位置上,
      理论上在固定调度下同样逐位可复现——README 对「确定性采样」仅要求 MTP_VARLEN=0,而不要求关闭 nextn。
    </div>
  </section>

  <!-- ============================================================ -->
  <section>
    <h2 class="sec"><span class="num">6</span>限制与代价</h2>
    <p class="lede">确定性不是免费的:平台、性能、与 EPLB / 投机解码的组合关系,都写死在代码的断言与条件里。</p>
    <table class="tbl">
      <tr><th>维度</th><th>约束 / 代价</th><th>代码依据</th></tr>
      <tr>
        <td>平台</td>
        <td><b>NVIDIA only</b>:NPU 上直接断言失败(<code>assert not envs.DEEPINFER_BATCH_INVARIANT</code>,TODO 标注「待完整支持 batch invariant 后移除」)。
        但 NPU 仍会打开 <code>use_deterministic_algorithms</code> 以稳定 CI 数值。</td>
        <td><code>deepinfer/worker/runtime_config.py:61-69</code>;<code>README.md:27-28</code></td>
      </tr>
      <tr>
        <td>吞吐</td>
        <td>官方标注「slower」:确定性 GEMM 放弃按形状自适应的 split-k / 高并发归约;combine 单次归约损失通信重叠;
        PROMPT 引擎失去 fused norm+rope+attn+cast 融合核;FlashMLA 走 batch-invariant 模式。</td>
        <td><code>eval/run_eval.py:74</code>;<code>runtime_config.py:67-69</code>;<code>userbuffer.py:79</code>;<code>attn.py:87-92</code></td>
      </tr>
      <tr>
        <td>EPLB 组合</td>
        <td>可与周期重排共存,但 combine 被迫单次归约;且重排决策依赖窗口化的 expert 计数(批量相关),
        跨<b>不同</b> batch 组合的绝对不变在放置层面不成立——此时保证的是「相同 batch 序列 ⇒ 相同结果」。</td>
        <td><code>userbuffer.py:79</code>;<code>eplb/__init__.py:152-165,222-278</code>;<code>tests/models/test_kl.py:105-107</code></td>
      </tr>
      <tr>
        <td>投机解码组合</td>
        <td>批次不变性:可与 <code>USE_NEXTN_DECODE&gt;0</code> 共存(test 直接覆盖 nextn=5);
        确定性采样:必须 <code>ENABLE_MTP_VARLEN=0</code>(VARLEN 的预算竞争使调度 batch 相关)。</td>
        <td><code>tests/models/test_batch_invariant.py:33</code>;<code>README.md:28</code>;<code>worker.py:218-219</code></td>
      </tr>
      <tr>
        <td>采样参数</td>
        <td>确定性采样必须显式传固定 <code>seq_seed</code>;缺省时每条请求随机取 64 位 seed,输出天然不可复现。
        temperature 近 0 时框架会强制 <code>top_p=1.0, top_k=-1</code>(等效贪心)。</td>
        <td><code>sampling_params.py:74,85-91,76-79</code></td>
      </tr>
      <tr>
        <td>验证开销</td>
        <td><code>DEEPINFER_COMPUTE_SUM_SMALLER_PROBS=1</code> 与 <code>top_logprobs&gt;0</code> 都会增加逐行 vocab 级的归约与 top-k 计算。</td>
        <td><code>sampler.py:104,501-509</code>;<code>sum_smaller_probs.py:10-28</code></td>
      </tr>
      <tr>
        <td>定位</td>
        <td>环境变量归属 Profiling &amp; Debug 分组;examples 默认仅在 NVIDIA 上 setdefault 开启(评测/演示用途),
        生产服务并不默认启用。</td>
        <td><code>environ.py:203-206</code>;<code>examples/offline_inference.py:42-43</code></td>
      </tr>
    </table>
    <div class="note reveal">
      <b>一个务实的使用建议(依据代码行为):</b>回归测试 / golden 对齐 / KL 检验等「需要逐位复现」的场景开
      <code>DEEPINFER_BATCH_INVARIANT=1</code>;面向吞吐的服务态保持默认(0);两者之间用 <code>DEEPINFER_DISABLE_SYNC_GUARD=1</code>
      这类 debug 开关排查发射期同步问题,而不是长期关闭守卫。
    </div>
  </section>

  <!-- ============================================================ -->
  <section>
    <h2 class="sec"><span class="num">7</span>验证体系:确定性是怎么被测试钉死的</h2>
    <p class="lede">从单内核的位相等,到端到端的 golden PPL 对齐,DeepInfer 为这两个特性搭了一整套测试金字塔。</p>

    <table class="tbl">
      <tr><th>层级</th><th>测试</th><th>验证内容</th><th>关键代码</th></tr>
      <tr>
        <td><span class="badge deepep">内核</span></td>
        <td><code>test_random_sampling_batch_invariant</code></td>
        <td>同一批 (probs, seeds, positions) 重复运行、整行随机置换、逐行单独采样,三者输出与批量参考<b>逐位相等</b>(n∈{256,512,4096} × vocab∈{1024,129280})</td>
        <td><code>tilelang_ops/random_sampling.py:308-332</code></td>
      </tr>
      <tr>
        <td><span class="badge deepep">内核</span></td>
        <td><code>fused_sample</code> 测试组</td>
        <td>新采样行与独立采样器在 exp(logprob) 上<b>位相等</b>;拒绝采样路径与参考实现一致;同输入两次运行所有输出 buffer 位相等</td>
        <td><code>tilelang_ops/fused_sample.py:458-464,466-498,511-525</code></td>
      </tr>
      <tr>
        <td><span class="badge open">统计</span></td>
        <td><code>test_random_sampling</code> / <code>gof</code> / <code>tiny_prob</code></td>
        <td>期望一致、卡方拟合优度、退化/极低概率(1e-7/1e-8)边界、零概率列不被采出</td>
        <td><code>tilelang_ops/random_sampling.py:101-163,219-305</code></td>
      </tr>
      <tr>
        <td><span class="badge open">统计</span></td>
        <td><code>tests/models/test_sampler.py</code></td>
        <td>端到端 rollout 的 <b>KS + 随机化 PIT</b> 检验(用 sum_smaller_probs 与 token_logprobs 构造 U(0,1) 统计量),覆盖 greedy / t1.0 / t8.0 / p1.0 四种配置</td>
        <td><code>tests/models/test_sampler.py:40-46,78-94,121-137</code></td>
      </tr>
      <tr>
        <td><span class="badge merged">端到端</span></td>
        <td><code>tests/models/test_batch_invariant.py</code></td>
        <td>64 条随机 prompt(长度 ~N(2500,1000))批量生成后,用 <b>golden teacher forcing</b> 把批量输出灌回单条重放,
        比对 (token_ids, logprobs, top_token_ids, top_logprobs) 完全相等——把「采样随机性」从变量中剔除,专测<b>模型数值</b>的批次不变性;EP=8 + nextn=5</td>
        <td><code>tests/models/test_batch_invariant.py:32-35,96-105</code>;golden 机制 <code>sampler.py:650-683</code>、<code>prepare_sample.cpp:229-248</code></td>
      </tr>
      <tr>
        <td><span class="badge merged">端到端</span></td>
        <td><code>tests/models/test_ve_batch_invariant.py</code></td>
        <td>视觉编码器(inline VE)embeds 与单图基线 <code>torch.equal</code> 按位相等:同形重复 batch + 随机形状混合 batch(最多 256 图/批)</td>
        <td><code>tests/models/test_ve_batch_invariant.py:105-146</code></td>
      </tr>
      <tr>
        <td><span class="badge hccl">golden</span></td>
        <td><code>tests/models/test_offline_inference.py</code></td>
        <td>跨运行的 decode PPL 与仓库内 golden JSON <b>逐值相等</b>(NVIDIA 侧子进程环境强制 <code>DEEPINFER_BATCH_INVARIANT=1</code>)——位级复现的最终验收</td>
        <td><code>tests/models/test_offline_inference.py:107-110,139-158</code></td>
      </tr>
      <tr>
        <td><span class="badge hccl">golden</span></td>
        <td><code>tests/models/test_kl.py</code></td>
        <td>相同 batch 两次运行的 logprob KL 检验;同时开启 BATCH_INVARIANT 与重排间隔 1000 + 32 个冗余 expert,验证「EPLB 重排 + 单次归约」下的可复现性</td>
        <td><code>tests/models/test_kl.py:97-111</code></td>
      </tr>
      <tr>
        <td><span class="badge nccl">守护</span></td>
        <td><code>tests/test_cuda_sync_guards.py</code></td>
        <td>sync guard 仲裁器的嵌套语义(forbid/allow 交替、跨线程、装饰器形态)与同步触发报错</td>
        <td><code>tests/test_cuda_sync_guards.py:27-212</code></td>
      </tr>
    </table>

    <div class="note good reveal">
      <b>测试设计的巧思:</b><code>test_batch_invariant.py</code> 的 <code>sp.golden_token_ids = [x.token_id for x in output]</code>
      (<code>:101</code>)用 golden teacher forcing 把「采样不可复现」这个干扰项从对比中拿掉——单条重放被强制走上与批量完全相同的 token 轨迹,
      于是 logprobs / top-logprobs 的任何差异都只能来自<b>模型前向的批次依赖</b>。这是对「批次不变性 ≠ 确定性采样」边界的教科书式运用。
    </div>
  </section>

  <!-- ============================================================ -->
  <section>
    <h2 class="sec"><span class="num">8</span>总结</h2>
    <p class="lede">一套「先让数学路径固定,再让随机路径固定」的两段式工程。</p>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🧊</span>批次不变性 = 固定数学路径</h3>
        <p>DeepGEMM / TileKernels 全局确定性算法(<code>runtime_config.py:67-69</code>)统一管住 GEMM 与算子层;
        FlashMLA <code>enable_batch_invariant</code> 管住 decode 注意力;PROMPT 引擎舍弃 fused prefill 注意力核
        (<code>attn.py:87-92</code>);EPLB 重排开启时 MoE combine 强制单次归约(<code>userbuffer.py:79</code>)。
        四面合围后,「和谁拼 batch」不再改变任何一次浮点加法的顺序。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🎲</span>确定性采样 = 固定随机路径</h3>
        <p>彻底抛弃全局 generator:每行的均匀数由 <code>(seq_seed, sample_position, sample_case)</code> 经 SplitMix64
        哈希而来(<code>random_sampling.py:58-84</code>),概率以 uint32 定点编码、两级 CDF 反演
        (<code>cuda/random_sampling.py</code>)——整数累加可结合,连采样的归约顺序都不可变。
        MTP 的 draft / 验证 / 拒绝三条流用 <code>_MTP_SEED_OFFSET</code> 与 <code>pos*3+case</code> 彻底去相关。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">⚖️</span>边界清晰</h3>
        <p>NVIDIA only(NPU 断言拦截);与 EPLB 重排共存但语义降级为「相同 batch 序列 ⇒ 相同结果」;
        与固定宽度投机解码共存,与 VARLEN 置信度调度互斥(README 的 <code>MTP_VARLEN=0</code> 要求);
        代价是官方明说的「slower」。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">🧪</span>可验证性是设计的一部分</h3>
        <p>golden teacher forcing 的批次不变测试、跨运行 golden PPL、KS/PIT 分布检验、内核级位相等断言、
        VE 按位 embeds——每个承诺都有对应测试钉住。确定性不是口号,而是被 CI 持续证明的属性。</p>
      </div>
    </div>

    <div class="timeline reveal" style="margin-top:26px">
      <div class="tl-item">
        <div class="tl-date">启用批次不变性</div>
        <div class="tl-body"><code>DEEPINFER_BATCH_INVARIANT=1</code>(NVIDIA)——模型结果与 batch 组成无关,可开 EPLB 与 nextn。</div>
      </div>
      <div class="tl-item">
        <div class="tl-date">启用确定性采样</div>
        <div class="tl-body"><code>DEEPINFER_BATCH_INVARIANT=1 DEEPINFER_ENABLE_MTP_VARLEN=0</code> + 每条请求传固定 <code>seq_seed</code>(NVIDIA)——相同输入与采样参数 ⇒ 相同输出。</div>
      </div>
      <div class="tl-item">
        <div class="tl-date">调试发射期同步</div>
        <div class="tl-body"><code>DEEPINFER_DISABLE_SYNC_GUARD=1</code> 临时关闭 forward/sampling 发射期的 CPU-GPU 同步检查。</div>
      </div>
    </div>

    <div class="note good reveal">
      <b>延伸阅读:</b>采样内核细节见本系列 <a href="/docs/inference-engines/deepinfer/01-kernels/" style="color:var(--accent2)">① 优化内核与运行时</a>;
      EPLB 重排与专家放置见 <a href="/docs/inference-engines/deepinfer/02-parallelism/" style="color:var(--accent2)">② 并行策略 DP/CP/EP+EPLB</a>;
      DSpark 投机解码与置信度调度见 <a href="/docs/inference-engines/deepinfer/03-dspark/" style="color:var(--accent2)">③ DSpark 投机解码</a>;
      forward/sampling 的重叠调度见 <a href="/docs/inference-engines/deepinfer/05-async-scheduling/" style="color:var(--accent2)">⑤ 异步调度</a>。
    </div>
  </section>

  <div class="pgnav">
    <span>DeepInfer 代码分析系列 · 由 ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/deepinfer/">← 返回系列总览</a></span>
  </div>
<script>
// 滚动显现动画
const io=new IntersectionObserver(es=>{es.forEach(e=>{if(e.isIntersecting){e.target.classList.add('on');io.unobserve(e.target)}})},{threshold:.12});
document.querySelectorAll('.reveal').forEach(el=>io.observe(el));
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>DeepInfer 深度解析 · ⑦ 结构化输出(regex / JSON Schema / EBNF)</title><link>https://hccl.club/docs/inference-engines/deepinfer/07-structured-output/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/07-structured-output/</guid><description><![CDATA[<div class="fwdoc">
<style>
.fwdoc{--bg:#0b1020; --bg2:#0f1729; --panel:#141d33; --panel2:#1a2440;
  --border:#263352; --text:#dbe4f5; --muted:#8ea0c2;
  --accent:#4f8cff; --accent2:#22d3ee; --good:#34d399; --warn:#fbbf24; --bad:#f87171; --purple:#a78bfa;
  --code-bg:#0d1424; --radius:14px;
  --serif:"Noto Serif SC","Songti SC",serif;}
.fwdoc *{box-sizing:border-box;margin:0;padding:0}
.fwdoc{background:linear-gradient(160deg,var(--bg) 0%,var(--bg2) 60%,#0a0f1e 100%);color:var(--text);
  font-family:"PingFang SC","Microsoft YaHei","Segoe UI",system-ui,sans-serif;line-height:1.75;}
.fwdoc{flex:1;min-width:0;padding:36px 48px 80px}
@media(max-width:960px){.fwdoc{padding:24px 18px 60px}}
.fwdoc .hero{position:relative;border-radius:var(--radius);overflow:hidden;padding:46px 44px;margin-bottom:34px;
  background:radial-gradient(1200px 400px at 15% -20%,rgba(79,140,255,.28),transparent 60%),
             radial-gradient(900px 380px at 95% 0%,rgba(167,139,250,.20),transparent 55%),
             linear-gradient(135deg,#16213e,#101a30);border:1px solid var(--border)}
.fwdoc .hero .crumb{font-size:12px;color:var(--accent2);letter-spacing:1px;margin-bottom:12px}
.fwdoc .hero h1{font-size:34px;color:#fff;font-weight:800;letter-spacing:.5px;margin-bottom:10px}
.fwdoc .hero p.desc{color:var(--muted);max-width:760px;font-size:15px}
.fwdoc .hero .tags{margin-top:18px;display:flex;gap:10px;flex-wrap:wrap}
.fwdoc .hero .tag{font-size:12px;padding:4px 14px;border-radius:999px;border:1px solid var(--border);
  background:rgba(79,140,255,.10);color:var(--accent2)}
.fwdoc .tag.good{border-color:rgba(52,211,153,.4);color:var(--good);background:rgba(52,211,153,.08)}
.fwdoc .tag.warn{border-color:rgba(251,191,36,.4);color:var(--warn);background:rgba(251,191,36,.08)}
.fwdoc section{margin-bottom:44px;scroll-margin-top:20px}
.fwdoc h2.sec{display:flex;align-items:center;gap:12px;font-size:23px;color:#fff;margin-bottom:6px;padding-bottom:10px;border-bottom:1px solid var(--border)}
.fwdoc h2.sec .num{display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:10px;flex-shrink:0;
  background:linear-gradient(135deg,var(--accent),var(--purple));color:#fff;font-size:15px;font-weight:800}
.fwdoc .lede{color:var(--muted);font-size:14px;margin-bottom:20px}
.fwdoc .grid{display:grid;gap:18px}
.fwdoc .grid.c2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}
.fwdoc .grid.c3{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}
.fwdoc .card{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:var(--radius);padding:22px 24px;transition:transform .3s,border-color .3s,box-shadow .3s}
.fwdoc .card:hover{transform:translateY(-3px);border-color:rgba(79,140,255,.55);box-shadow:0 12px 34px -14px rgba(79,140,255,.35)}
.fwdoc .card h3{font-size:16.5px;color:#fff;margin-bottom:8px;display:flex;align-items:center;gap:9px}
.fwdoc .card h3 .ico{width:26px;height:26px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;
  background:rgba(79,140,255,.16);font-size:14px;flex-shrink:0}
.fwdoc .card p{font-size:13.5px;color:var(--muted)}
.fwdoc .card p code,.fwdoc .inline-code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1.5px 7px;border-radius:6px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px}
.fwdoc ul.feat{list-style:none}
.fwdoc ul.feat li{padding:9px 0 9px 30px;position:relative;font-size:14px;color:var(--text);border-bottom:1px dashed rgba(38,51,82,.6)}
.fwdoc ul.feat li:last-child{border-bottom:none}
.fwdoc ul.feat li::before{content:"▸";position:absolute;left:8px;color:var(--accent);font-weight:700;animation:fw-blink 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
@keyframes fw-blink{0%,100%{opacity:.35}50%{opacity:1}}
.fwdoc pre.code{background:var(--code-bg);border:1px solid var(--border);border-radius:12px;padding:18px 20px;
  overflow-x:auto;font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px;line-height:1.65;margin:14px 0;position:relative}
.fwdoc pre.code::before{content:"● ● ●";display:block;color:#3a4a70;font-size:10px;letter-spacing:3px;margin-bottom:10px}
.fwdoc pre.code .k{color:#c792ea}
.fwdoc pre.code .s{color:#89ddff}
.fwdoc pre.code .c{color:#5d7294;font-style:italic}
.fwdoc pre.code .f{color:#82aaff}
.fwdoc pre.code .n{color:#f78c6c}
.fwdoc pre.code .h{color:#ffcb6b}
.fwdoc .filepath{font-family:"JetBrains Mono",Consolas,monospace;font-size:11.5px;color:var(--accent2);
  background:rgba(34,211,238,.08);border:1px solid rgba(34,211,238,.25);border-radius:6px;padding:2px 10px;display:inline-block;margin-bottom:4px}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border)}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px}
.fwdoc table.tbl td{padding:10px 14px;border-top:1px solid var(--border);color:var(--text);vertical-align:top}
.fwdoc table.tbl tr{transition:background .2s}
.fwdoc table.tbl tr:nth-child(even) td{background:rgba(20,29,51,.5)}
.fwdoc table.tbl tr:hover td{background:rgba(79,140,255,.10)}
.fwdoc table.tbl td code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;font-family:Consolas,monospace;font-size:12px}
.fwdoc .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px}
.fwdoc .badge.merged{background:rgba(52,211,153,.15);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.open{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.closed{background:rgba(248,113,113,.13);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.nccl{background:rgba(251,191,36,.12);color:var(--warn);border:1px solid rgba(251,191,36,.4)}
.fwdoc .badge.hccl{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .badge.deepep{background:rgba(34,211,238,.12);color:var(--accent2);border:1px solid rgba(34,211,238,.4)}
.fwdoc .reveal{opacity:0;transform:translateY(26px);transition:opacity .7s cubic-bezier(.2,.7,.3,1),transform .7s cubic-bezier(.2,.7,.3,1)}
.fwdoc .reveal.on{opacity:1;transform:none}
.fwdoc .reveal.d1{transition-delay:.12s}
.fwdoc .reveal.d2{transition-delay:.24s}
.fwdoc .reveal.d3{transition-delay:.36s}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:20px;margin:18px 0;position:relative;overflow:hidden}
.fwdoc .figure .cap{text-align:center;font-size:12.5px;color:var(--muted);margin-top:10px}
.fwdoc .figure svg{width:100%;height:auto;display:block}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-flow 1.2s linear infinite}
@keyframes fw-flow{to{stroke-dashoffset:-14}}
.fwdoc .pulse{animation:fw-pulse 2s ease-in-out infinite;transform-origin:center}
@keyframes fw-pulse{0%,100%{opacity:.45;transform:scale(1)}50%{opacity:1;transform:scale(1.06)}}
.fwdoc .node-gpu{fill:#16233f;stroke:#4f8cff;stroke-width:1.6;rx:10}
.fwdoc .node-gpu-title{fill:#dbe4f5;font-size:13px;font-weight:700}
.fwdoc .token-dot{fill:#22d3ee}
.fwdoc .barrow{filter:drop-shadow(0 0 6px rgba(34,211,238,.7))}
.fwdoc .timeline{position:relative;padding-left:34px}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .tl-item{position:relative;margin-bottom:20px}
.fwdoc .tl-item::before{content:"";position:absolute;left:-30px;top:7px;width:12px;height:12px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.18);animation:fw-pulse 2.4s infinite}
.fwdoc .tl-item .tl-date{font-size:11.5px;color:var(--accent2);letter-spacing:.5px}
.fwdoc .tl-item .tl-body{font-size:13.5px;color:var(--text);margin-top:3px}
.fwdoc .note{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13px;color:var(--text);margin:16px 0}
.fwdoc .note.warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .note.good{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .note b{color:#fff}
.fwdoc .pgnav{margin-top:60px;padding-top:20px;border-top:1px solid var(--border);color:#5a6b92;font-size:12px;
  display:flex;justify-content:space-between;flex-wrap:wrap;gap:10px}
.fwdoc .pgnav a{color:var(--accent2);text-decoration:none}
/* ===== 导入面板附加样式 ===== */
.fwdoc{border-radius:14px;margin:18px 0}
.fwdoc table.tbl{display:block;overflow-x:auto;max-width:100%}
@media (prefers-reduced-motion:reduce){
.fwdoc *,.fwdoc *::before,.fwdoc *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
.fwdoc .reveal{opacity:1!important;transform:none!important}
}

</style>

<!-- ================= 1. 概述 ================= -->
  <section id="s1">
    <h2 class="sec"><span class="num">1</span>概述:结构化输出解决什么问题</h2>
    <p class="lede">大模型天生是「自由文本生成器」:即便提示词写明「请输出 JSON」,temperature 采样仍可能产出多余空格、非法枚举值或未闭合括号。结构化输出(Structured Outputs,SO)把格式约束从「提示词约定」升级为「推理期硬保证」。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🎯</span>问题:格式错误的代价</h3>
        <p>下游 agent 解析失败、工具调用 JSON 不合法、正则抽取落空——生产服务里每一个格式错误都是一次失败的请求。靠重试或「再采样一次」既浪费 token 又不可控;靠约束解码的朴素实现(逐字符 DFS)则会破坏采样分布、拖慢解码。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧩</span>DeepInfer 的解法:每步 logits 掩码</h3>
        <p>把约束(regex / JSON Schema / EBNF)先离线<strong>编译</strong>成 token 级自动机;解码<strong>每一步</strong>生成一个 <code>[⌈vocab/32⌉]</code> 的 int32 位掩码,再用 GPU 内核把所有非法 token 的 logits 置为 <code>-inf</code>。采样分布被「裁剪」但不再重排——合法 token 间的相对概率保持不变,输出仍然自然。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">⚡</span>生产级工程化</h3>
        <p>文法编译在线程池<strong>异步</strong>进行,不阻塞引擎 step;编译带 20 秒超时与 10 GiB 缓存上限;编译线程绑定专用物理核(<code>DEEPINFER_SO_BUILDER_CPUS</code>);SO 的任何 bug(编译超时、matcher 运行时错误、不变量破坏)只判死<strong>单个请求</strong>,不连坐整个 batch——这是 CP rank 0 采样主路径上反复强调的容错边界。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">🚀</span>与投机解码共存</h3>
        <p>DSpark(MTP)每步提交多个 draft token 一次性验证。SO 为「当前位置 + 每个 draft 位置」分别预填掩码(<code>max_MTP_value + 1</code> 个缓冲),draft 被接受才真正推进自动机,否则回滚——约束与加速两不误。</p>
      </div>
    </div>

    <p style="font-size:14px;margin-top:18px">README 把 Structured outputs 列为 DeepInfer 的核心特性之一,并给出唯一入口:通过 <code>SamplingParams</code> 传 <code>so_args</code>。</p>
    <div>
      <span class="filepath">README.md:18, 29</span>
      <pre class="code"><span class="c"># README.md "Supported features" 列表</span>
- Structured outputs

<span class="c"># Feature details 一节</span>
- <span class="h">**Structured outputs:**</span> constrain generation to a regex, JSON schema, or EBNF grammar.
  Pass <span class="s">`so_args={"schema_type": ..., "schema": ...}`</span> to `SamplingParams`; see [examples](examples/_structured_output.py).</pre>
    </div>

    <div class="note">
      <b>一句话总览:</b>请求携带 <code>so_args</code> → <code>SOMatcherBuilder</code> 线程池异步把 schema 编译成 <code>XGrammarMatcher</code> → 挂到 <code>Sequence</code> 上(<code>seq.so_matcher</code>)→ 调度器用 <code>so_status</code> 账本跟踪激活状态 → 采样器每步把已生成 token 喂进 matcher、取出位掩码、经专用 CUDA 侧流拷上 GPU → TileLang 内核掩蔽 logits → 采样/验证。<b>整条链路横跨 Python 与 C++(csrc/engine),下文逐层拆解。</b>
    </div>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📁</span>代码地图:deepinfer/structure_output/</h3>
        <ul class="feat">
          <li><code>compiler.py</code> — <code>XGrammarCompiler</code>:xgrammar <code>GrammarCompiler</code> 封装,缓存与超时开关、三种 schema 分发编译</li>
          <li><code>matcher.py</code> — <code>XGrammarMatcher</code>(自动机状态机 + 掩码填充 + 回滚)与 <code>XGrammarMatcherFuture</code>(异步结果 + 超时)</li>
          <li><code>so_matcher_builder.py</code> — <code>SOMatcherBuilder</code>:编译线程池、CPU 绑核、submit/pump 异步生命周期</li>
          <li><code>mask.py</code> — <code>XGrammarUtils</code>:掩码分配与 GPU 应用入口(懒 import,避免把 xgrammar 拖进不用 SO 的部署)</li>
          <li><code>__init__.py</code> — 空文件(包标记)</li>
        </ul>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧭</span>外围集成点</h3>
        <ul class="feat">
          <li><code>deepinfer/sampling_params.py</code> — <code>so_args</code> 参数定义</li>
          <li><code>deepinfer/engine/llm_engine.py</code> — builder 懒构造、请求接入、每 step pump</li>
          <li><code>deepinfer/model_executor/layers/sampler.py</code> — <code>_get_so_mask</code> 逐请求更新 matcher、填掩码、侧流 H2D</li>
          <li><code>deepinfer/model_executor/layers/tilelang_ops/structure_output.py</code> — TileLang 位掩码内核封装与单测</li>
          <li><code>csrc/engine/sequence.hpp / scheduler.hpp</code> — <code>StructuredOutputState</code> 账本、状态回写、判死、抢占、fork</li>
          <li><code>examples/_structured_output.py</code> — 三种约束的端到端验证示例</li>
        </ul>
      </div>
    </div>
  </section>

  <!-- ================= 2. 三种约束类型与 xgrammar ================= -->
  <section id="s2">
    <h2 class="sec"><span class="num">2</span>三种约束类型(regex / JSON Schema / EBNF)与 xgrammar 引擎</h2>
    <p class="lede">DeepInfer 不自研文法引擎,而是集成开源的 <strong>xgrammar</strong>(<code>requirements.txt:21</code> 锁定 <code>xgrammar==0.2.2</code>),它提供「token 感知」的文法编译:直接在 tokenizer 的词表上编译出每步合法 token 集合,避免逐字符适配的指数爆炸。</p>

    <table class="tbl reveal">
      <tr><th>schema_type</th><th>xgrammar 编译 API</th><th>约束语义</th><th>典型 schema(取自真实代码)</th><th>代码引用</th></tr>
      <tr>
        <td><code>"regex"</code></td>
        <td><code>compile_regex(schema)</code></td>
        <td>整段输出须与正则 <b>fullmatch</b>(全串匹配,不是搜索)</td>
        <td><code>r"[A-Z]{2}-[0-9]{3}"</code> — 形如 <code>AB-123</code> 的编号</td>
        <td><span class="filepath" style="border:none;background:none;padding:0">compiler.py:59 / examples/_structured_output.py:26</span></td>
      </tr>
      <tr>
        <td><code>"json"</code></td>
        <td><code>compile_json_schema(schema, strict_mode=True)</code></td>
        <td>输出须为符合 JSON Schema 的单个 JSON 值;<b>strict 模式</b>收紧生成,不允许多余属性</td>
        <td><code>{"type":"object","properties":{"color":{"type":"string","enum":[...]},...},"additionalProperties":false}</code></td>
        <td><span class="filepath" style="border:none;background:none;padding:0">compiler.py:57 / examples/_structured_output.py:14-22</span></td>
      </tr>
      <tr>
        <td><code>"ebnf"</code></td>
        <td><code>compile_grammar(schema)</code></td>
        <td>输出须符合 EBNF 文法(最通用,regex/json 之外的兜底表达)</td>
        <td><code>root ::= "answer=" ("yes" | "no") ";level=" [1-3]</code></td>
        <td><span class="filepath" style="border:none;background:none;padding:0">compiler.py:61 / examples/_structured_output.py:34</span></td>
      </tr>
    </table>

    <p style="font-size:14px">分发逻辑集中在 <code>XGrammarCompiler.dispatch_and_compile</code>,所有异常统一包装成 <code>RuntimeError</code>,方便上层把它当成「编译失败」一种情况处理:</p>
    <div>
      <span class="filepath">deepinfer/structure_output/compiler.py:54-71</span>
      <pre class="code"><span class="k">def</span> <span class="f">dispatch_and_compile</span>(self, schema_type: <span class="k">str</span>, schema: <span class="k">str</span>) -&gt; CompiledGrammar:
    <span class="k">try</span>:
        <span class="k">if</span> schema_type == <span class="s">"json"</span>:
            ctx = self.inner_compiler.<span class="f">compile_json_schema</span>(schema, strict_mode=<span class="k">True</span>)
        <span class="k">elif</span> schema_type == <span class="s">"regex"</span>:
            ctx = self.inner_compiler.<span class="f">compile_regex</span>(schema)
        <span class="k">elif</span> schema_type == <span class="s">"ebnf"</span>:
            ctx = self.inner_compiler.<span class="f">compile_grammar</span>(schema)
        <span class="k">else</span>:
            <span class="k">raise</span> <span class="f">ValueError</span>(<span class="s">"Unsupported Grammar Type"</span>)
    <span class="k">except</span> <span class="f">RuntimeError</span> <span class="k">as</span> e:
        <span class="k">raise</span> <span class="f">RuntimeError</span>(<span class="s">f"xgrammar compilation RE: {e}"</span>) <span class="k">from</span> e
    <span class="k">except</span> <span class="f">ValueError</span> <span class="k">as</span> e:
        <span class="k">raise</span> <span class="f">RuntimeError</span>(<span class="s">f"xgrammar invalid input: {e}"</span>) <span class="k">from</span> e
    ...
    <span class="k">return</span> ctx</pre>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">2.1 so_args:唯一的用户接口</h3>
    <p style="font-size:14px"><code>so_args</code> 是一个普通 dict,<code>SamplingParams</code> 原样存放(不做校验,校验延迟到 builder/matcher 层),docstring 精确定义了每个键的契约:</p>
    <div>
      <span class="filepath">deepinfer/sampling_params.py:39-43, 59, 82</span>
      <pre class="code">so_args: dict, <span class="s">"schema_type"</span>, <span class="s">"schema"</span>;可选 <span class="s">"trigger_token_ids"</span>(单条 list[int]):
    触发 grammar 生效的 token id 序列,完整出现即触发,出现前自由生成;
    可选 <span class="s">"bound_token_id"</span>(非负整数,0 有效;缺省或 None 表示无 bound,
    必须搭配非空 trigger_token_ids,列表非法):bound 生效后不再允许自由
    token,先逐 token 强制走完 trigger 序列再进 grammar

<span class="k">def</span> <span class="f">__init__</span>(self, ..., so_args: dict | <span class="k">None</span> = <span class="k">None</span>, golden_token_ids: list[int] | <span class="k">None</span> = <span class="k">None</span>, ...):
    ...
    self.so_args = so_args</pre>
    </div>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🔗</span>trigger_token_ids:延迟激活</h3>
        <p>典型场景:「模型先自由写分析,出现 <code>&lt;answer&gt;</code> 之后再按 schema 输出」。<code>trigger_token_ids</code> 是一段 token id 序列;matcher 用 <b>KMP 失配函数</b>(<code>matcher.py:24-33</code> 的 <code>_kmp_failure</code>)在自由生成的 token 流里流式匹配该序列——中途失配不会浪费已匹配前缀。完整出现之前,不施加任何掩码(<code>constrained()</code> 为 False,<code>matcher.py:121-122</code>)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🔒</span>bound_token_id:硬绑定触发</h3>
        <p>无 bound 时,trigger 序列匹配期间模型仍在自由生成(可能写出半截 <code>&lt;answer</code> 又拐走);设置 <code>bound_token_id</code> 后,一旦该 token 出现即「开铐」:此后每一步只允许 trigger 序列的下一个精确 token(<code>matcher.py:136-139</code> 直接比较,不走 KMP),走完 trigger 才进入 grammar。<code>validate_trigger_bound</code>(<code>matcher.py:48-55</code>)要求:非负整数列表、bound 必须搭配非空 trigger。</p>
      </div>
    </div>

    <div class="note warn">
      <b>两个被显式拒绝的旧参数:</b><code>SOMatcherBuilder.build</code> 一进来就检查——<code>"serialized"</code>(不接受序列化文法,离线场景必须给 schema_type + schema,<code>so_matcher_builder.py:60-61</code>)与 <code>"bound_token_ids"</code>(复数形式已废弃,改用单个 <code>bound_token_id</code>,<code>so_matcher_builder.py:62-63</code>)。传了直接 <code>ValueError</code>。
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">2.2 xgrammar 集成与「词表校验」</h3>
    <p style="font-size:14px">文法编译必须知道<strong>具体 tokenizer 的词表</strong>——同一个 <code>"yes"</code> 在不同 BPE 词表里切分不同,合法 token 集合也不同。builder 构造时用模型的 HF tokenizer 建立一次性的 <code>TokenizerInfo</code>:</p>
    <div>
      <span class="filepath">deepinfer/structure_output/so_matcher_builder.py:29, 49</span>
      <pre class="code">self._tokenizer_info = <span class="f">TokenizerInfo.from_huggingface</span>(tokenizer, vocab_size=vocab_size)
...
<span class="c"># 编译器本身也在池内构造,内部并行 2 线程</span>
self._compiler = self._pool.<span class="f">submit</span>(XGrammarCompiler, self._tokenizer_info, num_threads=<span class="n">2</span>).<span class="f">result</span>()</pre>
    </div>
    <ul class="feat reveal">
      <li><b>词表维度一致性</b>由三处共同保证:matcher 分配掩码用引擎的 <code>vocab_size</code>(<code>from_compiled</code>,<code>matcher.py:94-106</code>);采样器缓冲同样按 <code>self.vocab_size</code> 分配(<code>sampler.py:324-327</code>);TileLang 内核断言 <code>logits 词表 ≥ 位掩码词表</code>(<code>structure_output.py:31-35</code> 的 assert)。</li>
      <li><b>特殊 token 拒绝</b>:xgrammar 把特殊 token 视为不可接受,<code>accept_token</code> 捕获 <code>"regarded as a special token"</code> 异常并返回 False(<code>matcher.py:170-174</code>),DEBUG 开启时打印拒绝日志。</li>
      <li><b>EOS 语义</b>:文法到达可停止状态时才允许接受 EOS;接受 EOS 后 <code>tokens_after_eos</code> 置 0(<code>matcher.py:165-167</code>),此后 <code>fill_vocab_mask</code> 返回全 1 的 <code>mask_after_eos</code>(<code>matcher.py:189-191</code>)——请求随即正常 stop,这也是示例断言 <code>finish_reason == "stop"</code> 且末 token 为 EOS 的根据。</li>
    </ul>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">2.3 与视觉编码器(VE)/ 多模态的关系</h3>
    <p style="font-size:14px">检索 <code>deepinfer/ve/</code> 全目录,<b>没有任何 SO 专用代码</b>——这是设计使然:SO 约束作用在<strong>采样/解码阶段</strong>(logits 掩码),而 VE 在 <strong>prefill 阶段</strong>处理图像并改写 prompt(<code>llm_engine.py:546-553</code> 的 <code>overwrite_prompt</code>)。两者天然正交:多模态请求可以同时携带 <code>so_args</code>,图像部分不受文法影响,生成的文本部分照常被掩码约束。两点佐证:</p>
    <ul class="feat reveal">
      <li><code>examples/benchmark.py</code> 中 VL 请求(prompt_mode 非 text 时走 <code>build_vl_requests</code>)与 <code>--enable_so</code> 的 regex 约束可以叠加(<code>benchmark.py:280</code> 的 <code>so_args</code> 进入所有请求共用的 <code>sampling_kwargs</code>)。</li>
      <li><code>add_request</code> 里 <code>multi_modal_data</code> 分支与 <code>so_args</code> 分支互不干扰(<code>llm_engine.py:546-553</code> vs <code>llm_engine.py:606-613</code>),SO 逻辑只看 <code>sampling_params.so_args is not None</code>。</li>
    </ul>
    <div class="note">顺带澄清一个容易混淆的命名:<code>deepinfer/ve/schema.py:1</code> 开头的 docstring「multi_modal_data 跨模块共享的常量与资源键解读」——此 <em>schema</em> 是<b>多模态数据字典的键约定</b>(image_bytes / mm_token_type 等),与文法 schema 毫无关系。</div>
  </section>

  <!-- ================= 3. 编译与匹配流水线 ================= -->
  <section id="s3">
    <h2 class="sec"><span class="num">3</span>约束编译与匹配流水线</h2>
    <p class="lede">从请求进入到每步掩码生效,完整链路横跨「Python 调度面」与「GPU 采样面」。下图是总览动画:上半行是一次性的编译流水线,下半行是每个 decode step 重复的匹配流水线。</p>

    <div class="figure reveal">
      <svg viewBox="0 0 1160 505" xmlns="http://www.w3.org/2000/svg" font-family="'PingFang SC','Microsoft YaHei',sans-serif">
        <defs>
          <marker id="arw" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
            <path d="M0,0 L9,4.5 L0,9 z" fill="#4f8cff"/>
          </marker>
          <marker id="arw2" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
            <path d="M0,0 L9,4.5 L0,9 z" fill="#22d3ee"/>
          </marker>
          <linearGradient id="gpool" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stop-color="#1b2a4a"/><stop offset="1" stop-color="#16233f"/>
          </linearGradient>
        </defs>

        <text x="20" y="22" fill="#8ea0c2" font-size="13" font-weight="700">A · 一次性编译流水线(请求接入时,线程池异步)</text>
        <text x="20" y="255" fill="#8ea0c2" font-size="13" font-weight="700">B · 每个 decode step 循环(采样器内,含 MTP draft 各步)</text>

        <!-- Row A nodes -->
        <g>
          <rect x="20" y="42" width="185" height="112" rx="12" fill="#16233f" stroke="#4f8cff" stroke-width="1.6"/>
          <text x="112" y="66" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">① 用户请求</text>
          <text x="112" y="88" text-anchor="middle" fill="#8ea0c2" font-size="11">SamplingParams(</text>
          <text x="112" y="104" text-anchor="middle" fill="#89ddff" font-size="11">so_args={"schema_type",</text>
          <text x="112" y="120" text-anchor="middle" fill="#89ddff" font-size="11">"schema", ...})</text>
          <text x="112" y="140" text-anchor="middle" fill="#5d7294" font-size="10.5">llm_engine.py:606</text>
        </g>
        <path class="flowline" d="M205,98 H245" stroke="#4f8cff" stroke-width="2" marker-end="url(#arw)"/>
        <circle r="4.5" fill="#22d3ee" class="barrow"><animateMotion dur="1.6s" repeatCount="indefinite" path="M205,98 H245"/></circle>

        <g>
          <rect x="245" y="42" width="205" height="112" rx="12" fill="#16233f" stroke="#4f8cff" stroke-width="1.6"/>
          <text x="347" y="66" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">② 文法分发</text>
          <text x="347" y="86" text-anchor="middle" fill="#8ea0c2" font-size="10.5">dispatch_and_compile()</text>
          <rect x="262" y="96" width="52" height="17" rx="8" fill="rgba(34,211,238,.14)" stroke="#22d3ee" stroke-width=".8"/><text x="288" y="108.5" text-anchor="middle" fill="#22d3ee" font-size="10">regex</text>
          <rect x="320" y="96" width="46" height="17" rx="8" fill="rgba(52,211,153,.14)" stroke="#34d399" stroke-width=".8"/><text x="343" y="108.5" text-anchor="middle" fill="#34d399" font-size="10">json</text>
          <rect x="372" y="96" width="52" height="17" rx="8" fill="rgba(167,139,250,.14)" stroke="#a78bfa" stroke-width=".8"/><text x="398" y="108.5" text-anchor="middle" fill="#a78bfa" font-size="10">ebnf</text>
          <text x="347" y="140" text-anchor="middle" fill="#5d7294" font-size="10.5">compiler.py:54-71</text>
        </g>
        <path class="flowline" d="M450,98 H490" stroke="#4f8cff" stroke-width="2" marker-end="url(#arw)"/>
        <circle r="4.5" fill="#22d3ee" class="barrow"><animateMotion dur="1.6s" begin=".4s" repeatCount="indefinite" path="M450,98 H490"/></circle>

        <g>
          <rect class="pulse" x="490" y="42" width="225" height="112" rx="12" fill="url(#gpool)" stroke="#22d3ee" stroke-width="1.8"/>
          <text x="602" y="66" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">③ 编译线程池(SOMatcherBuilder)</text>
          <text x="602" y="87" text-anchor="middle" fill="#8ea0c2" font-size="10.5">ThreadPoolExecutor(max_workers=len(idle_cpus))</text>
          <text x="602" y="103" text-anchor="middle" fill="#8ea0c2" font-size="10.5">XGrammarCompiler(num_threads=2) · CPU 绑核</text>
          <text x="602" y="119" text-anchor="middle" fill="#5d7294" font-size="10.5">编译缓存 ≤ DEEPINFER_XGRAMMAR_CACHE_LIMIT_BYTES</text>
          <text x="602" y="145" text-anchor="middle" fill="#5d7294" font-size="10.5">so_matcher_builder.py:45-49</text>
        </g>
        <path class="flowline" d="M715,98 H755" stroke="#4f8cff" stroke-width="2" marker-end="url(#arw)"/>
        <circle r="4.5" fill="#22d3ee" class="barrow"><animateMotion dur="1.6s" begin=".8s" repeatCount="indefinite" path="M715,98 H755"/></circle>

        <g>
          <rect x="755" y="42" width="185" height="112" rx="12" fill="#16233f" stroke="#a78bfa" stroke-width="1.6"/>
          <text x="847" y="66" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">④ CompiledGrammar</text>
          <text x="847" y="88" text-anchor="middle" fill="#8ea0c2" font-size="10.5">xgrammar 编译产物</text>
          <text x="847" y="104" text-anchor="middle" fill="#8ea0c2" font-size="10.5">token-aware 自动机描述</text>
          <text x="847" y="126" text-anchor="middle" fill="#5d7294" font-size="10.5">Future 返回 / 20s 超时窗</text>
          <text x="847" y="145" text-anchor="middle" fill="#5d7294" font-size="10.5">compiler.py:34-39</text>
        </g>

        <!-- elbow from Row A to Row B -->
        <path class="flowline" d="M847,154 V198 H112 V272" stroke="#a78bfa" stroke-width="2" fill="none" marker-end="url(#arw)"/>
        <circle r="4.5" fill="#a78bfa" class="barrow"><animateMotion dur="3s" repeatCount="indefinite" path="M847,154 V198 H112 V272"/></circle>
        <text x="480" y="192" text-anchor="middle" fill="#a78bfa" font-size="11">编译完成 → pump() 把 matcher 挂到 seq.so_matcher 并入调度</text>

        <!-- Row B nodes -->
        <g>
          <rect x="20" y="272" width="185" height="132" rx="12" fill="#16233f" stroke="#22d3ee" stroke-width="1.6"/>
          <text x="112" y="296" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">⑤ XGrammarMatcher</text>
          <text x="112" y="316" text-anchor="middle" fill="#8ea0c2" font-size="10.5">xgrammar GrammarMatcher</text>
          <text x="112" y="332" text-anchor="middle" fill="#8ea0c2" font-size="10.5">max_rollback_tokens = 7</text>
          <text x="112" y="348" text-anchor="middle" fill="#8ea0c2" font-size="10.5">KMP trigger 追踪 / EOS 状态</text>
          <text x="112" y="364" text-anchor="middle" fill="#8ea0c2" font-size="10.5">rollback(steps) 可回退</text>
          <text x="112" y="392" text-anchor="middle" fill="#5d7294" font-size="10.5">matcher.py:58-83</text>
        </g>
        <path class="flowline" d="M205,338 H245" stroke="#22d3ee" stroke-width="2" marker-end="url(#arw2)"/>
        <circle r="4.5" fill="#22d3ee" class="barrow"><animateMotion dur="1.3s" repeatCount="indefinite" path="M205,338 H245"/></circle>

        <g>
          <rect x="245" y="272" width="205" height="132" rx="12" fill="#16233f" stroke="#22d3ee" stroke-width="1.6"/>
          <text x="347" y="296" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">⑥ accept_token</text>
          <text x="347" y="316" text-anchor="middle" fill="#8ea0c2" font-size="10.5">喂入上一轮已接受的 token</text>
          <text x="347" y="332" text-anchor="middle" fill="#8ea0c2" font-size="10.5">(accepted + last_output)</text>
          <text x="347" y="348" text-anchor="middle" fill="#8ea0c2" font-size="10.5">非法 token → False → 判死</text>
          <text x="347" y="364" text-anchor="middle" fill="#8ea0c2" font-size="10.5">特殊 token 一律拒绝</text>
          <text x="347" y="392" text-anchor="middle" fill="#5d7294" font-size="10.5">matcher.py:134-179</text>
        </g>
        <path class="flowline" d="M450,338 H490" stroke="#22d3ee" stroke-width="2" marker-end="url(#arw2)"/>
        <circle r="4.5" fill="#22d3ee" class="barrow"><animateMotion dur="1.3s" begin=".35s" repeatCount="indefinite" path="M450,338 H490"/></circle>

        <g>
          <rect x="490" y="272" width="225" height="132" rx="12" fill="#16233f" stroke="#22d3ee" stroke-width="1.6"/>
          <text x="602" y="296" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">⑦ fill_next_token_bitmask</text>
          <text x="602" y="316" text-anchor="middle" fill="#8ea0c2" font-size="10.5">int32 位掩码 [B, ⌈vocab/32⌉]</text>
          <g>
            <rect x="512" y="328" width="11" height="15" fill="#22d3ee" opacity=".9"><animate attributeName="opacity" values=".15;1;.15" dur="2s" repeatCount="indefinite"/></rect>
            <rect x="525" y="328" width="11" height="15" fill="#22d3ee" opacity=".3"><animate attributeName="opacity" values=".3;1;.3" dur="2s" begin=".3s" repeatCount="indefinite"/></rect>
            <rect x="538" y="328" width="11" height="15" fill="#263352"/>
            <rect x="551" y="328" width="11" height="15" fill="#22d3ee" opacity=".5"><animate attributeName="opacity" values=".5;1;.5" dur="2s" begin=".6s" repeatCount="indefinite"/></rect>
            <rect x="564" y="328" width="11" height="15" fill="#263352"/>
            <rect x="577" y="328" width="11" height="15" fill="#22d3ee" opacity=".8"><animate attributeName="opacity" values=".2;1;.2" dur="2s" begin=".9s" repeatCount="indefinite"/></rect>
            <rect x="590" y="328" width="11" height="15" fill="#263352"/>
            <rect x="603" y="328" width="11" height="15" fill="#22d3ee" opacity=".6"><animate attributeName="opacity" values=".6;1;.6" dur="2s" begin="1.2s" repeatCount="indefinite"/></rect>
            <rect x="616" y="328" width="11" height="15" fill="#263352"/>
            <rect x="629" y="328" width="11" height="15" fill="#263352"/>
            <rect x="642" y="328" width="11" height="15" fill="#22d3ee" opacity=".4"><animate attributeName="opacity" values=".4;1;.4" dur="2s" begin="1.5s" repeatCount="indefinite"/></rect>
            <rect x="655" y="328" width="11" height="15" fill="#263352"/>
            <rect x="668" y="328" width="11" height="15" fill="#263352"/>
            <text x="602" y="362" text-anchor="middle" fill="#5d7294" font-size="10">1 = 合法 · 0 = 非法(每 32 个 token 压一个 int32)</text>
          </g>
          <text x="602" y="392" text-anchor="middle" fill="#5d7294" font-size="10.5">matcher.py:181-194</text>
        </g>
        <path class="flowline" d="M715,338 H755" stroke="#22d3ee" stroke-width="2" marker-end="url(#arw2)"/>
        <circle r="4.5" fill="#22d3ee" class="barrow"><animateMotion dur="1.3s" begin=".7s" repeatCount="indefinite" path="M715,338 H755"/></circle>

        <g>
          <rect x="755" y="272" width="185" height="132" rx="12" fill="#16233f" stroke="#22d3ee" stroke-width="1.6"/>
          <text x="847" y="296" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">⑧ 侧流 H2D 拷贝</text>
          <text x="847" y="316" text-anchor="middle" fill="#8ea0c2" font-size="10.5">pinned CPU 缓冲 → so_copy_stream</text>
          <text x="847" y="332" text-anchor="middle" fill="#8ea0c2" font-size="10.5">cuda(non_blocking=True)</text>
          <text x="847" y="348" text-anchor="middle" fill="#8ea0c2" font-size="10.5">so_mask_ready 事件同步</text>
          <text x="847" y="392" text-anchor="middle" fill="#5d7294" font-size="10.5">sampler.py:391-407</text>
        </g>
        <path class="flowline" d="M940,338 H985" stroke="#22d3ee" stroke-width="2" marker-end="url(#arw2)"/>
        <circle r="4.5" fill="#22d3ee" class="barrow"><animateMotion dur="1.3s" begin="1.05s" repeatCount="indefinite" path="M940,338 H985"/></circle>

        <g>
          <rect x="985" y="272" width="155" height="132" rx="12" fill="#16233f" stroke="#34d399" stroke-width="1.6"/>
          <text x="1062" y="296" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">⑨ 掩码采样</text>
          <text x="1062" y="316" text-anchor="middle" fill="#8ea0c2" font-size="10.5">TileLang 内核 inplace 掩码</text>
          <text x="1062" y="332" text-anchor="middle" fill="#f87171" font-size="10.5">非法位 logits → -inf</text>
          <text x="1062" y="348" text-anchor="middle" fill="#8ea0c2" font-size="10.5">采样 / MTP 验证</text>
          <text x="1062" y="392" text-anchor="middle" fill="#5d7294" font-size="10.5">sampler.py:433-437</text>
        </g>

        <!-- per-step loop -->
        <path class="flowline" d="M1062,404 V460 H112 V404" stroke="#34d399" stroke-width="2" fill="none" marker-end="url(#arw2)" stroke-dasharray="4 6"/>
        <circle r="4.5" fill="#34d399" class="barrow"><animateMotion dur="3.2s" repeatCount="indefinite" path="M1062,404 V460 H112 V404"/></circle>
        <text x="590" y="455" text-anchor="middle" fill="#34d399" font-size="11.5">每个 decode step:记账回写(processOutputs)→ 下一轮 accept + 掩码(sampler.py:332-389 → scheduler.hpp:928-929)</text>
      </svg>
      <div class="cap">图 3-1 · 结构化输出总流水线:上半行「请求 → schema 分发 → 编译线程池 → CompiledGrammar」一次性完成;下半行「matcher 自动机 → 逐 token 接受 → 位掩码生成 → 侧流拷贝 → 掩码采样」每个 decode step 循环执行(绿色回环)。</div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">3.1 SOMatcherBuilder:线程池与 CPU 绑核</h3>
    <p style="font-size:14px">builder 是 SO 的「编译工厂」,在引擎首次遇到带 <code>so_args</code> 的请求时懒构造(<code>llm_engine.py:227-228</code>,注释明确说:<code>get_idle_cpus</code> 在 CPU 配额不足的机型上直接 raise,不用 SO 的部署不应为此启动失败)。worker 线程通过 <code>os.sched_setaffinity(0, ...)</code> 绑到为该 GPU 预留的物理核上:</p>
    <div>
      <span class="filepath">deepinfer/structure_output/so_matcher_builder.py:33-49</span>
      <pre class="code">initializer = <span class="k">None</span>
<span class="k">if</span> bind_cpus:
    <span class="k">import</span> os

    <span class="k">def</span> <span class="f">_bind_cpu_affinity</span>() -&gt; <span class="k">None</span>:
        <span class="c"># 0 = 调用线程自身:绑定执行 initializer 的 worker 线程,而非整个进程/主线程。</span>
        <span class="c"># psutil.Process() 的默认 PID 指向主线程,不能用于绑定当前 worker 线程。</span>
        os.<span class="f">sched_setaffinity</span>(<span class="n">0</span>, <span class="f">set</span>(bind_cpus))
        logger.<span class="f">info</span>(<span class="s">"SOMatcherBuilder worker bound to cpus=%s"</span>, bind_cpus)

    initializer = _bind_cpu_affinity

self._pool = <span class="f">ThreadPoolExecutor</span>(max_workers=max_workers, initializer=initializer)
self._compiler = self._pool.<span class="f">submit</span>(XGrammarCompiler, self._tokenizer_info, num_threads=<span class="n">2</span>).<span class="f">result</span>()
<span class="c"># submit/pump 均在主线程调用,worker 线程只填 future,不碰 seq 入调度逻辑</span>
self._pending: list[tuple[object, XGrammarMatcherFuture, Callable[[object], <span class="k">None</span>]]] = []</pre>
    </div>
    <div class="note"><b>线程安全设计的关键一句:</b>「submit/pump 均在主线程调用,worker 线程只填 future,不碰 seq 入调度逻辑」(<code>so_matcher_builder.py:50</code>)。worker 只做纯计算(编译 + 回放),一切与调度器、Sequence 状态的交互都收敛在主线程,免锁。</div>

    <p style="font-size:14px">核的来源:<code>get_idle_cpus(local_rank)</code> 按「每 GPU 分到的物理核数」切出前 <code>DEEPINFER_SO_BUILDER_CPUS</code>(默认 4)个核给 builder;若配额不足直接抛错,而不是静默降级:</p>
    <div>
      <span class="filepath">deepinfer/utils.py:154-161</span>
      <pre class="code"><span class="k">def</span> <span class="f">get_idle_cpus</span>(local_rank: <span class="k">int</span>) -&gt; list[<span class="k">int</span>]:
    phy_cpus = psutil.<span class="f">cpu_count</span>(logical=<span class="k">False</span>)
    num_cpus_per_gpu = phy_cpus // <span class="f">get_actual_num_gpus</span>()
    so_builder_cpus = envs.DEEPINFER_SO_BUILDER_CPUS
    <span class="k">if</span> so_builder_cpus &gt; num_cpus_per_gpu:
        <span class="k">raise</span> <span class="f">RuntimeError</span>(<span class="s">f"num_cpus_per_gpu={num_cpus_per_gpu} 不足以容纳 SO builder 绑核 (so_builder_cpus={so_builder_cpus})"</span>)
    start = local_rank * num_cpus_per_gpu
    <span class="k">return</span> <span class="f">list</span>(<span class="f">range</span>(start, start + so_builder_cpus))</pre>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">3.2 build():编译 + 状态回放</h3>
    <p style="font-size:14px">每个请求的 matcher 在池内构建。注意 <code>replay_tokens</code>:fork / 前缀复用场景下,新 matcher 需要把已生成的 token 逐个「喂」进自动机以恢复状态,任何一个被拒绝即整体失败:</p>
    <div>
      <span class="filepath">deepinfer/structure_output/so_matcher_builder.py:58-95</span>
      <pre class="code"><span class="k">def</span> <span class="f">build</span>(self, so_args: dict, replay_tokens: list[<span class="k">int</span>] | <span class="k">None</span> = <span class="k">None</span>) -&gt; XGrammarMatcherFuture:
    replay_tokens = replay_tokens <span class="k">or</span> []
    <span class="k">if</span> <span class="s">"serialized"</span> <span class="k">in</span> so_args:
        <span class="k">raise</span> <span class="f">ValueError</span>(<span class="s">"Offline structured output does not accept serialized grammars; provide schema_type and schema"</span>)
    <span class="k">if</span> <span class="s">"bound_token_ids"</span> <span class="k">in</span> so_args:
        <span class="k">raise</span> <span class="f">ValueError</span>(<span class="s">"bound_token_ids is no longer supported; use bound_token_id with a single non-negative integer"</span>)
    ...
    <span class="k">def</span> <span class="f">_build</span>() -&gt; XGrammarMatcher:
        ctx = self._compiler.<span class="f">dispatch_and_compile</span>(so_args[<span class="s">"schema_type"</span>], schema)
        matcher = XGrammarMatcher.<span class="f">from_compiled</span>(ctx, self._vocab_size, self._eos_id, trigger_tokens, bound_token_id=bound_token_id)
        <span class="k">for</span> i, token <span class="k">in</span> <span class="f">enumerate</span>(replay_tokens):
            <span class="k">if</span> <span class="k">not</span> matcher.<span class="f">accept_token</span>(<span class="f">int</span>(token)):
                <span class="k">raise</span> <span class="f">RuntimeError</span>(<span class="s">f"SO replay failed: token {token} (idx {i}/{len(replay_tokens)}) rejected during matcher state restore"</span>)
        <span class="k">return</span> matcher

    task: Future = self._pool.<span class="f">submit</span>(_build)
    <span class="k">return</span> XGrammarMatcherFuture(task=task)</pre>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">3.3 XGrammarMatcher:自动机状态与 accept_token</h3>
    <p style="font-size:14px">matcher 包装 xgrammar 的 <code>GrammarMatcher</code>,在外面补齐了 DeepInfer 特有的状态:trigger 进度(KMP)、bound 计数、EOS 后状态、matcher 内 token 数、回滚历史——回滚上限 <code>MAX_ROLLBACK_TOKENS = DEEPINFER_USE_NEXTN_DECODE + 2</code>(默认 nextn=5 时为 7,<code>matcher.py:20</code> + <code>environ.py:136</code>),正好覆盖「一步最多接受的 draft 数 + 余量」:</p>
    <div>
      <span class="filepath">deepinfer/structure_output/matcher.py:18-20, 74-83</span>
      <pre class="code">DEBUG_PRINT = envs.DEEPINFER_XGRAMMAR_DEBUG
DEEPINFER_XGRAMMAR_TIMEOUT = envs.DEEPINFER_XGRAMMAR_TIMEOUT
MAX_ROLLBACK_TOKENS = envs.DEEPINFER_USE_NEXTN_DECODE + <span class="n">2</span>
...
<span class="c"># XGrammarMatcher.__init__ 内的 SO 簿记状态</span>
self.trigger_progress = <span class="n">0</span>          <span class="c"># KMP 匹配进度</span>
self._trigger_failure = <span class="f">_kmp_failure</span>(self.trigger_tokens)
self._progress_history: list[<span class="k">int</span>] = []  <span class="c"># 回滚用历史,容量上限 MAX_ROLLBACK_TOKENS</span>
self.tokens_after_bound = -<span class="n">1</span>      <span class="c"># bound 触发后已走 token 数;-1 未触发</span>
self.tokens_in_matcher = <span class="n">0</span>       <span class="c"># 已喂入 xgrammar 自动机的 token 数</span>
self.tokens_after_eos = -<span class="n">1</span>       <span class="c"># EOS 已接受后的 token 数;-1 未结束</span>
...
self.inner_matcher = <span class="f">InnerMatcher</span>(ctx, max_rollback_tokens=MAX_ROLLBACK_TOKENS)</pre>
    </div>

    <p style="font-size:14px"><code>accept_token</code> 是状态机的心脏,四条分支:①trigger 未完成且未 bound → KMP 流式推进;②trigger 未完成且已 bound → 精确匹配下一个 trigger token;③EOS 已接受 → 只计数;④正常约束期 → 喂 xgrammar 自动机:</p>
    <div>
      <span class="filepath">deepinfer/structure_output/matcher.py:134-179(节选)</span>
      <pre class="code"><span class="k">def</span> <span class="f">accept_token</span>(self, token: <span class="k">int</span>) -&gt; bool:
    <span class="k">if</span> self._trigger_pending():                       <span class="c"># trigger 序列尚未完整出现</span>
        <span class="k">if</span> self._bound_fired():                       <span class="c"># 已 bound:只许精确匹配 trigger</span>
            <span class="k">if</span> token != self.trigger_tokens[self.trigger_progress]:
                <span class="k">return</span> <span class="k">False</span>
            ...
        <span class="k">else</span>:                                         <span class="c"># 未 bound:KMP 流式匹配,允许自由生成</span>
            progress = self.trigger_progress
            <span class="k">while</span> progress &gt; <span class="n">0</span> <span class="k">and</span> token != self.trigger_tokens[progress]:
                progress = self._trigger_failure[progress - <span class="n">1</span>]
            <span class="k">if</span> token == self.trigger_tokens[progress]:
                progress += <span class="n">1</span>
            self.trigger_progress = progress
        ...
        <span class="k">return</span> <span class="k">True</span>                                    <span class="c"># trigger 期自由 token 一律放行</span>
    <span class="k">if</span> self.<span class="f">finished</span>():                                <span class="c"># EOS 之后:仅计数</span>
        self.tokens_after_eos += <span class="n">1</span>
        <span class="k">return</span> <span class="k">True</span>
    res = self.inner_matcher.<span class="f">accept_token</span>(token, debug_print=DEBUG_PRINT)
    <span class="k">if</span> res:
        self.tokens_in_matcher += <span class="n">1</span>
        ...
        <span class="k">if</span> token == self.eos_token_id:                <span class="c"># 接受 EOS:进入收尾状态</span>
            self.tokens_after_eos = <span class="n">0</span>
    <span class="k">return</span> res</pre>
    </div>

    <p style="font-size:14px"><code>fill_vocab_mask</code> 把「当前位置允许哪些 token」写进位掩码,三条路径——bound 未走完时直接手写单 token 位(比 xgrammar 快)、EOS 后复制全 1 掩码、正常路径调用 xgrammar:</p>
    <div>
      <span class="filepath">deepinfer/structure_output/matcher.py:181-204(节选)</span>
      <pre class="code"><span class="k">def</span> <span class="f">fill_vocab_mask</span>(self, vocab_mask: torch.Tensor, idx: <span class="k">int</span>) -&gt; bool:
    <span class="k">if</span> self._bound_fired() <span class="k">and</span> self._trigger_pending():
        expected = self.trigger_tokens[self.trigger_progress]      <span class="c"># 只允许 trigger 的下一个 token</span>
        vocab_mask[idx].<span class="f">zero_</span>()
        vocab_mask[idx][expected &gt;&gt; <span class="n">5</span>] |= np.<span class="f">int32</span>(np.<span class="f">uint32</span>(<span class="n">1</span> &lt;&lt; (expected &amp; <span class="n">31</span>)))  <span class="c"># 手写 bit:word = id&gt;&gt;5, bit = id&amp;31</span>
        <span class="k">return</span> <span class="k">True</span>
    <span class="k">if</span> self.<span class="f">finished</span>():
        vocab_mask[idx].<span class="f">copy_</span>(self.mask_after_eos)                 <span class="c"># EOS 后:全 1(请求即将 stop)</span>
        <span class="k">return</span> <span class="k">True</span>
    self.inner_matcher.<span class="f">fill_next_token_bitmask</span>(vocab_mask, idx, debug_print=DEBUG_PRINT)
    <span class="k">return</span> <span class="k">True</span></pre>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">3.4 位掩码格式与 TileLang 掩码内核</h3>
    <p style="font-size:14px">掩码是 xgrammar 的标准 bitmask 布局:<code>[batch, ⌈vocab_size/32⌉]</code> 的 int32 张量,第 k 个 bit 为 1 表示 token k 合法(<code>get_bitmask_shape</code> / <code>bitmask_dtype</code>,<code>matcher.py:14</code>;分配入口 <code>allocate_vocab_mask</code>,<code>matcher.py:36-45</code>)。GPU 侧的掩蔽内核是 TileLang 实现,支持 <b>按 step 寻址</b>——这是 MTP 兼容的关键:</p>
    <div>
      <span class="filepath">deepinfer/model_executor/layers/tilelang_ops/structure_output.py:12-37</span>
      <pre class="code"><span class="k">def</span> <span class="f">apply_token_bitmask_by_step_inplace</span>(
    logits: torch.Tensor,      <span class="c"># [total_q, vocab_size], fp32, 按请求打包,inplace 修改</span>
    bitmask: torch.Tensor,     <span class="c"># [num_requests, ceil(vocab_size / 32)], int32</span>
    indices: torch.Tensor,     <span class="c"># [num_selected_requests], CUDA int32</span>
    ftp: torch.Tensor | <span class="k">None</span> = <span class="k">None</span>,  <span class="c"># [num_requests]: 每个请求首个打包行;None 时 indices 直接寻址</span>
    step: <span class="k">int</span> = <span class="n">0</span>,           <span class="c"># 相对每请求首行的偏移(draft 第 k 步)</span>
) -&gt; <span class="k">None</span>:
    ...
    kernel = ops.<span class="f">apply_token_bitmask_by_step_inplace_tl</span>(vocab_size, ftp <span class="k">is</span> <span class="k">not</span> <span class="k">None</span>)
    kernel(logits, bitmask, indices, ftp, step)</pre>
    </div>
    <p style="font-size:14px">语义上等价于参考实现(<code>structure_output.py:40-61</code>):<code>allowed = (bitmask[req, word_ids] &gt;&gt; bit_ids) &amp; 1</code>,随后 <code>logits[row].masked_fill_(~allowed, -inf)</code>。基准测试用 V4.1-Flash 的真实词表规模 <code>vocab_size=129280</code>(<code>structure_output.py:106</code>),batch 512 时掩蔽依然是纯带宽型小内核。</p>
    <div class="note good"><b>懒加载细节:</b><code>mask.py</code> 的 <code>allocate_vocab_mask</code> 用函数内懒 import——「本模块在 sampler import 闭包里,顶层 import 会把 xgrammar 拖进不用 SO 的部署」(<code>mask.py:16-20</code>);而 <code>XGrammarUtils.apply_vocab_mask_by_step_inplace</code>(<code>mask.py:23-33</code>)只是 TileLang 内核的薄断言包装(indices 设备/dtype 校验)。不用 SO 的服务完全不感知 xgrammar 的存在。</div>
  </section>

  <!-- ================= 4. 异步编译、超时与缓存 ================= -->
  <section id="s4">
    <h2 class="sec"><span class="num">4</span>异步编译与超时 / 缓存机制详解</h2>
    <p class="lede">文法编译可能是 CPU 密集操作(复杂 JSON Schema 可达数百毫秒甚至更久)。若同步编译,一条坏请求就能卡住整个引擎 step。DeepInfer 把编译完全异步化,并给每个编译任务一个从提交时刻起算的超时窗。</p>

    <div class="figure reveal">
      <svg viewBox="0 0 1160 470" xmlns="http://www.w3.org/2000/svg" font-family="'PingFang SC','Microsoft YaHei',sans-serif">
        <defs>
          <marker id="arw3" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
            <path d="M0,0 L9,4.5 L0,9 z" fill="#4f8cff"/>
          </marker>
          <marker id="arw4" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
            <path d="M0,0 L9,4.5 L0,9 z" fill="#34d399"/>
          </marker>
          <marker id="arw5" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
            <path d="M0,0 L9,4.5 L0,9 z" fill="#f87171"/>
          </marker>
        </defs>

        <!-- lane backgrounds -->
        <rect x="60" y="42" width="1080" height="160" rx="12" fill="rgba(79,140,255,.05)" stroke="#263352"/>
        <rect x="60" y="288" width="1080" height="130" rx="12" fill="rgba(167,139,250,.05)" stroke="#263352"/>
        <text x="52" y="128" fill="#8ea0c2" font-size="13" font-weight="700" transform="rotate(-90 52 128)" text-anchor="middle">Engine 主线程</text>
        <text x="52" y="358" fill="#8ea0c2" font-size="13" font-weight="700" transform="rotate(-90 52 358)" text-anchor="middle">Worker 线程池</text>

        <!-- engine lane -->
        <g>
          <rect x="84" y="66" width="160" height="86" rx="10" fill="#16233f" stroke="#4f8cff" stroke-width="1.5"/>
          <text x="164" y="88" text-anchor="middle" fill="#fff" font-size="12.5" font-weight="700">add_request()</text>
          <text x="164" y="108" text-anchor="middle" fill="#8ea0c2" font-size="10.5">so_args ≠ None 且 enqueue</text>
          <text x="164" y="126" text-anchor="middle" fill="#5d7294" font-size="10">llm_engine.py:606-613</text>
        </g>
        <path class="flowline" d="M244,109 H292" stroke="#4f8cff" stroke-width="2" marker-end="url(#arw3)"/>
        <circle r="4" fill="#22d3ee" class="barrow"><animateMotion dur="1.4s" repeatCount="indefinite" path="M244,109 H292"/></circle>

        <g>
          <rect x="292" y="66" width="172" height="86" rx="10" fill="#16233f" stroke="#4f8cff" stroke-width="1.5"/>
          <text x="378" y="88" text-anchor="middle" fill="#fff" font-size="12.5" font-weight="700">submit(seq, so_args)</text>
          <text x="378" y="108" text-anchor="middle" fill="#8ea0c2" font-size="10.5">(seq, future, on_ready) 入 _pending</text>
          <text x="378" y="126" text-anchor="middle" fill="#5d7294" font-size="10">so_matcher_builder.py:97-107</text>
        </g>
        <path class="flowline" d="M464,109 H512" stroke="#4f8cff" stroke-width="2" marker-end="url(#arw3)"/>
        <circle r="4" fill="#22d3ee" class="barrow"><animateMotion dur="1.4s" begin=".3s" repeatCount="indefinite" path="M464,109 H512"/></circle>

        <g>
          <rect class="pulse" x="512" y="66" width="196" height="86" rx="10" fill="#16233f" stroke="#22d3ee" stroke-width="1.8"/>
          <text x="610" y="88" text-anchor="middle" fill="#fff" font-size="12.5" font-weight="700">每 step:pre_sampler_sync()</text>
          <text x="610" y="108" text-anchor="middle" fill="#8ea0c2" font-size="10.5">pump() 轮询 _pending(非阻塞)</text>
          <text x="610" y="126" text-anchor="middle" fill="#5d7294" font-size="10">llm_engine.py:841-842</text>
        </g>
        <path class="flowline" d="M708,109 H756" stroke="#4f8cff" stroke-width="2" marker-end="url(#arw3)"/>
        <circle r="4" fill="#22d3ee" class="barrow"><animateMotion dur="1.4s" begin=".6s" repeatCount="indefinite" path="M708,109 H756"/></circle>

        <g>
          <rect x="756" y="66" width="150" height="86" rx="10" fill="#16233f" stroke="#4f8cff" stroke-width="1.5"/>
          <text x="831" y="88" text-anchor="middle" fill="#fff" font-size="12.5" font-weight="700">try_result()</text>
          <text x="831" y="108" text-anchor="middle" fill="#8ea0c2" font-size="10.5">done → 取结果 / 超时 → abort</text>
          <text x="831" y="126" text-anchor="middle" fill="#5d7294" font-size="10">matcher.py:319-338</text>
        </g>

        <!-- outcomes -->
        <path class="flowline" d="M906,95 H948" stroke="#34d399" stroke-width="2" marker-end="url(#arw4)"/>
        <path class="flowline" d="M906,132 H948" stroke="#f87171" stroke-width="2" marker-end="url(#arw5)"/>
        <g>
          <rect x="948" y="66" width="192" height="42" rx="9" fill="rgba(52,211,153,.10)" stroke="#34d399" stroke-width="1.5"/>
          <text x="1044" y="83" text-anchor="middle" fill="#34d399" font-size="10.5" font-weight="700">编译完成 → seq.so_matcher = matcher</text>
          <text x="1044" y="99" text-anchor="middle" fill="#34d399" font-size="10">on_ready(seq) → add_sequence 入 waiting</text>
        </g>
        <g>
          <rect x="948" y="118" width="192" height="42" rx="9" fill="rgba(248,113,113,.10)" stroke="#f87171" stroke-width="1.5" class="pulse"/>
          <text x="1044" y="135" text-anchor="middle" fill="#f87171" font-size="10.5" font-weight="700">超时 20s / 异常 → aborted_matcher</text>
          <text x="1044" y="151" text-anchor="middle" fill="#f87171" font-size="10">_enqueue 置 FINISHED_SO_FAILED</text>
        </g>

        <!-- worker lane -->
        <g>
          <rect x="292" y="308" width="172" height="86" rx="10" fill="#16233f" stroke="#a78bfa" stroke-width="1.5"/>
          <text x="378" y="330" text-anchor="middle" fill="#fff" font-size="12.5" font-weight="700">_build()(池内执行)</text>
          <text x="378" y="350" text-anchor="middle" fill="#8ea0c2" font-size="10.5">编译 + from_compiled + replay</text>
          <text x="378" y="368" text-anchor="middle" fill="#5d7294" font-size="10">CPU 绑核 worker(默认 4 核)</text>
        </g>
        <path class="flowline" d="M464,351 H512" stroke="#a78bfa" stroke-width="2" marker-end="url(#arw3)"/>
        <circle r="4" fill="#a78bfa" class="barrow"><animateMotion dur="1.8s" repeatCount="indefinite" path="M464,351 H512"/></circle>

        <g>
          <rect x="512" y="308" width="196" height="86" rx="10" fill="#16233f" stroke="#a78bfa" stroke-width="1.5"/>
          <text x="610" y="330" text-anchor="middle" fill="#fff" font-size="12.5" font-weight="700">dispatch_and_compile()</text>
          <text x="610" y="350" text-anchor="middle" fill="#8ea0c2" font-size="10.5">regex / json / ebnf → CompiledGrammar</text>
          <text x="610" y="368" text-anchor="middle" fill="#5d7294" font-size="10">命中缓存则秒回</text>
        </g>
        <path class="flowline" d="M708,351 H756" stroke="#a78bfa" stroke-width="2" marker-end="url(#arw3)"/>
        <circle r="4" fill="#a78bfa" class="barrow"><animateMotion dur="1.8s" begin=".5s" repeatCount="indefinite" path="M708,351 H756"/></circle>

        <g>
          <rect x="756" y="308" width="150" height="86" rx="10" fill="#16233f" stroke="#a78bfa" stroke-width="1.5"/>
          <text x="831" y="330" text-anchor="middle" fill="#fff" font-size="12.5" font-weight="700">future 完成</text>
          <text x="831" y="350" text-anchor="middle" fill="#8ea0c2" font-size="10.5">matcher 就绪(或异常)</text>
          <text x="831" y="368" text-anchor="middle" fill="#5d7294" font-size="10">XGrammarMatcherFuture</text>
        </g>

        <!-- submit down / result up -->
        <path class="flowline" d="M378,152 V308" stroke="#4f8cff" stroke-width="2" stroke-dasharray="5 6" marker-end="url(#arw3)"/>
        <text x="392" y="235" fill="#8ea0c2" font-size="10.5">pool.submit(_build)</text>
        <path class="flowline" d="M831,308 V152" stroke="#34d399" stroke-width="2" stroke-dasharray="5 6" marker-end="url(#arw4)"/>
        <circle r="4.5" fill="#34d399" class="barrow"><animateMotion dur="2.2s" repeatCount="indefinite" path="M831,308 V152"/></circle>
        <text x="845" y="245" fill="#34d399" font-size="10.5">future.done() → 结果上浮</text>

        <!-- timeout window -->
        <path d="M378,262 H831" stroke="#fbbf24" stroke-width="1.6" stroke-dasharray="6 6" fill="none"/>
        <text x="604" y="282" text-anchor="middle" fill="#fbbf24" font-size="11">DEEPINFER_XGRAMMAR_TIMEOUT = 20s(自 future 构造时刻起算,matcher.py:265-269)</text>
        <circle r="5" class="barrow">
          <animateMotion dur="6s" repeatCount="indefinite" path="M378,262 H831"/>
          <animate attributeName="fill" values="#22d3ee;#fbbf24;#f87171" dur="6s" repeatCount="indefinite"/>
        </circle>
        <g class="pulse">
          <circle cx="356" cy="262" r="9" fill="none" stroke="#fbbf24" stroke-width="1.5"/>
          <path d="M356,256 v5 l3.5,3" stroke="#fbbf24" stroke-width="1.5" fill="none"/>
        </g>
      </svg>
      <div class="cap">图 4-1 · 异步编译生命周期:主线程 submit 后立即返回,pending 队列由每 step 的 pump 非阻塞收割;worker 线程绑核编译,结果经 future 上浮;黄线是 20 秒超时窗,游标颜色由青转红,越窗即判 aborted_matcher → FINISHED_SO_FAILED。</div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">4.1 引擎侧:同步与异步两条接入路径</h3>
    <p style="font-size:14px"><code>add_request</code> 里按 <code>enqueue</code> 参数分流:<code>enqueue=False</code>(调用方自行管理调度,如 benchmark)时无法靠 pump 重入,退回<strong>同步阻塞构建</strong>;常规路径走异步 submit:</p>
    <div>
      <span class="filepath">deepinfer/engine/llm_engine.py:606-630</span>
      <pre class="code">so_pending = <span class="k">False</span>
<span class="k">if</span> sampling_params.so_args <span class="k">is</span> <span class="k">not</span> <span class="k">None</span>:
    so_args = sampling_params.so_args
    <span class="k">if</span> <span class="k">not</span> enqueue:
        <span class="c"># 调用方自行管理调度,无法靠 pump 重入,保持同步构建</span>
        seq.so_matcher = self.so_matcher_builder.<span class="f">build</span>(so_args).<span class="f">result</span>()   <span class="c"># 阻塞至编译完成/超时</span>
    <span class="k">else</span>:
        so_pending = <span class="k">True</span>
...
<span class="k">def</span> <span class="f">_enqueue</span>(s: Sequence) -&gt; <span class="k">None</span>:
    <span class="k">if</span> s.so_matcher <span class="k">is</span> <span class="k">not</span> <span class="k">None</span> <span class="k">and</span> s.so_matcher.<span class="f">is_aborted</span>():
        s.status = SequenceStatus.FINISHED_SO_FAILED               <span class="c"># 编译超时/失败:入队前即判死</span>
    self.scheduler.<span class="f">add_sequence</span>(s)
    ...
<span class="k">if</span> so_pending:
    self.so_matcher_builder.<span class="f">submit</span>(seq, sampling_params.so_args, _enqueue)
<span class="k">else</span>:
    <span class="f">_enqueue</span>(seq)</pre>
    </div>

    <p style="font-size:14px">编译中的请求<b>尚未进入调度器</b>,但引擎必须把它们计入「未完成」统计,否则 <code>has_unfinished_requests</code> 提前翻假、DP 各 rank 的 all-reduce(MAX)也会不一致:</p>
    <div>
      <span class="filepath">deepinfer/engine/llm_engine.py:658-663, 673-674, 841-842</span>
      <pre class="code"><span class="k">def</span> <span class="f">get_num_unfinished_requests</span>(self) -&gt; <span class="k">int</span>:
    num_requests = self.scheduler.<span class="f">get_num_unfinished_seqs</span>()
    <span class="k">if</span> self._so_matcher_builder <span class="k">is</span> <span class="k">not</span> <span class="k">None</span>:
        num_requests += self._so_matcher_builder.<span class="f">get_num_pending</span>()   <span class="c"># pending 也算未完成</span>
    <span class="k">return</span> num_requests
...
unfinished = unfinished <span class="k">or</span> self.<span class="f">so_builder_has_pending</span>()                    <span class="c"># DP all_reduce(Max) 的一部分</span>
...
<span class="c"># pre_sampler_sync(每 step、采样前)——ZOS 异步调度下也在主线程稳定执行</span>
<span class="k">if</span> self._so_matcher_builder <span class="k">is</span> <span class="k">not</span> <span class="k">None</span>:
    self._so_matcher_builder.<span class="f">pump</span>()</pre>
    </div>

    <p style="font-size:14px"><code>pump</code> 本体是 O(pending) 的非阻塞轮询:<code>try_result()</code> 返回 None 表示仍在编译,继续挂住;一旦有结果(含超时产出的 aborted_matcher),就把 matcher 挂到 seq 并回调 <code>on_ready</code> 入调度:</p>
    <div>
      <span class="filepath">deepinfer/structure_output/so_matcher_builder.py:109-121</span>
      <pre class="code"><span class="k">def</span> <span class="f">pump</span>(self) -&gt; <span class="k">None</span>:
    <span class="s">"""轮询 pending,把已编完的 seq 出队并 on_ready 入调度。"""</span>
    <span class="k">if</span> <span class="k">not</span> self._pending:
        <span class="k">return</span>
    still_pending = []
    <span class="k">for</span> seq, future, on_ready <span class="k">in</span> self._pending:
        matcher = future.<span class="f">try_result</span>()  <span class="c"># 非阻塞,超时返回 aborted_matcher</span>
        <span class="k">if</span> matcher <span class="k">is</span> <span class="k">None</span>:
            still_pending.<span class="f">append</span>((seq, future, on_ready))
            <span class="k">continue</span>
        seq.so_matcher = matcher
        on_ready(seq)
    self._pending = still_pending</pre>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">4.2 超时语义:从提交时刻起算的「死线」</h3>
    <p style="font-size:14px"><code>XGrammarMatcherFuture</code> 构造时记下 <code>start_time = time.monotonic()</code> 并固定超时上限(默认 <code>DEEPINFER_XGRAMMAR_TIMEOUT=20</code> 秒,<code>matcher.py:19</code> + <code>environ.py:175</code>)。无论走阻塞的 <code>result()</code> 还是非阻塞的 <code>try_result()</code>,剩余时间都从这条死线扣:</p>
    <div>
      <span class="filepath">deepinfer/structure_output/matcher.py:261-269, 297-317, 319-338(节选)</span>
      <pre class="code"><span class="k">class</span> <span class="f">XGrammarMatcherFuture</span>:
    <span class="k">def</span> <span class="f">__init__</span>(self, task: Future, timeout: <span class="k">int</span> = DEEPINFER_XGRAMMAR_TIMEOUT) -&gt; <span class="k">None</span>:
        self.task = task
        self.timeout = timeout
        self.start_time = time.<span class="f">monotonic</span>()          <span class="c"># 死线起点 = 提交时刻</span>
        ...
<span class="c"># 阻塞路径(add_request 的同步分支)</span>
    <span class="k">def</span> <span class="f">result</span>(self) -&gt; XGrammarMatcher:
        ...
        rem_time = self.timeout - (time.<span class="f">monotonic</span>() - self.start_time)
        rem_time = <span class="f">max</span>(rem_time, <span class="n">1e-5</span>)
        <span class="k">try</span>:
            self._resolve(rem_time)
        <span class="k">except</span> concurrent.futures.TimeoutError:
            self.res = XGrammarMatcher.<span class="f">aborted_matcher</span>(<span class="s">"xgrammar timeout when waiting for result"</span>)
        ...
<span class="c"># 非阻塞路径(pump 每步调用)</span>
    <span class="k">def</span> <span class="f">try_result</span>(self) -&gt; XGrammarMatcher | <span class="k">None</span>:
        ...
        <span class="k">elif</span> time.<span class="f">monotonic</span>() - self.start_time &gt; self.timeout:
            self.res = XGrammarMatcher.<span class="f">aborted_matcher</span>(
                <span class="s">f"xgrammar runtime error when try_result, timeout({time.monotonic() - self.start_time:.2f}s)"</span>)</pre>
    </div>
    <ul class="feat reveal">
      <li><b>超时不是杀线程</b>:xgrammar 编译无法安全中断,所以超时只产生一个 <code>aborted_matcher</code> 哨兵(内部 <code>ctx=None</code>,<code>matcher.py:87-92</code>),请求被判死;后台编译继续跑完,结果被 <code>release()</code> 丢弃(<code>matcher.py:273-286</code>——对未完成任务还会调用 <code>task.cancel()</code>,已完成的则释放 matcher 资源)。</li>
      <li><b>abort 惰性传播</b>:aborted matcher 被 <code>is_aborted()</code> 感知的时机有三处——入队前(<code>llm_engine.py:621-622</code>)、sampler 的 <code>update_so_status</code>(<code>sampler.py:347-350</code>,置 <code>so_status=-1</code>)、以及日志(<code>_log_abort</code>,<code>matcher.py:288-291</code>,只打一次 debug)。</li>
      <li><b>释放路径完备</b>:引擎 <code>close()</code> 会显式 <code>shutdown()</code> builder——等线程池排空、release 所有 pending future、关闭 compiler 并清空缓存(<code>llm_engine.py:358-361</code> + <code>so_matcher_builder.py:129-138</code>),注释指出只依赖 GC 的话 nanobind 会在 atexit 报泄漏。</li>
    </ul>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">4.3 编译缓存:性能优化与 DoS 防线</h3>
    <p style="font-size:14px">同一 schema 反复出现(比如全站共用一个 JSON Schema)时,缓存让编译近乎零成本。但缓存也是内存风险点——DeepInfer 在 <code>XGrammarCompiler</code> 构造时把策略全部显式化:</p>
    <div>
      <span class="filepath">deepinfer/structure_output/compiler.py:16-39</span>
      <pre class="code"><span class="k">class</span> <span class="f">XGrammarCompiler</span>:
    <span class="k">def</span> <span class="f">__init__</span>(self, tokenizer_info: TokenizerInfo, num_threads: <span class="k">int</span>) -&gt; <span class="k">None</span>:
        self.vocab_size = tokenizer_info.vocab_size
        <span class="c"># xgrammar &lt;= 0.1.x had production incidents with cache enabled; keep this env as the kill switch.</span>
        self.disable_cache = envs.DEEPINFER_XGRAMMAR_DISABLE_CACHE
        self.cache_limit_bytes = envs.DEEPINFER_XGRAMMAR_CACHE_LIMIT_BYTES

        <span class="k">if</span> self.disable_cache:
            logger.<span class="f">info</span>(<span class="s">"Cache for xgrammar is disabled."</span>)
        <span class="k">elif</span> self.cache_limit_bytes &lt;= <span class="n">0</span>:
            logger.<span class="f">warning</span>(
                <span class="s">"xgrammar cache is enabled WITHOUT a size limit (DEEPINFER_XGRAMMAR_CACHE_LIMIT_BYTES=%d). "</span>
                <span class="s">"The cache grows unboundedly with distinct schemas and may cause OOM (DoS vector, "</span>
                <span class="s">"see CVE-2025-32381). Set a positive byte limit for production."</span>, ...)
        <span class="k">else</span>:
            logger.<span class="f">info</span>(<span class="s">f"The cache size limit for xgrammar is set to {self.cache_limit_bytes // 1024 // 1024}MB."</span>)
        ...
        self.inner_compiler = <span class="f">InnerCompiler</span>(
            tokenizer_info=tokenizer_info,
            cache_enabled=<span class="k">not</span> self.disable_cache,
            max_threads=num_threads,
            cache_limit_bytes=self.cache_limit_bytes,
        )</pre>
    </div>
    <div class="note warn">
      <b>三个层次的防御:</b>①<b>kill switch</b>——<code>DEEPINFER_XGRAMMAR_DISABLE_CACHE</code> 一键关缓存(注释:xgrammar ≤ 0.1.x 开缓存出过生产事故,保留开关以备新版本再翻车);②<b>默认上限 10 GiB</b>(<code>environ.py:177</code>),超限由 xgrammar 按其 LRU 淘汰;③<b>无上限时大声告警</b>——明确点名无界缓存是 DoS 向量并引用 CVE-2025-32381。缓存挂在「每个 builder 一个 compiler、每个 compiler 绑定一个 tokenizer」的结构上,所以缓存键天然按模型隔离(<code>so_matcher_builder.py:29</code> + <code>:49</code>)。
    </div>
  </section>

  <!-- ================= 5. 与采样/调度/投机解码的交互 ================= -->
  <section id="s5">
    <h2 class="sec"><span class="num">5</span>与采样 / 调度 / 投机解码的交互</h2>
    <p class="lede">SO 不是孤立模块:它寄生在采样热路径上,与 C++ 调度器的状态账本、DSpark(MTP)投机解码、golden token 强制输出、抢占与 fork 全部纠缠在一起。这一节是全特性的「难点密集区」。</p>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">5.1 so_status:跨 Python/C++ 的状态账本</h3>
    <p style="font-size:14px">matcher 的 Python 对象持有自动机状态,但「SO 是否激活」由 C++ <code>Sequence</code> 上的整型账本 <code>structured_output.status</code> 记录,经 pybind 双向暴露(<code>pybind_sequence.cpp:123-124</code>),并在构造 <code>SequenceMetadata</code> 时快照给采样器(<code>sequence.hpp:368-369, 384</code>;ZOS 路径用 <code>refresh_for_sampling</code> 刷新,<code>sequence.hpp:408-418</code>,pybind 侧注明必须持 GIL,<code>pybind_scheduler.cpp:51</code>):</p>
    <div>
      <span class="filepath">csrc/engine/sequence.hpp:230-233</span>
      <pre class="code"><span class="k">struct</span> <span class="f">StructuredOutputState</span> {
    <span class="k">int</span> status{<span class="n">0</span>}; <span class="c">// 0 还没开始,1 刚开始(交界处),2 已经开始了,-1 aborted</span>
    py::object matcher = py::none();
};</pre>
    </div>

    <div class="figure reveal">
      <svg viewBox="0 0 1160 300" xmlns="http://www.w3.org/2000/svg" font-family="'PingFang SC','Microsoft YaHei',sans-serif">
        <defs>
          <marker id="arw6" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
            <path d="M0,0 L9,4.5 L0,9 z" fill="#4f8cff"/>
          </marker>
          <marker id="arw7" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
            <path d="M0,0 L9,4.5 L0,9 z" fill="#f87171"/>
          </marker>
        </defs>
        <!-- state 0 -->
        <g>
          <rect x="60" y="80" width="220" height="100" rx="14" fill="#16233f" stroke="#4f8cff" stroke-width="1.6"/>
          <text x="170" y="112" text-anchor="middle" fill="#fff" font-size="15" font-weight="800">status = 0</text>
          <text x="170" y="134" text-anchor="middle" fill="#8ea0c2" font-size="11.5">未激活:prompt 尚未算完</text>
          <text x="170" y="152" text-anchor="middle" fill="#8ea0c2" font-size="11.5">(chunked prefill 中间 chunk)</text>
          <text x="170" y="170" text-anchor="middle" fill="#5d7294" font-size="10">sampler 早退分支 sampler.py:318</text>
        </g>
        <path class="flowline" d="M280,130 H350" stroke="#4f8cff" stroke-width="2" marker-end="url(#arw6)"/>
        <circle r="4.5" fill="#22d3ee" class="barrow"><animateMotion dur="2.2s" repeatCount="indefinite" path="M280,130 H350"/></circle>
        <text x="315" y="112" text-anchor="middle" fill="#8ea0c2" font-size="10">最后 prefill chunk</text>
        <text x="315" y="126" text-anchor="middle" fill="#5d7294" font-size="9.5">llm_engine.py:913-915</text>

        <!-- state 1 -->
        <g>
          <rect x="350" y="80" width="220" height="100" rx="14" fill="#16233f" stroke="#fbbf24" stroke-width="1.6"/>
          <text x="460" y="112" text-anchor="middle" fill="#fff" font-size="15" font-weight="800">status = 1</text>
          <text x="460" y="134" text-anchor="middle" fill="#8ea0c2" font-size="11.5">交界:最后 prefill chunk 采样步</text>
          <text x="460" y="152" text-anchor="middle" fill="#8ea0c2" font-size="11.5">本步产出的第 1 个 token 即受掩码约束</text>
          <text x="460" y="170" text-anchor="middle" fill="#5d7294" font-size="10">首个生成 token 被掩码,prompt 不进自动机</text>
        </g>
        <path class="flowline" d="M570,130 H640" stroke="#4f8cff" stroke-width="2" marker-end="url(#arw6)"/>
        <circle r="4.5" fill="#22d3ee" class="barrow"><animateMotion dur="2.2s" begin=".6s" repeatCount="indefinite" path="M570,130 H640"/></circle>
        <text x="605" y="112" text-anchor="middle" fill="#8ea0c2" font-size="10">sampler 首次处理</text>
        <text x="605" y="126" text-anchor="middle" fill="#5d7294" font-size="9.5">sampler.py:356-357</text>

        <!-- state 2 -->
        <g>
          <rect x="640" y="80" width="220" height="100" rx="14" fill="#16233f" stroke="#34d399" stroke-width="1.8" class="pulse"/>
          <text x="750" y="112" text-anchor="middle" fill="#fff" font-size="15" font-weight="800">status = 2</text>
          <text x="750" y="134" text-anchor="middle" fill="#8ea0c2" font-size="11.5">激活:每个 decode step</text>
          <text x="750" y="152" text-anchor="middle" fill="#8ea0c2" font-size="11.5">接受上轮 token → 填掩码 → 回滚 draft</text>
          <text x="750" y="170" text-anchor="middle" fill="#5d7294" font-size="10">sampler.py:352-355 / 361-376</text>
          <path class="flowline" d="M860,95 C915,60 915,60 862,92" stroke="#34d399" stroke-width="2" fill="none" marker-end="url(#arw6)"/>
        </g>

        <!-- aborted -->
        <path class="flowline" d="M750,180 V225 H985" stroke="#f87171" stroke-width="2" marker-end="url(#arw7)"/>
        <text x="858" y="215" text-anchor="middle" fill="#f87171" font-size="10.5">编译超时 / matcher 运行时错误 / 不变量破坏 → aborted</text>
        <g>
          <rect x="985" y="80" width="160" height="100" rx="14" fill="rgba(248,113,113,.08)" stroke="#f87171" stroke-width="1.6"/>
          <text x="1065" y="106" text-anchor="middle" fill="#fff" font-size="15" font-weight="800">status = -1</text>
          <text x="1065" y="126" text-anchor="middle" fill="#8ea0c2" font-size="10.5">aborted:请求判死</text>
          <text x="1065" y="142" text-anchor="middle" fill="#f87171" font-size="10.5">FINISHED_SO_FAILED</text>
          <text x="1065" y="158" text-anchor="middle" fill="#5d7294" font-size="9.5">scheduler.hpp:977 补 token 0</text>
        </g>
        <g>
          <rect x="985" y="222" width="160" height="34" rx="9" fill="rgba(248,113,113,.10)" stroke="#f87171" stroke-width="1.2"/>
          <text x="1065" y="244" text-anchor="middle" fill="#f87171" font-size="10.5">进 ignored_seqs 带回 finish_reason</text>
        </g>

        <text x="60" y="50" fill="#8ea0c2" font-size="12.5" font-weight="700">so_status 状态机(账本在 C++ Sequence 上,采样器每步上报回写 scheduler.hpp:928-929)</text>
        <text x="640" y="262" text-anchor="middle" fill="#5d7294" font-size="10.5">回写链:SamplerOutput.so_status(list[int]) → scheduler.processOutputs → seq.structured_output.status(sequence.py:254-255 / llm_engine.py:728-734)</text>
      </svg>
      <div class="cap">图 5-1 · so_status 状态机:0(未激活)→ 1(最后 prefill chunk 交界,首个生成 token 起即被掩码)→ 2(每 decode step 常态);任何失败路径收敛到 -1,由 C++ 账本判死,防「判死后自由生成」。</div>
    </div>

    <div class="note"><b>为什么需要「账本」而不只看当步上报?</b><code>scheduler.hpp:972-981</code> 的注释给出答案:sampler 对「批内无活跃 SO」的步返回 <code>so_status=None</code>,若只认当步上报,账本已是 -1 的 seq(例如 prefill engine 判死后迁到 completion engine 的副本)会无约束自由生成——所以判死只看账本,并且给死请求补一个 <code>token 0</code> 占位保证 token 流形状一致。<code>SequenceStatus::FINISHED_SO_FAILED</code> 是独立的结束原因枚举(<code>sequence.hpp:39</code>),判死的 seq 在调度时直接进 <code>ignored_seqs</code>(<code>scheduler.hpp:364</code>)。</div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">5.2 采样热路径:_get_so_mask 的三重叠</h3>
    <p style="font-size:14px">sampler 的 <code>forward</code> 在 <b>logits 尚在 GPU 上计算时</b>就开始准备 SO 掩码(注释原文:「Start preparing the structured-output mask while logits are computed」,<code>sampler.py:135-138</code>),掩码就绪事件 <code>so_mask_ready</code> 在使用前 <code>wait_event</code>(<code>sampler.py:163-164</code>)——掩码准备与模型前向天然并行:</p>
    <div>
      <span class="filepath">deepinfer/model_executor/layers/sampler.py:135-138, 163-164, 318, 324-327</span>
      <pre class="code"><span class="c"># Start preparing the structured-output mask while logits are computed.</span>
driver_inputs = sampler_inputs.driver
<span class="k">if</span> driver_inputs <span class="k">is</span> <span class="k">not</span> <span class="k">None</span>:
    so_indices, so_bitmasks, so_status, so_mask_ready = self.<span class="f">_get_so_mask</span>(seq_metadata_list)
...
<span class="k">if</span> so_mask_ready <span class="k">is</span> <span class="k">not</span> <span class="k">None</span>:
    torch.cuda.<span class="f">current_stream</span>().<span class="f">wait_event</span>(so_mask_ready)
...
<span class="c"># _get_so_mask 内:</span>
<span class="k">if</span> <span class="f">all</span>(s.so_status &lt;= <span class="n">0</span> <span class="k">for</span> s <span class="k">in</span> seq_metadata_list):       <span class="c"># 全批无活跃 SO:零成本早退</span>
    <span class="k">return</span> <span class="k">None</span>, <span class="k">None</span>, <span class="k">None</span>, <span class="k">None</span>
...
<span class="c"># max_MTP_value + 1 个 pinned CPU 位掩码缓冲(当前位置 + 每 draft 步各一)</span>
self.bitmasks_cpu = [<span class="f">allocate_vocab_mask</span>(num_sampling_token, self.vocab_size, pin_memory=<span class="k">True</span>)
                    <span class="k">for</span> _ <span class="k">in</span> <span class="f">range</span>(self.max_MTP_value + <span class="n">1</span>)]</pre>
    </div>

    <p style="font-size:14px">每个请求的更新逻辑(节选,完整见 <code>sampler.py:332-389</code>)——注意「接受上轮 token」「为当前位填掩码」「为 draft 预填掩码后回滚」三个阶段:</p>
    <div>
      <span class="filepath">deepinfer/model_executor/layers/sampler.py:352-376(节选)</span>
      <pre class="code"><span class="k">if</span> so_status[idx] == <span class="n">2</span>:
    <span class="k">for</span> token <span class="k">in</span> seq_metadata.last_accepted_token + [seq_metadata.last_output_token]:
        <span class="k">if</span> <span class="k">not</span> matcher.<span class="f">accept_token</span>(token):
            <span class="k">raise</span> <span class="f">RuntimeError</span>(<span class="s">f"matcher rejected step token {token}, upstream invariant broken"</span>)  <span class="c"># ← 不变量校验</span>
<span class="k">elif</span> so_status[idx] == <span class="n">1</span>:
    so_status[idx] = <span class="n">2</span>                     <span class="c"># 交界步:只切换状态,不喂 prompt token</span>

<span class="k">if</span> matcher.<span class="f">constrained</span>():
    mask_filled = matcher.<span class="f">fill_vocab_mask</span>(self.bitmasks_cpu[<span class="n">0</span>], idx)   <span class="c"># 当前位置的掩码</span>
    so_indices_cpu[<span class="n">0</span>].<span class="f">append</span>(idx)

num_accepted_steps = <span class="n">0</span>
<span class="k">for</span> k, draft_token <span class="k">in</span> <span class="f">enumerate</span>(seq_metadata.last_next_n_token):          <span class="c"># 上一轮的 draft 序列</span>
    <span class="k">if</span> matcher.<span class="f">accept_token</span>(draft_token):                                <span class="c"># 试接受:合法才为该 draft 位准备掩码</span>
        <span class="k">if</span> matcher.<span class="f">constrained</span>():
            mask_filled = matcher.<span class="f">fill_vocab_mask</span>(self.bitmasks_cpu[k + <span class="n">1</span>], idx)
            so_indices_cpu[k + <span class="n">1</span>].<span class="f">append</span>(idx)
        num_accepted_steps += <span class="n">1</span>
    <span class="k">else</span>:
        <span class="k">break</span>                                                                  <span class="c"># draft 违反文法:后面无需再看</span>
matcher.<span class="f">rollback</span>(num_accepted_steps)                                        <span class="c"># 回滚:matcher 停在「当前已确认」状态</span></pre>
    </div>

    <div class="figure reveal">
      <svg viewBox="0 0 1160 560" xmlns="http://www.w3.org/2000/svg" font-family="'PingFang SC','Microsoft YaHei',sans-serif">
        <defs>
          <marker id="arw8" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
            <path d="M0,0 L9,4.5 L0,9 z" fill="#22d3ee"/>
          </marker>
          <marker id="arw9" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
            <path d="M0,0 L9,4.5 L0,9 z" fill="#fbbf24"/>
          </marker>
        </defs>

        <text x="20" y="28" fill="#8ea0c2" font-size="13" font-weight="700">一个 decode step 内的 SO × MTP 协作(以 nextn=5,上轮 draft=[t1,t2,t3] 为例)</text>

        <!-- matcher loop -->
        <rect x="20" y="52" width="310" height="380" rx="14" fill="rgba(79,140,255,.05)" stroke="#263352"/>
        <text x="175" y="78" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">XGrammarMatcher(采样器主线程内顺序执行)</text>

        <g>
          <rect x="45" y="96" width="260" height="66" rx="10" fill="#16233f" stroke="#22d3ee" stroke-width="1.4"/>
          <text x="175" y="118" text-anchor="middle" fill="#fff" font-size="12" font-weight="700">1 · 接受上轮确认 token</text>
          <text x="175" y="136" text-anchor="middle" fill="#8ea0c2" font-size="10.5">accepted_tokens + [last_output_token]</text>
          <text x="175" y="152" text-anchor="middle" fill="#5d7294" font-size="9.5">reject → "upstream invariant broken" → 判死 sampler.py:353-355</text>
        </g>
        <path class="flowline" d="M175,162 V178" stroke="#22d3ee" stroke-width="2" marker-end="url(#arw8)"/>
        <circle r="4" fill="#22d3ee" class="barrow"><animateMotion dur="2.8s" repeatCount="indefinite" path="M175,162 V178"/></circle>

        <g>
          <rect x="45" y="178" width="260" height="66" rx="10" fill="#16233f" stroke="#22d3ee" stroke-width="1.4"/>
          <text x="175" y="200" text-anchor="middle" fill="#fff" font-size="12" font-weight="700">2 · fill mask[0](当前位置)</text>
          <text x="175" y="218" text-anchor="middle" fill="#8ea0c2" font-size="10.5">下一 token 的合法集合 → bitmask[0][idx]</text>
          <text x="175" y="234" text-anchor="middle" fill="#5d7294" font-size="9.5">matcher.py:181-204 · sampler.py:361-364</text>
        </g>
        <path class="flowline" d="M175,244 V260" stroke="#22d3ee" stroke-width="2" marker-end="url(#arw8)"/>
        <circle r="4" fill="#22d3ee" class="barrow"><animateMotion dur="2.8s" begin=".5s" repeatCount="indefinite" path="M175,244 V260"/></circle>

        <g>
          <rect x="45" y="260" width="260" height="76" rx="10" fill="#16233f" stroke="#22d3ee" stroke-width="1.4"/>
          <text x="175" y="282" text-anchor="middle" fill="#fff" font-size="12" font-weight="700">3 · 逐个试接受 draft,填 mask[k+1]</text>
          <text x="175" y="300" text-anchor="middle" fill="#8ea0c2" font-size="10.5">t1 ✓ → mask[1] · t2 ✓ → mask[2] · t3 ✗ → break</text>
          <text x="175" y="316" text-anchor="middle" fill="#8ea0c2" font-size="10.5">draft 违反文法:该 draft 必然被掩码拒绝</text>
          <text x="175" y="330" text-anchor="middle" fill="#5d7294" font-size="9.5">sampler.py:367-375</text>
        </g>
        <path class="flowline" d="M175,336 V352" stroke="#22d3ee" stroke-width="2" marker-end="url(#arw8)"/>
        <circle r="4" fill="#22d3ee" class="barrow"><animateMotion dur="2.8s" begin="1s" repeatCount="indefinite" path="M175,336 V352"/></circle>

        <g>
          <rect x="45" y="352" width="260" height="62" rx="10" fill="#16233f" stroke="#a78bfa" stroke-width="1.4"/>
          <text x="175" y="374" text-anchor="middle" fill="#fff" font-size="12" font-weight="700">4 · rollback(num_accepted_steps=2)</text>
          <text x="175" y="392" text-anchor="middle" fill="#8ea0c2" font-size="10.5">自动机回到「当前确认」状态;draft 只是试探</text>
          <text x="175" y="406" text-anchor="middle" fill="#5d7294" font-size="9.5">matcher.py:206-232 · sampler.py:376</text>
        </g>

        <!-- bitmask buffers -->
        <text x="370" y="70" fill="#fff" font-size="13" font-weight="700">位掩码缓冲(max_MTP_value + 1 个,pinned)</text>
        <g>
          <rect x="370" y="86" width="230" height="34" rx="7" fill="#0d1424" stroke="#22d3ee" stroke-width="1.3"/>
          <text x="382" y="108" fill="#22d3ee" font-size="11" font-family="Consolas,monospace">bitmask[0] ← 当前位置</text>
          <rect x="560" y="93" width="9" height="20" fill="#22d3ee" opacity=".9"><animate attributeName="opacity" values=".2;1;.2" dur="1.8s" repeatCount="indefinite"/></rect>
          <rect x="571" y="93" width="9" height="20" fill="#263352"/><rect x="582" y="93" width="9" height="20" fill="#22d3ee" opacity=".55"><animate attributeName="opacity" values=".55;1;.55" dur="1.8s" begin=".4s" repeatCount="indefinite"/></rect>
        </g>
        <g>
          <rect x="370" y="128" width="230" height="34" rx="7" fill="#0d1424" stroke="#22d3ee" stroke-width="1.3"/>
          <text x="382" y="150" fill="#22d3ee" font-size="11" font-family="Consolas,monospace">bitmask[1] ← draft 步 1</text>
          <rect x="560" y="135" width="9" height="20" fill="#22d3ee" opacity=".7"><animate attributeName="opacity" values=".3;1;.3" dur="1.8s" begin=".6s" repeatCount="indefinite"/></rect>
          <rect x="571" y="135" width="9" height="20" fill="#263352"/><rect x="582" y="135" width="9" height="20" fill="#263352"/>
        </g>
        <g>
          <rect x="370" y="170" width="230" height="34" rx="7" fill="#0d1424" stroke="#22d3ee" stroke-width="1.3"/>
          <text x="382" y="192" fill="#22d3ee" font-size="11" font-family="Consolas,monospace">bitmask[2] ← draft 步 2</text>
          <rect x="560" y="177" width="9" height="20" fill="#22d3ee" opacity=".7"><animate attributeName="opacity" values=".3;1;.3" dur="1.8s" begin=".9s" repeatCount="indefinite"/></rect>
          <rect x="571" y="177" width="9" height="20" fill="#263352"/><rect x="582" y="177" width="9" height="20" fill="#263352"/>
        </g>
        <g>
          <rect x="370" y="212" width="230" height="34" rx="7" fill="#0d1424" stroke="#263352" stroke-width="1.2" stroke-dasharray="4 4"/>
          <text x="382" y="234" fill="#5d7294" font-size="11" font-family="Consolas,monospace">bitmask[3..5] ← t3 起未填</text>
        </g>
        <path class="flowline" d="M305,211 H370" stroke="#22d3ee" stroke-width="2" marker-end="url(#arw8)"/>
        <path class="flowline" d="M305,298 C340,298 340,145 370,145" stroke="#22d3ee" stroke-width="1.6" fill="none" marker-end="url(#arw8)"/>
        <path class="flowline" d="M305,298 C345,298 345,187 370,187" stroke="#22d3ee" stroke-width="1.6" fill="none" marker-end="url(#arw8)"/>

        <!-- H2D -->
        <g>
          <rect x="370" y="270" width="230" height="62" rx="10" fill="#16233f" stroke="#a78bfa" stroke-width="1.4"/>
          <text x="485" y="292" text-anchor="middle" fill="#fff" font-size="12" font-weight="700">so_copy_stream 侧流 H2D</text>
          <text x="485" y="310" text-anchor="middle" fill="#8ea0c2" font-size="10.5">pinned → cuda(non_blocking) → so_mask_ready</text>
          <text x="485" y="325" text-anchor="middle" fill="#5d7294" font-size="9.5">sampler.py:391-407</text>
        </g>
        <path class="flowline" d="M600,145 C640,145 640,200 660,200" stroke="#22d3ee" stroke-width="2" fill="none" marker-end="url(#arw8)"/>
        <path class="flowline" d="M600,301 C630,301 630,330 660,330" stroke="#a78bfa" stroke-width="2" fill="none" marker-end="url(#arw8)"/>
        <circle r="4.5" fill="#a78bfa" class="barrow"><animateMotion dur="2s" repeatCount="indefinite" path="M600,301 C630,301 630,330 660,330"/></circle>

        <!-- logits matrix -->
        <g>
          <rect x="660" y="86" width="300" height="290" rx="12" fill="#0d1424" stroke="#263352"/>
          <text x="810" y="110" text-anchor="middle" fill="#fff" font-size="12.5" font-weight="700">logits [total_q × 129280](fp32)</text>
          <text x="810" y="126" text-anchor="middle" fill="#8ea0c2" font-size="10">请求 i 的打包行:ftp[i] 起,step 偏移寻址</text>
          <!-- rows -->
          <g font-family="Consolas,monospace" font-size="10.5">
            <rect x="680" y="140" width="240" height="26" rx="5" fill="#16233f" stroke="#22d3ee" stroke-width="1"/>
            <text x="690" y="157" fill="#22d3ee">row ftp[i]+0 · 当前位置(mask[0])</text>
            <rect x="680" y="172" width="240" height="26" rx="5" fill="#16233f" stroke="#22d3ee" stroke-width="1" stroke-dasharray="4 3"/>
            <text x="690" y="189" fill="#22d3ee" opacity=".85">row ftp[i]+1 · draft t1(mask[1])</text>
            <rect x="680" y="204" width="240" height="26" rx="5" fill="#16233f" stroke="#22d3ee" stroke-width="1" stroke-dasharray="4 3"/>
            <text x="690" y="221" fill="#22d3ee" opacity=".85">row ftp[i]+2 · draft t2(mask[2])</text>
            <rect x="680" y="236" width="240" height="26" rx="5" fill="#16233f" stroke="#263352"/>
            <text x="690" y="253" fill="#5d7294">row ftp[i]+3 · draft t3(未掩码,将被拒绝)</text>
          </g>
          <!-- -inf cells -->
          <rect x="700" y="142" width="16" height="22" fill="#f87171" opacity=".75"><animate attributeName="opacity" values=".15;.8;.15" dur="1.6s" repeatCount="indefinite"/></rect>
          <rect x="736" y="174" width="16" height="22" fill="#f87171" opacity=".6"><animate attributeName="opacity" values=".15;.8;.15" dur="1.6s" begin=".4s" repeatCount="indefinite"/></rect>
          <rect x="754" y="206" width="16" height="22" fill="#f87171" opacity=".6"><animate attributeName="opacity" values=".15;.8;.15" dur="1.6s" begin=".8s" repeatCount="indefinite"/></rect>
          <text x="810" y="286" text-anchor="middle" fill="#f87171" font-size="10.5">非法位 → -inf(红格闪烁)</text>
          <text x="810" y="304" text-anchor="middle" fill="#8ea0c2" font-size="9.5">apply_token_bitmask_by_step_inplace(logits, bitmask[step],</text>
          <text x="810" y="318" text-anchor="middle" fill="#8ea0c2" font-size="9.5">indices, ftp, step) · sampler.py:433-437</text>
          <text x="810" y="352" text-anchor="middle" fill="#34d399" font-size="10.5">掩码先于 process_sampling:top-k/top-p 看到的已是裁剪后分布</text>
        </g>

        <!-- bottom: verification & writeback -->
        <g>
          <rect x="660" y="400" width="300" height="76" rx="10" fill="#16233f" stroke="#34d399" stroke-width="1.5"/>
          <text x="810" y="424" text-anchor="middle" fill="#fff" font-size="12" font-weight="700">采样 & MTP 验证</text>
          <text x="810" y="442" text-anchor="middle" fill="#8ea0c2" font-size="10.5">t1、t2 依概率接受;t3 在掩码分布下大概率出局</text>
          <text x="810" y="458" text-anchor="middle" fill="#5d7294" font-size="9.5">sampler.py:439-457 process_sampling</text>
        </g>
        <path class="flowline" d="M810,376 V400" stroke="#34d399" stroke-width="2" marker-end="url(#arw8)"/>
        <circle r="4" fill="#34d399" class="barrow"><animateMotion dur="2s" begin=".7s" repeatCount="indefinite" path="M810,376 V400"/></circle>

        <g>
          <rect x="1000" y="400" width="140" height="76" rx="10" fill="#16233f" stroke="#fbbf24" stroke-width="1.4"/>
          <text x="1070" y="424" text-anchor="middle" fill="#fff" font-size="12" font-weight="700">processOutputs 回写</text>
          <text x="1070" y="442" text-anchor="middle" fill="#8ea0c2" font-size="10">accepted_tokens /</text>
          <text x="1070" y="456" text-anchor="middle" fill="#8ea0c2" font-size="10">last_output_token / status</text>
          <text x="1070" y="470" text-anchor="middle" fill="#5d7294" font-size="9">scheduler.hpp:928-970</text>
        </g>
        <path class="flowline" d="M960,438 H1000" stroke="#fbbf24" stroke-width="2" marker-end="url(#arw9)"/>

        <!-- loop back -->
        <path class="flowline" d="M1070,476 V516 H175 V432" stroke="#fbbf24" stroke-width="2" fill="none" marker-end="url(#arw9)" stroke-dasharray="4 6"/>
        <circle r="4" fill="#fbbf24" class="barrow"><animateMotion dur="3.4s" repeatCount="indefinite" path="M1070,476 V516 H175 V432"/></circle>
        <text x="620" y="510" text-anchor="middle" fill="#fbbf24" font-size="11">下一 decode step:账本驱动,继续「接受 → 掩码 → 试探 → 回滚」循环</text>
      </svg>
      <div class="cap">图 5-2 · SO 与 DSpark(MTP)投机解码:matcher 先确认上轮已接受 token,为当前位置与每个合法 draft 位预填掩码,再整体回滚;GPU 侧按 step 偏移把各 draft 行的非法 logits 置 -inf,使「违反文法的 draft」在验证时几乎必然出局,而合法 draft 的接受概率分布不被扭曲。</div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">5.3 侧流 H2D 与事件同步</h3>
    <p style="font-size:14px">位掩码在 CPU 上由 xgrammar 填写(pinned 内存),需要异步搬到 GPU。DeepInfer 用独立的 <code>so_copy_stream</code> 侧流执行 H2D,并用两个 CUDA event 严格定序:先 record <code>copy_after</code>(消费者流)确保 CPU 写完成对拷贝可见,拷贝完 record <code>so_mask_ready</code>,主采样流 <code>wait_event</code> 后才允许内核读掩码;所有张量再 <code>record_stream</code> 防止内存池提前回收:</p>
    <div>
      <span class="filepath">deepinfer/model_executor/layers/sampler.py:391-407</span>
      <pre class="code">consumer_stream = torch.cuda.<span class="f">current_stream</span>()
copy_after = torch.cuda.<span class="f">Event</span>()
copy_after.<span class="f">record</span>(consumer_stream)
<span class="k">if</span> self.so_copy_stream <span class="k">is</span> <span class="k">None</span>:
    self.so_copy_stream = torch.cuda.<span class="f">Stream</span>()
<span class="k">with</span> torch.cuda.<span class="f">stream</span>(self.so_copy_stream):
    self.so_copy_stream.<span class="f">wait_event</span>(copy_after)
    so_bitmasks = [m.<span class="f">cuda</span>(non_blocking=<span class="k">True</span>) <span class="k">for</span> m <span class="k">in</span> self.bitmasks_cpu]      <span class="c"># pinned → DMA</span>
    so_indices = [torch.<span class="f">tensor</span>(indices, dtype=torch.int32, device=<span class="s">"cpu"</span>, pin_memory=<span class="k">True</span>).<span class="f">cuda</span>(non_blocking=<span class="k">True</span>)
                  <span class="k">for</span> indices <span class="k">in</span> so_indices_cpu]
    so_mask_ready = torch.cuda.<span class="f">Event</span>()
    so_mask_ready.<span class="f">record</span>(self.so_copy_stream)

<span class="k">for</span> tensor <span class="k">in</span> [*so_bitmasks, *so_indices]:
    tensor.<span class="f">record_stream</span>(consumer_stream)</pre>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">5.4 golden tokens 与 trigger 的冲突校验</h3>
    <p style="font-size:14px"><code>SamplingParams</code> 还能携带 <code>golden_token_ids</code>(<code>sampling_params.py:60</code>)强制指定输出——用于评测对齐 / teacher forcing。SO 与之叠加时顺序是:<b>先掩码、后 golden 覆盖</b>。golden 令牌绕过掩码直接替换采样结果(<code>_prefill_golden_gen</code> / <code>_update_golden_tokens</code>,<code>sampler.py:597-683</code>;decode 侧在 <code>get_accept_result</code> 内合并,<code>sampler.py:470-480</code>),但<strong>逃不过自动机</strong>:下一个 step 的 <code>update_so_status</code> 会把被强制输出的 token 交给 <code>accept_token</code>,文法不容即抛「upstream invariant broken」并判死该请求(<code>sampler.py:352-355</code>)。换句话说,冲突不是悄悄吞掉,而是以单请求失败的形式显式暴露。</p>
    <ul class="feat reveal">
      <li><b>trigger 的校验</b>在两个层面:<code>validate_trigger_bound</code>(<code>matcher.py:48-55</code>)做静态校验(token id 非负整数列表、bound 搭配非空 trigger,违者直接以 aborted_matcher 结束请求,<code>so_matcher_builder.py:71-76</code>);运行期 KMP 匹配状态可被 <code>rollback</code> 按 <code>_progress_history</code> 恢复,回滚超过保留历史(上限 7)则抛 RuntimeError(<code>matcher.py:223-230</code>)。</li>
      <li><b>词表校验</b>:matcher 掩码尺寸 = 引擎真实词表(<code>from_compiled</code> 用 <code>vocab_size</code> 构造全 1 的 <code>mask_after_eos</code>,<code>matcher.py:105</code>);TileLang 内核断言 logits 词表不小于掩码词表(<code>structure_output.py:31-35</code>);引擎侧 prompt token 合法性另有独立闸(<code>llm_engine.py:580-590</code>)。</li>
    </ul>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">5.5 故障隔离:不让 SO 的 bug 连坐整个引擎</h3>
    <p style="font-size:14px"><code>update_so_status</code> 的异常处理是全文件最有「生产味」的注释——CP rank 0 的采样主路径上,一个 raise 会连坐所有请求并导致 NCCL barrier 超时:</p>
    <div>
      <span class="filepath">deepinfer/model_executor/layers/sampler.py:377-386(节选)</span>
      <pre class="code"><span class="k">except</span> <span class="f">Exception</span>:
    <span class="c"># 此处在 CP rank 0 采样主路径,raise 会连坐所有请求 + NCCL barrier 超时;</span>
    <span class="c"># SO 的 bug 只判死本请求,不带崩 engine。</span>
    logger.<span class="f">exception</span>(<span class="s">"[SO] matcher failed during update_so_status, killing request %s (so_status=%d)"</span>, ...)
    matcher.<span class="f">set_aborted</span>(<span class="s">"SO matcher runtime failure in update_so_status"</span>)
    so_status[idx] = -<span class="n">1</span></pre>
    </div>
    <p style="font-size:14px">同类防御还出现在:matcher 为 None(<code>sampler.py:342-345</code>,warning + 判死)、最后 prefill chunk 账本异常(<code>llm_engine.py:917-928</code>,注释解释为什么必须当步判死而不是只置 -1——sampler 快路径可能吞掉 -1)、以及编译超时(4.2 节)。<code>so_status=-1</code> 一路回写到 C++ 账本后,<code>processOutputs</code> 给请求补 <code>token 0</code> 并置 <code>FINISHED_SO_FAILED</code>(<code>scheduler.hpp:977-981</code>),调用方拿到明确的失败原因。</p>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">5.6 调度交互:抢占不支持重算、fork 复制 matcher</h3>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">✂️</span>被抢占 = 直接结束</h3>
        <p>普通请求被抢占可以回炉重算(<code>reset_for_recompute</code> 后放回 waiting),但 matcher 的自动机状态无法廉价地随 KV 回退重建——<code>_preempt</code> 里只要 <code>structured_output.status != 0</code> 就直接判 <code>FINISHED_PREEMPTED</code> 并告警「structured output (so_status {}) can not be recomputed」(<code>scheduler.hpp:770-776</code>)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧬</span>fork:前缀复用 + matcher 克隆</h3>
        <p><code>fork_seq</code> 用缓存前缀派生新序列时,把父请求的 <code>so_matcher</code> 交给 <code>copy_without_status()</code> 克隆(<code>matcher.py:234-243</code>;status 由「prompt 是否算完」重推:<code>so_matcher.is_none() || prompt_incomplete ? 0 : 1</code>,<code>scheduler.hpp:1097-1099</code>)。<code>examples/benchmark.py:342</code> 正是传 <code>source_seq.so_matcher</code> 批量 fork 出整批同约束请求。</p>
      </div>
    </div>
    <p style="font-size:14px">另有一处精妙的「prompt 不进自动机」设计:<code>Sequence</code> 构造时把 <code>mtp.last_output_token</code> 初始化为<b>prompt 的最后一个 token</b>(<code>sequence.hpp:282</code>),于是最后 prefill chunk 采样时 <code>last_output_token != -1</code>,sampler 才会进入 SO 分支填首个掩码;而 chunked prefill 的非最后 chunk 被显式置 -1(<code>sequence.hpp:386-388</code>),sampler 以此跳过 SO 更新(<code>sampler.py:339</code>)。prompt token 本身永远不被 <code>accept_token</code>——文法只约束生成部分。</p>
  </section>

  <!-- ================= 6. 使用示例 ================= -->
  <section id="s6">
    <h2 class="sec"><span class="num">6</span>使用示例:examples/_structured_output.py</h2>
    <p class="lede">这是仓库对外的官方 SO 示例,也是回归测试:三个用例分别覆盖 regex / json / ebnf,prompt 故意「诱导」模型跑偏,用断言证明约束真的生效。</p>

    <div>
      <span class="filepath">examples/_structured_output.py:11-64(完整)</span>
      <pre class="code"><span class="k">def</span> <span class="f">run_structured_output</span>(llm: LLM, dp_rank: <span class="k">int</span>) -&gt; <span class="k">None</span>:
    <span class="k">from</span> deepinfer.sampling_params <span class="k">import</span> SamplingParams

    json_schema = {
        <span class="s">"type"</span>: <span class="s">"object"</span>,
        <span class="s">"properties"</span>: {
            <span class="s">"color"</span>: {<span class="s">"type"</span>: <span class="s">"string"</span>, <span class="s">"enum"</span>: [<span class="s">"red"</span>, <span class="s">"green"</span>, <span class="s">"blue"</span>]},
            <span class="s">"count"</span>: {<span class="s">"type"</span>: <span class="s">"integer"</span>, <span class="s">"enum"</span>: [<span class="n">1</span>, <span class="n">2</span>, <span class="n">3</span>]},
        },
        <span class="s">"required"</span>: [<span class="s">"color"</span>, <span class="s">"count"</span>],
        <span class="s">"additionalProperties"</span>: <span class="k">False</span>,
    }
    cases = [
        (
            <span class="s">"一只会唱歌的冰箱飞到了月亮上。请随便续写一个很长的故事,不要写编号。"</span>,          <span class="c"># ← 诱导写故事</span>
            {<span class="s">"schema_type"</span>: <span class="s">"regex"</span>, <span class="s">"schema"</span>: <span class="k">r</span><span class="s">"[A-Z]{2}-[0-9]{3}"</span>},  <span class="c"># ← 却只能输出 AB-123 形式</span>
        ),
        (
            <span class="s">"火星上的面条为什么会跳舞?请用自然语言胡思乱想,不要输出 JSON 或代码。"</span>,        <span class="c"># ← 明令禁止 JSON</span>
            {<span class="s">"schema_type"</span>: <span class="s">"json"</span>, <span class="s">"schema"</span>: json.<span class="f">dumps</span>(json_schema)},
        ),
        (
            <span class="s">"请写一首关于紫色拖鞋和时间旅行的长诗,不要用英文,也不要给出简短答案。"</span>,        <span class="c"># ← 诱导写长诗</span>
            {<span class="s">"schema_type"</span>: <span class="s">"ebnf"</span>, <span class="s">"schema"</span>: <span class="s">'root ::= "answer=" ("yes" | "no") ";level=" [1-3]'</span>},
        ),
    ]
    outputs = llm.<span class="f">generate</span>(
        prompts=[prompt <span class="k">for</span> prompt, _ <span class="k">in</span> cases],
        sampling_params=[<span class="f">SamplingParams</span>(temperature=<span class="n">0</span>, max_tokens=<span class="n">128</span>, so_args=so_args) <span class="k">for</span> _, so_args <span class="k">in</span> cases],
        use_tqdm=<span class="k">False</span>,
    )
    <span class="k">assert</span> <span class="f">len</span>(outputs) == <span class="f">len</span>(cases), <span class="s">f"Expected {len(cases)} SO results, got {len(outputs)}"</span>
    <span class="k">for</span> (_, so_args), output <span class="k">in</span> <span class="f">zip</span>(cases, outputs, strict=<span class="k">True</span>):
        schema_type = so_args[<span class="s">"schema_type"</span>]
        <span class="k">assert</span> output, <span class="s">f"{schema_type}: missing output"</span>
        last = output[-<span class="n">1</span>]
        <span class="k">assert</span> last.finished <span class="k">and</span> last.finish_reason == <span class="s">"stop"</span>, <span class="s">f"{schema_type}: {last.finish_reason}"</span>
        <span class="k">assert</span> last.token_id == llm.llm_engine.eos_id, <span class="s">f"{schema_type}: missing final EOS"</span>   <span class="c"># 文法允许停止时才出 EOS</span>
        text = llm.<span class="f">get_tokenizer</span>().<span class="f">decode</span>(
            [token.token_id <span class="k">for</span> token <span class="k">in</span> output[:-<span class="n">1</span>]],
            skip_special_tokens=<span class="k">False</span>, clean_up_tokenization_spaces=<span class="k">False</span>,
        )
        <span class="k">if</span> schema_type == <span class="s">"regex"</span>:
            <span class="k">assert</span> <span class="f">re</span>.<span class="f">fullmatch</span>(so_args[<span class="s">"schema"</span>], text), <span class="s">f"regex: {text!r}"</span>
        <span class="k">elif</span> schema_type == <span class="s">"json"</span>:
            value = json.<span class="f">loads</span>(text)
            <span class="k">assert</span> <span class="f">isinstance</span>(value, dict) <span class="k">and</span> <span class="f">set</span>(value) == {<span class="s">"color"</span>, <span class="s">"count"</span>}, <span class="s">f"json: {text!r}"</span>
            <span class="k">assert</span> value[<span class="s">"color"</span>] <span class="k">in</span> {<span class="s">"red"</span>, <span class="s">"green"</span>, <span class="s">"blue"</span>}, <span class="s">f"json: {text!r}"</span>
            <span class="k">assert</span> <span class="k">type</span>(value[<span class="s">"count"</span>]) <span class="k">is</span> <span class="k">int</span> <span class="k">and</span> value[<span class="s">"count"</span>] <span class="k">in</span> {<span class="n">1</span>, <span class="n">2</span>, <span class="n">3</span>}, <span class="s">f"json: {text!r}"</span>
        <span class="k">else</span>:
            <span class="k">assert</span> schema_type == <span class="s">"ebnf"</span>
            <span class="k">assert</span> <span class="f">re</span>.<span class="f">fullmatch</span>(<span class="k">r</span><span class="s">"answer=(yes|no);level=[1-3]"</span>, text), <span class="s">f"ebnf: {text!r}"</span>
        <span class="f">print</span>(<span class="s">f"DP {dp_rank}; SO {schema_type}: {text!r}"</span>, flush=<span class="k">True</span>)</pre>
    </div>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🧪</span>示例要点逐条</h3>
        <ul class="feat">
          <li>三个 prompt 全部与约束<strong>背道而驰</strong>(求故事 / 禁 JSON / 求长诗)——证明约束来自引擎而非模型「听话」</li>
          <li><code>temperature=0</code>:即便贪心解码,无约束时模型也几乎必然跑偏;有约束时输出唯一合法</li>
          <li>结束断言:<code>finish_reason == "stop"</code> 且末 token 恰为 <code>llm.llm_engine.eos_id</code>——SO 请求以文法允许的 EOS 正常收尾,而非 <code>FINISHED_SO_FAILED</code> / 长度截断</li>
          <li>regex 断言用 <code>re.fullmatch</code>(全串匹配),与 xgrammar <code>compile_regex</code> 的语义一致</li>
        </ul>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🔌</span>入口与测试接线</h3>
        <ul class="feat">
          <li><code>offline_inference.py</code> 提供 <code>--check_structured_output</code> 开关,在同一 LLM 实例完成 PPL 评测后调用 <code>run_structured_output</code>(<code>offline_inference.py:20, 104-107</code>)</li>
          <li><code>examples/README.md:13</code>:该开关跑 regex / JSON / EBNF 三项校验并验证正常 EOS 终止,任何失败都会让整个 run 失败</li>
          <li><code>tests/models/test_offline_inference.py:164</code> 在默认模型的离线推理测试中显式开启,单次运行同时验证 PPL 与结构化输出</li>
        </ul>
      </div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">6.1 benchmark 中的 SO:异步等待与批量 fork</h3>
    <p style="font-size:14px"><code>examples/benchmark.py</code> 展示了两个引擎级用法:①自己管理调度(<code>enqueue=False</code> 路径)时,必须手动泵 pending 直到编译完成再分配;②fork 一批同 schema 请求时把父 matcher 传下去:</p>
    <div>
      <span class="filepath">examples/benchmark.py:280, 311-313, 337-351(节选)</span>
      <pre class="code">sampling_kwargs = <span class="f">dict</span>(
    ...,
    so_args={<span class="s">"schema_type"</span>: <span class="s">"regex"</span>, <span class="s">"schema"</span>: <span class="k">r</span><span class="s">"Hello, my name is [a-z]+"</span>} <span class="k">if</span> args.enable_so <span class="k">else</span> <span class="k">None</span>,
)
...
<span class="c"># 等待异步 SO 编译完成,确保所有 SO seq 已 add_sequence 后再分配</span>
<span class="k">while</span> llm.llm_engine.<span class="f">so_builder_has_pending</span>():
    llm.llm_engine.so_matcher_builder.<span class="f">pump</span>()
...
fork_seq = scheduler.<span class="f">fork_seq</span>(
    source_seq, <span class="k">None</span>, f<span class="s">"_benchmark_fork_{fork_index}"</span>, params_for_request(fork_index),
    source_seq.so_matcher,        <span class="c"># ← 父请求的 matcher,clone 后给 fork 复用</span>
    golden_token_id, -<span class="n">1</span>, <span class="f">next</span>(llm.llm_engine.seq_counter), time.<span class="f">monotonic</span>(),
)</pre>
    </div>
  </section>

  <!-- ================= 7. 配置项参考 ================= -->
  <section id="s7">
    <h2 class="sec"><span class="num">7</span>配置项参考</h2>
    <p class="lede">SO 的全部开关集中在 <code>deepinfer/environ.py:173-178</code> 的「Structured Output」段(非 data descriptor,首次访问时从环境变量解析并缓存,<code>environ.py:38-53</code>)。</p>

    <table class="tbl reveal">
      <tr><th>环境变量</th><th>默认值</th><th>作用</th><th>消费点(file:line)</th></tr>
      <tr>
        <td><code>DEEPINFER_XGRAMMAR_DEBUG</code></td>
        <td>false</td>
        <td>打开 xgrammar matcher 的 debug_print:每次 accept / fill 掩码打印自动机内部状态、特殊 token 拒绝日志、停止后掩码提示</td>
        <td><code>matcher.py:18, 158, 173, 193, 198</code></td>
      </tr>
      <tr>
        <td><code>DEEPINFER_XGRAMMAR_TIMEOUT</code></td>
        <td>20(秒)</td>
        <td>编译 future 的超时死线,自提交(<code>XGrammarMatcherFuture</code> 构造)时刻起算;越窗产出 aborted_matcher,请求判 FINISHED_SO_FAILED,后台线程跑完即弃</td>
        <td><code>matcher.py:19, 265-269, 305-310, 332-335</code></td>
      </tr>
      <tr>
        <td><code>DEEPINFER_XGRAMMAR_DISABLE_CACHE</code></td>
        <td>false</td>
        <td>编译缓存 kill switch(xgrammar ≤ 0.1.x 开缓存曾出生产事故);开启后每次全量编译</td>
        <td><code>compiler.py:18, 21-22, 37</code></td>
      </tr>
      <tr>
        <td><code>DEEPINFER_XGRAMMAR_CACHE_LIMIT_BYTES</code></td>
        <td>10 GiB<br>(10*1024^3)</td>
        <td>编译缓存字节上限;设为 ≤0 表示无上限,启动时大声告警 OOM/DoS 风险(引用 CVE-2025-32381)</td>
        <td><code>compiler.py:19, 23-29, 38</code></td>
      </tr>
      <tr>
        <td><code>DEEPINFER_SO_BUILDER_CPUS</code></td>
        <td>4</td>
        <td>每个 GPU 为 SO 编译线程池预留(并绑核)的物理 CPU 数;配额不足时 <code>get_idle_cpus</code> 直接 raise。同时决定 <code>max_workers</code></td>
        <td><code>utils.py:154-161</code> → <code>llm_engine.py:334-341</code></td>
      </tr>
      <tr>
        <td><code>DEEPINFER_USE_NEXTN_DECODE</code></td>
        <td>5</td>
        <td>(间接)决定 matcher 回滚容量 <code>MAX_ROLLBACK_TOKENS = 该值 + 2</code> 与掩码缓冲数量 <code>max_MTP_value + 1</code></td>
        <td><code>environ.py:136</code> → <code>matcher.py:20</code> / <code>sampler.py:326</code></td>
      </tr>
    </table>

    <table class="tbl reveal">
      <tr><th colspan="4">so_args 字典字段(用户接口)</th></tr>
      <tr><th>键</th><th>必填</th><th>取值 / 语义</th><th>校验位置</th></tr>
      <tr><td><code>"schema_type"</code></td><td>是</td><td><code>"regex"</code> / <code>"json"</code> / <code>"ebnf"</code>,其他值抛「Unsupported Grammar Type」</td><td><code>compiler.py:56-63</code></td></tr>
      <tr><td><code>"schema"</code></td><td>是</td><td>regex 正则串 / JSON Schema 的 JSON 字符串 / EBNF 文法串</td><td>由 xgrammar 编译期校验</td></tr>
      <tr><td><code>"trigger_token_ids"</code></td><td>否</td><td>list[int]:完整出现前自由生成;KMP 流式匹配;须非负整数</td><td><code>matcher.py:48-55, 140-148</code></td></tr>
      <tr><td><code>"bound_token_id"</code></td><td>否</td><td>非负整数(0 有效):出现后强制逐 token 走完 trigger 再进文法;须搭配非空 trigger</td><td><code>matcher.py:51-55, 136-139, 183-187</code></td></tr>
      <tr><td><code>"serialized"</code></td><td>—</td><td><span class="badge closed">显式拒绝</span> 离线场景不接受序列化文法</td><td><code>so_matcher_builder.py:60-61</code></td></tr>
      <tr><td><code>"bound_token_ids"</code></td><td>—</td><td><span class="badge closed">显式拒绝</span> 旧复数形式已废弃</td><td><code>so_matcher_builder.py:62-63</code></td></tr>
    </table>

    <table class="tbl reveal">
      <tr><th colspan="3">so_status 状态码(账本语义,csrc/engine/sequence.hpp:232 注释)</th></tr>
      <tr><th>值</th><th>含义</th><th>迁移点</th></tr>
      <tr><td><code>0</code></td><td>未开始:prompt 未算完 / matcher 未就绪</td><td>构造默认;非最后 prefill chunk 保持(chunked prefill 下 sampler 以 <code>last_output_token == -1</code> 跳过,<code>sequence.hpp:386-388</code>)</td></tr>
      <tr><td><code>1</code></td><td>刚开始(交界处):最后 prefill chunk 的采样步,首个生成 token 即被掩码</td><td><code>llm_engine.py:913-915</code>(调度后、采样前置位)</td></tr>
      <tr><td><code>2</code></td><td>已开始:每个 decode step 接受上轮 token 并填掩码</td><td><code>sampler.py:356-357</code>(sampler 首次处理时 1→2)</td></tr>
      <tr><td><code>-1</code></td><td>aborted:编译超时 / 运行时错误 / 不变量破坏 → FINISHED_SO_FAILED</td><td><code>sampler.py:347-350, 377-386</code> → 回写 <code>scheduler.hpp:928-929</code> → 判死 <code>scheduler.hpp:977-981</code></td></tr>
    </table>
  </section>

  <!-- ================= 8. 总结 ================= -->
  <section id="s8">
    <h2 class="sec"><span class="num">8</span>总结</h2>
    <p class="lede">结构化输出是「算法简单、工程艰难」的典型特性:核心只有「编译文法 → 每步掩码」,但要在 zero-overhead 调度、MTP 投机解码、多级引擎与故障隔离的生产约束下不出错。</p>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">💎</span>设计亮点</h3>
        <ul class="feat">
          <li><b>编译与调度彻底解耦</b>:线程池 + future + 每步 pump,慢 schema 不阻塞任何请求;worker 绑核且不碰调度状态,免锁</li>
          <li><b>掩码准备与 logits 计算重叠</b>:CPU 填 xgrammar 位掩码的同时 GPU 算 logits,再经专用侧流 H2D + 双 event 定序,掩码几乎不上关键路径</li>
          <li><b>MTP 兼容的「试探-回滚」</b>:draft 只被试探性接受用于填 per-step 掩码,随即 rollback;违反文法的 draft 在验证时被掩码分布天然淘汰,合法 draft 分布不被扭曲</li>
          <li><b>故障半径=1 个请求</b>:从编译超时到 matcher 异常,一切失败收敛到 aborted_matcher + <code>so_status=-1</code> + FINISHED_SO_FAILED,采样主路径永不 raise(注释点名 NCCL barrier 连坐风险)</li>
          <li><b>账本防「判死后自由生成」</b>:判死只认 C++ 账本而非当步上报,迁移/重试副本不会漏网</li>
          <li><b>安全默认</b>:缓存默认 10 GiB 上限,无上限时告警 CVE-2025-32381;xgrammar 依赖精确锁版本 0.2.2</li>
        </ul>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">⚖️</span>边界与代价</h3>
        <ul class="feat">
          <li><b>SO 请求不可抢占重算</b>:KV 不足时直接 FINISHED_PREEMPTED(<code>scheduler.hpp:770-776</code>),生产上应给 SO 流量预留余量</li>
          <li><b>超时不杀编译线程</b>:20s 死线后请求判死,但后台编译继续占用 CPU 直到自然结束——病态 schema 仍会烧绑核 CPU</li>
          <li><b>golden token 与文法冲突即失败</b>:强制输出不接受掩码例外,下一 step 自动机校验后判死(显式失败而非静默吞错)</li>
          <li><b>掩码为 O(batch × ⌈V/32⌉) 内存与 H2D</b>:129280 词表、512 请求时每步约 0.8 MB 掩码(Draft 各步另计),靠 pinned + 侧流摊薄</li>
          <li><b>能力面</b>:仅离线 <code>LLM.generate</code> 路径;序列化文法与旧 bound_token_ids 已被显式禁用</li>
        </ul>
      </div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:24px 0 10px">关键文件索引</h3>
    <table class="tbl reveal">
      <tr><th>文件</th><th>职责</th><th>关键位置</th></tr>
      <tr><td><code>deepinfer/structure_output/compiler.py</code></td><td>xgrammar GrammarCompiler 封装;三类型分发;缓存策略</td><td>:14, :34-39, :54-71</td></tr>
      <tr><td><code>deepinfer/structure_output/matcher.py</code></td><td>自动机包装(KMP trigger / bound / EOS / 回滚);异步 future 与超时</td><td>:20, :58, :134-179, :181-204, :206-232, :261-338</td></tr>
      <tr><td><code>deepinfer/structure_output/so_matcher_builder.py</code></td><td>编译线程池、CPU 绑核、submit/pump 生命周期、replay</td><td>:33-49, :58-95, :109-121, :129-138</td></tr>
      <tr><td><code>deepinfer/structure_output/mask.py</code></td><td>掩码分配与 GPU 应用入口(懒 import)</td><td>:16-33</td></tr>
      <tr><td><code>deepinfer/model_executor/layers/sampler.py</code></td><td>SO 掩码热路径:_get_so_mask、侧流 H2D、per-step 应用、故障隔离</td><td>:135-138, :301-408, :433-437</td></tr>
      <tr><td><code>deepinfer/model_executor/layers/tilelang_ops/structure_output.py</code></td><td>TileLang 位掩码内核(按 step 寻址)+ 单测/基准</td><td>:12-61</td></tr>
      <tr><td><code>deepinfer/engine/llm_engine.py</code></td><td>builder 懒构造、请求接入、pending 计数、每 step pump、prefill 交界置位</td><td>:329-345, :606-630, :841-842, :910-928</td></tr>
      <tr><td><code>csrc/engine/sequence.hpp / scheduler.hpp</code></td><td>C++ 账本、状态回写、判死、抢占、fork 克隆 matcher</td><td>sequence.hpp:230-233, 282, 368-369; scheduler.hpp:770-776, 928-981, 1097-1099</td></tr>
      <tr><td><code>examples/_structured_output.py</code></td><td>regex / json / ebnf 三例 + 严格断言</td><td>:11-64</td></tr>
    </table>

    <div class="note good">
      <b>选型一句话:</b>需要「模型输出必然可解析」的场景(工具调用、评测抽取、结构化 agent)直接传 <code>so_args</code>;复杂度上,regex 最快最简单,JSON Schema 覆盖绝大多数 API 契约,EBNF 兜底一切自由文法。生产部署记得三件事:给 <code>DEEPINFER_SO_BUILDER_CPUS</code> 留足物理核、不要把 <code>DEEPINFER_XGRAMMAR_CACHE_LIMIT_BYTES</code> 设成 0、接受「SO 请求被抢占即终止」的调度语义。
    </div>
  </section>

  <div class="pgnav">
    <span>DeepInfer 代码分析系列 · 由 ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/deepinfer/">← 返回系列总览</a></span>
  </div>
<script>
// 滚动显现动画
const io=new IntersectionObserver(es=>{es.forEach(e=>{if(e.isIntersecting){e.target.classList.add('on');io.unobserve(e.target)}})},{threshold:.12});
document.querySelectorAll('.reveal').forEach(el=>io.observe(el));
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>NCCL 使用场景全景(代码级) · DeepInfer</title><link>https://hccl.club/docs/inference-engines/deepinfer/08-nccl-usage/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/08-nccl-usage/</guid><description><![CDATA[<div class="fwdoc">
<style>
.fwdoc{--bg:#0b1020; --bg2:#0f1729; --panel:#141d33; --panel2:#1a2440;
  --border:#263352; --text:#dbe4f5; --muted:#8ea0c2;
  --accent:#4f8cff; --accent2:#22d3ee; --good:#34d399; --warn:#fbbf24; --bad:#f87171; --purple:#a78bfa;
  --code-bg:#0d1424; --radius:14px;
  --serif:"Noto Serif SC","Songti SC",serif;}
.fwdoc *{box-sizing:border-box;margin:0;padding:0}
.fwdoc{background:linear-gradient(160deg,var(--bg) 0%,var(--bg2) 60%,#0a0f1e 100%);color:var(--text);
  font-family:"PingFang SC","Microsoft YaHei","Segoe UI",system-ui,sans-serif;line-height:1.75;}
.fwdoc{flex:1;min-width:0;padding:36px 48px 80px}
@media(max-width:960px){.fwdoc{padding:24px 18px 60px}}
.fwdoc .hero{position:relative;border-radius:var(--radius);overflow:hidden;padding:46px 44px;margin-bottom:34px;
  background:radial-gradient(1200px 400px at 15% -20%,rgba(79,140,255,.28),transparent 60%),
             radial-gradient(900px 380px at 95% 0%,rgba(167,139,250,.20),transparent 55%),
             linear-gradient(135deg,#16213e,#101a30);border:1px solid var(--border)}
.fwdoc .hero .crumb{font-size:12px;color:var(--accent2);letter-spacing:1px;margin-bottom:12px}
.fwdoc .hero h1{font-size:34px;color:#fff;font-weight:800;letter-spacing:.5px;margin-bottom:10px}
.fwdoc .hero p.desc{color:var(--muted);max-width:760px;font-size:15px}
.fwdoc .hero .tags{margin-top:18px;display:flex;gap:10px;flex-wrap:wrap}
.fwdoc .hero .tag{font-size:12px;padding:4px 14px;border-radius:999px;border:1px solid var(--border);
  background:rgba(79,140,255,.10);color:var(--accent2)}
.fwdoc .tag.good{border-color:rgba(52,211,153,.4);color:var(--good);background:rgba(52,211,153,.08)}
.fwdoc .tag.warn{border-color:rgba(251,191,36,.4);color:var(--warn);background:rgba(251,191,36,.08)}
.fwdoc section{margin-bottom:44px;scroll-margin-top:20px}
.fwdoc h2.sec{display:flex;align-items:center;gap:12px;font-size:23px;color:#fff;margin-bottom:6px;padding-bottom:10px;border-bottom:1px solid var(--border)}
.fwdoc h2.sec .num{display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:10px;flex-shrink:0;
  background:linear-gradient(135deg,var(--accent),var(--purple));color:#fff;font-size:15px;font-weight:800}
.fwdoc .lede{color:var(--muted);font-size:14px;margin-bottom:20px}
.fwdoc .grid{display:grid;gap:18px}
.fwdoc .grid.c2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}
.fwdoc .grid.c3{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}
.fwdoc .card{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:var(--radius);padding:22px 24px;transition:transform .3s,border-color .3s,box-shadow .3s}
.fwdoc .card:hover{transform:translateY(-3px);border-color:rgba(79,140,255,.55);box-shadow:0 12px 34px -14px rgba(79,140,255,.35)}
.fwdoc .card h3{font-size:16.5px;color:#fff;margin-bottom:8px;display:flex;align-items:center;gap:9px}
.fwdoc .card h3 .ico{width:26px;height:26px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;
  background:rgba(79,140,255,.16);font-size:14px;flex-shrink:0}
.fwdoc .card p{font-size:13.5px;color:var(--muted)}
.fwdoc .card p code,.fwdoc .inline-code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1.5px 7px;border-radius:6px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px}
.fwdoc ul.feat{list-style:none}
.fwdoc ul.feat li{padding:9px 0 9px 30px;position:relative;font-size:14px;color:var(--text);border-bottom:1px dashed rgba(38,51,82,.6)}
.fwdoc ul.feat li:last-child{border-bottom:none}
.fwdoc ul.feat li::before{content:"▸";position:absolute;left:8px;color:var(--accent);font-weight:700;animation:fw-blink 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
@keyframes fw-blink{0%,100%{opacity:.35}50%{opacity:1}}
.fwdoc pre.code{background:var(--code-bg);border:1px solid var(--border);border-radius:12px;padding:18px 20px;
  overflow-x:auto;font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px;line-height:1.65;margin:14px 0;position:relative}
.fwdoc pre.code::before{content:"● ● ●";display:block;color:#3a4a70;font-size:10px;letter-spacing:3px;margin-bottom:10px}
.fwdoc pre.code .k{color:#c792ea}
.fwdoc pre.code .s{color:#89ddff}
.fwdoc pre.code .c{color:#5d7294;font-style:italic}
.fwdoc pre.code .f{color:#82aaff}
.fwdoc pre.code .n{color:#f78c6c}
.fwdoc pre.code .h{color:#ffcb6b}
.fwdoc .filepath{font-family:"JetBrains Mono",Consolas,monospace;font-size:11.5px;color:var(--accent2);
  background:rgba(34,211,238,.08);border:1px solid rgba(34,211,238,.25);border-radius:6px;padding:2px 10px;display:inline-block;margin-bottom:4px}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border)}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px}
.fwdoc table.tbl td{padding:10px 14px;border-top:1px solid var(--border);color:var(--text);vertical-align:top}
.fwdoc table.tbl tr{transition:background .2s}
.fwdoc table.tbl tr:nth-child(even) td{background:rgba(20,29,51,.5)}
.fwdoc table.tbl tr:hover td{background:rgba(79,140,255,.10)}
.fwdoc table.tbl td code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;font-family:Consolas,monospace;font-size:12px}
.fwdoc .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px}
.fwdoc .badge.merged{background:rgba(52,211,153,.15);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.open{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.closed{background:rgba(248,113,113,.13);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.nccl{background:rgba(251,191,36,.12);color:var(--warn);border:1px solid rgba(251,191,36,.4)}
.fwdoc .badge.hccl{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .badge.deepep{background:rgba(34,211,238,.12);color:var(--accent2);border:1px solid rgba(34,211,238,.4)}
.fwdoc .reveal{opacity:0;transform:translateY(26px);transition:opacity .7s cubic-bezier(.2,.7,.3,1),transform .7s cubic-bezier(.2,.7,.3,1)}
.fwdoc .reveal.on{opacity:1;transform:none}
.fwdoc .reveal.d1{transition-delay:.12s}
.fwdoc .reveal.d2{transition-delay:.24s}
.fwdoc .reveal.d3{transition-delay:.36s}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:20px;margin:18px 0;position:relative;overflow:hidden}
.fwdoc .figure .cap{text-align:center;font-size:12.5px;color:var(--muted);margin-top:10px}
.fwdoc .figure svg{width:100%;height:auto;display:block}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-flow 1.2s linear infinite}
@keyframes fw-flow{to{stroke-dashoffset:-14}}
.fwdoc .pulse{animation:fw-pulse 2s ease-in-out infinite;transform-origin:center}
@keyframes fw-pulse{0%,100%{opacity:.45;transform:scale(1)}50%{opacity:1;transform:scale(1.06)}}
.fwdoc .node-gpu{fill:#16233f;stroke:#4f8cff;stroke-width:1.6;rx:10}
.fwdoc .node-gpu-title{fill:#dbe4f5;font-size:13px;font-weight:700}
.fwdoc .token-dot{fill:#22d3ee}
.fwdoc .barrow{filter:drop-shadow(0 0 6px rgba(34,211,238,.7))}
.fwdoc .timeline{position:relative;padding-left:34px}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .tl-item{position:relative;margin-bottom:20px}
.fwdoc .tl-item::before{content:"";position:absolute;left:-30px;top:7px;width:12px;height:12px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.18);animation:fw-pulse 2.4s infinite}
.fwdoc .tl-item .tl-date{font-size:11.5px;color:var(--accent2);letter-spacing:.5px}
.fwdoc .tl-item .tl-body{font-size:13.5px;color:var(--text);margin-top:3px}
.fwdoc .note{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13px;color:var(--text);margin:16px 0}
.fwdoc .note.warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .note.good{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .note b{color:#fff}
.fwdoc .pgnav{margin-top:60px;padding-top:20px;border-top:1px solid var(--border);color:#5a6b92;font-size:12px;
  display:flex;justify-content:space-between;flex-wrap:wrap;gap:10px}
.fwdoc .pgnav a{color:var(--accent2);text-decoration:none}
/* ===== 导入面板附加样式 ===== */
.fwdoc{border-radius:14px;margin:18px 0}
.fwdoc table.tbl{display:block;overflow-x:auto;max-width:100%}
@media (prefers-reduced-motion:reduce){
.fwdoc *,.fwdoc *::before,.fwdoc *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
.fwdoc .reveal{opacity:1!important;transform:none!important}
}

</style>

<!-- ============================================================ 1. 总览 ============================================================ -->
  <section id="s1">
    <h2 class="sec"><span class="num">1</span>NCCL 在 DeepInfer 通信栈中的定位</h2>
    <p class="lede">GPU 平台上,DeepInfer 把「集合通信」交给 NCCL、「大流量 MoE/CP 数据面」交给 DeepEP-V2 自建 NVLink/RDMA 通路、「CPU 控制消息」交给 gloo 与共享内存队列。NCCL 承担的是<strong>控制面与中等流量的设备侧同步</strong>:进程组预热、CP 元数据广播、DP 终止检测、EPLB 统计与专家权重迁移。</p>

    <div class="figure reveal">
      <svg viewBox="0 0 1180 560" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="arw" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#8ea0c2"/>
          </marker>
          <linearGradient id="gnccl" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stop-color="#fbbf24" stop-opacity=".28"/><stop offset="1" stop-color="#fbbf24" stop-opacity=".06"/>
          </linearGradient>
          <linearGradient id="gdeep" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stop-color="#22d3ee" stop-opacity=".28"/><stop offset="1" stop-color="#22d3ee" stop-opacity=".06"/>
          </linearGradient>
          <linearGradient id="ggloo" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stop-color="#a78bfa" stop-opacity=".28"/><stop offset="1" stop-color="#a78bfa" stop-opacity=".06"/>
          </linearGradient>
          <linearGradient id="gshm" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stop-color="#34d399" stop-opacity=".28"/><stop offset="1" stop-color="#34d399" stop-opacity=".06"/>
          </linearGradient>
        </defs>

        <!-- 顶:应用层 -->
        <rect x="240" y="14" width="700" height="74" rx="12" fill="#16233f" stroke="#4f8cff" stroke-width="1.6"/>
        <text x="590" y="42" text-anchor="middle" fill="#fff" font-size="15" font-weight="700">应用层:LLMEngine · Worker/ModelRunner · EPLB(ExpertLoadBalancer) · Sampler · DFlash MTP</text>
        <text x="590" y="70" text-anchor="middle" fill="#8ea0c2" font-size="12">每 step 的调度、采样与专家负载均衡决策都从这里发起通信</text>

        <!-- 四条泳道 -->
        <rect x="20"  y="130" width="278" height="330" rx="12" fill="url(#gnccl)" stroke="#fbbf24" stroke-width="1.6"/>
        <rect x="312" y="130" width="278" height="330" rx="12" fill="url(#gdeep)" stroke="#22d3ee" stroke-width="1.6"/>
        <rect x="604" y="130" width="278" height="330" rx="12" fill="url(#ggloo)" stroke="#a78bfa" stroke-width="1.6"/>
        <rect x="896" y="130" width="264" height="330" rx="12" fill="url(#gshm)" stroke="#34d399" stroke-width="1.6"/>

        <text x="159" y="158" text-anchor="middle" fill="#fbbf24" font-size="15" font-weight="800">NCCL(控制面/同步)</text>
        <text x="451" y="158" text-anchor="middle" fill="#22d3ee" font-size="15" font-weight="800">DeepEP-V2(数据面)</text>
        <text x="743" y="158" text-anchor="middle" fill="#a78bfa" font-size="15" font-weight="800">gloo(CPU 消息)</text>
        <text x="1028" y="158" text-anchor="middle" fill="#34d399" font-size="15" font-weight="800">SHM / IPC / SymmMem</text>

        <!-- NCCL lane items -->
        <g font-size="12" fill="#dbe4f5">
          <rect x="38" y="176" width="242" height="56" rx="8" fill="#141d33" stroke="#fbbf24" stroke-opacity=".5" class="pulse"/>
          <text x="159" y="198" text-anchor="middle">7 张设备进程组 world/local/dp/</text>
          <text x="159" y="216" text-anchor="middle">cp/ep/ep_in_dp/enp</text>
          <rect x="38" y="242" width="242" height="44" rx="8" fill="#141d33" stroke="#fbbf24" stroke-opacity=".5"/>
          <text x="159" y="262" text-anchor="middle">all_reduce / broadcast /</text>
          <text x="159" y="278" text-anchor="middle">all_gather_into_tensor / batch_isend_irecv</text>
          <rect x="38" y="294" width="242" height="44" rx="8" fill="#141d33" stroke="#fbbf24" stroke-opacity=".5"/>
          <text x="159" y="314" text-anchor="middle">SM 预算 ≤ 32 CTA</text>
          <text x="159" y="330" text-anchor="middle">DEEPINFER_NCCL_NUM_SMS</text>
          <rect x="38" y="346" width="242" height="44" rx="8" fill="#141d33" stroke="#fbbf24" stroke-opacity=".5"/>
          <text x="159" y="366" text-anchor="middle">communicator 由 deep_ep 经</text>
          <text x="159" y="382" text-anchor="middle">_comm_ptr() 复用</text>
          <text x="159" y="436" text-anchor="middle" fill="#fbbf24" font-size="11.5">NCCL 2.32.3 · build.sh:17-18</text>
        </g>

        <!-- DeepEP lane -->
        <g font-size="12" fill="#dbe4f5">
          <rect x="330" y="176" width="242" height="56" rx="8" fill="#141d33" stroke="#22d3ee" stroke-opacity=".5" class="pulse"/>
          <text x="451" y="198" text-anchor="middle">EPBuffer:MoE dispatch/combine</text>
          <text x="451" y="216" text-anchor="middle">NVLink + RDMA 自建通信(不经 NCCL)</text>
          <rect x="330" y="242" width="242" height="44" rx="8" fill="#141d33" stroke="#22d3ee" stroke-opacity=".5"/>
          <text x="451" y="262" text-anchor="middle">CPManager(BucketBuffer):</text>
          <text x="451" y="278" text-anchor="middle">CP all-gather 会话</text>
          <rect x="330" y="294" width="242" height="44" rx="8" fill="#141d33" stroke="#22d3ee" stroke-opacity=".5"/>
          <text x="451" y="314" text-anchor="middle">EngramBuffer:稀疏 n-gram 检索</text>
          <rect x="330" y="346" width="242" height="44" rx="8" fill="#141d33" stroke="#22d3ee" stroke-opacity=".5"/>
          <text x="451" y="366" text-anchor="middle">通信 SM 数</text>
          <text x="451" y="382" text-anchor="middle">DEEPINFER_USERBUFFER_COMM_SMS</text>
          <text x="451" y="436" text-anchor="middle" fill="#22d3ee" font-size="11.5">userbuffer.py · mlp.py:471/504/602</text>
        </g>

        <!-- gloo lane -->
        <g font-size="12" fill="#dbe4f5">
          <rect x="622" y="176" width="242" height="56" rx="8" fill="#141d33" stroke="#a78bfa" stroke-opacity=".5" class="pulse"/>
          <text x="743" y="198" text-anchor="middle">默认 ProcessGroup(backend="gloo")</text>
          <text x="743" y="216" text-anchor="middle">worker/base.py:334-340</text>
          <rect x="622" y="242" width="242" height="44" rx="8" fill="#141d33" stroke="#a78bfa" stroke-opacity=".5"/>
          <text x="743" y="262" text-anchor="middle">cpu_dp / cpu_cp / cpu_ep_in_dp</text>
          <text x="743" y="278" text-anchor="middle">三张 CPU 备份组</text>
          <rect x="622" y="294" width="242" height="44" rx="8" fill="#141d33" stroke="#a78bfa" stroke-opacity=".5"/>
          <text x="743" y="314" text-anchor="middle">ZOS 终止检测(CPU tensor)</text>
          <text x="743" y="330" text-anchor="middle">llm_engine.py:668</text>
          <rect x="622" y="346" width="242" height="44" rx="8" fill="#141d33" stroke="#a78bfa" stroke-opacity=".5"/>
          <text x="743" y="366" text-anchor="middle">barrier ×2(stop 退出路径)</text>
          <text x="743" y="382" text-anchor="middle">base.py:138/140 · timeout 4h</text>
          <text x="743" y="436" text-anchor="middle" fill="#a78bfa" font-size="11.5">DEEPINFER_GLOO_TIMEOUT=14400s</text>
        </g>

        <!-- SHM lane -->
        <g font-size="12" fill="#dbe4f5">
          <rect x="914" y="176" width="228" height="56" rx="8" fill="#141d33" stroke="#34d399" stroke-opacity=".5" class="pulse"/>
          <text x="1028" y="198" text-anchor="middle">MessageQueue(SHM 广播)</text>
          <text x="1028" y="216" text-anchor="middle">CP 组内对象广播</text>
          <rect x="914" y="242" width="228" height="44" rx="8" fill="#141d33" stroke="#34d399" stroke-opacity=".5"/>
          <text x="1028" y="262" text-anchor="middle">CUDA IPC:单机 EPLB 权重镜像</text>
          <text x="1028" y="278" text-anchor="middle">eplb/__init__.py:206-220</text>
          <rect x="914" y="294" width="228" height="44" rx="8" fill="#141d33" stroke="#34d399" stroke-opacity=".5"/>
          <text x="1028" y="314" text-anchor="middle">SymmBuffer(NVLink 对称内存)</text>
          <text x="1028" y="330" text-anchor="middle">DeepGEMM · userbuffer.py:221</text>
          <rect x="914" y="346" width="228" height="44" rx="8" fill="#141d33" stroke="#34d399" stroke-opacity=".5"/>
          <text x="1028" y="366" text-anchor="middle">跨进程/跨 rank 零拷贝</text>
          <text x="1028" y="436" text-anchor="middle" fill="#34d399" font-size="11.5">shm_broadcast.py · eplb/shuffle.py</text>
        </g>

        <!-- 底部:NPU 分支 -->
        <rect x="240" y="486" width="700" height="58" rx="12" fill="#16233f" stroke="#a78bfa" stroke-width="1.4"/>
        <text x="590" y="510" text-anchor="middle" fill="#a78bfa" font-size="13" font-weight="700">NPU 平台(昇腾 950):同名抽象,distributed_backend="hccl"(platform.py:89)</text>
        <text x="590" y="532" text-anchor="middle" fill="#8ea0c2" font-size="11.5">init_device_groups 对 "nccl"/"hccl" 同等对待(parallel_state.py:181),本系列文档聚焦 GPU 侧 NCCL</text>

        <!-- 应用层到泳道的连线 -->
        <g stroke="#8ea0c2" stroke-width="1.4" marker-end="url(#arw)">
          <line x1="390" y1="88" x2="160" y2="128" class="flowline"/>
          <line x1="510" y1="88" x2="450" y2="128" class="flowline"/>
          <line x1="660" y1="88" x2="740" y2="128" class="flowline"/>
          <line x1="820" y1="88" x2="1020" y2="128" class="flowline"/>
        </g>
      </svg>
      <div class="cap">图 1-1 · DeepInfer GPU 通信栈分工:NCCL 管集合通信控制面,DeepEP-V2 管大流量数据面,gloo 管 CPU 消息,SHM/IPC/SymmMem 管节点内零拷贝(连线流动方向即每 step 的通信发起路径)</div>
    </div>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🎯</span>NCCL 只出现在「设备侧进程组」上</h3>
        <p>DeepInfer 的<strong>默认 ProcessGroup 是 gloo</strong>(<code>worker/base.py:334-340</code>,<code>init_process_group(backend="gloo")</code>),因此任何 <code>dist.*</code> 调用只要显式传入了 <code>PG.xxx_group()</code> 设备组,才会走 NCCL。这是判别代码中某次通信是否走 NCCL 的<strong>唯一可靠标准</strong>,本文所有调用点都按此核对。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧩</span>七张 NCCL 组,三张 gloo 备份组</h3>
        <p><code>parallel_state.py:86-118</code> 创建 <code>world / local / dp / cp / ep / enp / ep_in_dp</code> 七类设备组;同时以 <code>backend="gloo"</code> 建了 <code>cpu_dp / cpu_cp / cpu_ep_in_dp</code> 三张 CPU 备份组,用于对象广播、SHM 队列引导与 ZOS 终止检测。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">⚡</span>NCCL 内核被限制在 32 个 SM</h3>
        <p>每张 NCCL 组都带 <code>ProcessGroupNCCL.Options</code>:<code>max_ctas = min_ctas = DEEPINFER_NCCL_NUM_SMS</code>(默认 32,<code>platform.py:80-83</code>),防止集合通信内核与计算内核抢占 SM;DeepEP 侧另有独立的 <code>DEEPINFER_USERBUFFER_COMM_SMS</code> 预算。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">🔍</span>communicator 全生命周期可观测</h3>
        <p><code>nccl_memory.py</code> 的 <code>NCCLMemoryStatsLogger</code> 遍历 <code>c10d._world.pg_map</code>,经 <code>backend._comm_ptr()</code> 过滤未初始化的 communicator,读 <code>memory_stats()["total"]</code>,按 <code>PG_dict</code> 别名输出 GiB 级内存快照——NCCL 通信缓冲在 SM100 大规模部署下是显存的重要消耗项。</p>
      </div>
    </div>

    <div class="note">
      <b>一个容易误判的事实:</b>全仓库 grep <code>dist\.</code> 得到的调用点中,<code>worker/base.py:138/140</code> 的两个 <code>dist.barrier()</code> <strong>并不走 NCCL</strong>——它们没有传 <code>group</code> 参数,落在默认 gloo 组上;<code>distributed/shm_broadcast.py:454/457</code> 的 <code>broadcast_object_list</code> 传入的是 <code>cpu_cp_group</code>(gloo),也<strong>不走 NCCL</strong>。逐一澄清见 <a href="#s48">第 4.8 节</a>。
    </div>
  </section>

  <!-- ============================================================ 2. 初始化与调优 ============================================================ -->
  <section id="s2">
    <h2 class="sec"><span class="num">2</span>NCCL 后端初始化与调优</h2>
    <p class="lede">NCCL 的初始化发生在 Worker 启动序:先建 gloo 默认组 → 按拓扑切分七张 NCCL 组(带 CTA 预算)→ eager 跑一遍 all_reduce 强制建立 communicator → 设置 NCCL 原生环境变量。整条链路决定了后续每一次集合通信的 SM 占用与启动行为。</p>

    <h3 style="color:#fff;font-size:17px;margin-bottom:6px">2.1 后端声明:平台抽象下的 "nccl"</h3>
    <p style="font-size:14px;color:var(--muted);margin-bottom:8px">DeepInfer 用平台抽象屏蔽 GPU/NPU 差异,<code>distributed_backend</code> 是唯一的后端开关:</p>
    <pre class="code"><span class="filepath">deepinfer/platform.py:55-83(节选)</span>
<span class="k">class</span> <span class="f">PlatformGPU</span>(Platform):
    enum = PlatformEnum.GPU
    tilelang_ops_backend = <span class="s">"cuda"</span>
    distributed_backend = <span class="s">"nccl"</span>          <span class="c"># ← 58 行:GPU 平台的 torch.distributed 后端</span>

    <span class="k">def</span> <span class="f">get_distributed_options</span>(<span class="k">self</span>) -> <span class="k">object</span>:
        <span class="k">import</span> torch.distributed <span class="k">as</span> dist
        <span class="k">from</span> deepinfer <span class="k">import</span> envs
        options = dist.ProcessGroupNCCL.<span class="f">Options</span>()   <span class="c"># ← 80 行</span>
        options.config.max_ctas = envs.DEEPINFER_NCCL_NUM_SMS       <span class="c"># ← 81 行:NCCL 通信内核 CTA 上限</span>
        options.config.min_ctas = envs.DEEPINFER_NCCL_NUM_SMS       <span class="c"># ← 82 行:CTA 下限(锁定规模,禁自适应扩张)</span>
        <span class="k">return</span> options

<span class="k">class</span> <span class="f">PlatformNPU</span>(Platform):
    distributed_backend = <span class="s">"hccl"</span>          <span class="c"># ← 89 行:昇腾平台对应 HCCL</span></pre>
    <ul class="feat">
      <li><code>max_ctas/min_ctas</code> 成对设置为同一值:NCCL communicator 建立时即把通信内核的 CTA 规模<strong>钉死在 32</strong>(默认值),既保证低时延集合通信有稳定并行度,又把 SM 让给计算内核。</li>
      <li>NPU 侧 <code>get_distributed_options()</code>(platform.py:145-149)返回 <code>ProcessGroupHCCL.Options()</code>,同一套 <code>parallel_state</code> 逻辑对两种平台透明。</li>
    </ul>

    <h3 style="color:#fff;font-size:17px;margin:8px 0 6px">2.2 默认组是 gloo:NCCL 组必须显式创建</h3>
    <p style="font-size:14px;color:var(--muted);margin-bottom:8px">这是理解 DeepInfer NCCL 使用方式的第一个关键:默认 ProcessGroup 是 CPU gloo,不是 NCCL。</p>
    <pre class="code"><span class="filepath">deepinfer/worker/base.py:315-344(_init_distributed_environment,节选)</span>
<span class="k">def</span> <span class="f">_init_distributed_environment</span>(parallel_config, cp_rank, distributed_init_method=<span class="k">None</span>):
    ...
    <span class="k">if not</span> dist.<span class="f">is_initialized</span>():
        rank = engine_rank * cp_size + cp_rank
        dist.<span class="f">init_process_group</span>(
            backend=<span class="s">"gloo"</span>,                     <span class="c"># ← 335 行:默认 PG = gloo(CPU)</span>
            world_size=parallel_config.world_size,
            rank=rank,
            init_method=distributed_init_method,
            timeout=envs.DEEPINFER_GLOO_TIMEOUT,        <span class="c"># ← 339 行:默认 14400s = 4 小时</span>
        )
    <span class="f">init_parallel_groups</span>(dp_size, ep_size=ep_size, cp_size=cp_size, enp_size=enp_size)  <span class="c"># ← 343 行:再建 NCCL 子组</span></pre>
    <p style="font-size:14px;color:var(--muted)">随后 <code>parallel_state.py</code> 按 rank 重排公式把全部 rank 切成七类设备组与三张 gloo 备份组:</p>
    <table class="tbl">
      <tr><th>进程组</th><th>创建位置(file:line)</th><th>后端</th><th>rank 划分(einops 表达式)</th><th>别名/复用</th><th>典型用途</th></tr>
      <tr><td><code>PG.world</code></td><td>parallel_state.py:86</td><td><span class="badge nccl">NCCL</span></td><td><code>[全部 rank]</code></td><td>ep_size == 总 rank 时被 <code>PG.ep</code> 复用(102-103 行)</td><td>KV 块数对齐(base.py:265)</td></tr>
      <tr><td><code>PG.local</code></td><td>parallel_state.py:89</td><td><span class="badge nccl">NCCL</span></td><td><code>ranks.unsqueeze(-1)</code> 每机一组</td><td>ep_size == 1 时被 <code>PG.ep_in_dp</code> 复用(114-115 行)</td><td>机内单卡组(DeepEP 域判断)</td></tr>
      <tr><td><code>PG.dp</code></td><td>parallel_state.py:93</td><td><span class="badge nccl">NCCL</span></td><td><code>(replica dp cp) -&gt; (replica cp) dp</code></td><td>—</td><td>DP 终止检测(llm_engine.py:677)</td></tr>
      <tr><td><code>PG.cpu_dp_group</code></td><td>parallel_state.py:94</td><td><span class="badge hccl">gloo</span></td><td>同上</td><td>—</td><td>ZOS 终止检测(CPU 路径)</td></tr>
      <tr><td><code>PG.cp</code></td><td>parallel_state.py:98</td><td><span class="badge nccl">NCCL</span></td><td><code>(dp cp) -&gt; dp cp</code></td><td>—</td><td>CP 元数据/采样广播(communication_op.py:32/43)</td></tr>
      <tr><td><code>PG.cpu_cp_group</code></td><td>parallel_state.py:99</td><td><span class="badge hccl">gloo</span></td><td>同上</td><td>SHM MessageQueue 引导(parallel_state.py:124)</td><td>对象广播 + run_workers RPC(base.py:298)</td></tr>
      <tr><td><code>PG.ep</code></td><td>parallel_state.py:106</td><td><span class="badge nccl">NCCL</span></td><td><code>(edp ep) -&gt; edp ep</code></td><td>ep_size == 总 rank 时复用 world</td><td>EPLB 统计/重排、decode perf</td></tr>
      <tr><td><code>PG.enp</code></td><td>parallel_state.py:110</td><td><span class="badge nccl">NCCL</span></td><td><code>(replica enp) -&gt; replica enp</code></td><td>—</td><td>Engram FP8 scale 聚合(engram.py:100)</td></tr>
      <tr><td><code>PG.ep_in_dp</code></td><td>parallel_state.py:117</td><td><span class="badge nccl">NCCL</span></td><td><code>(edp ep_in_dp) -&gt; edp ep_in_dp</code></td><td>ep_size == 1 时复用 local</td><td>DeepEP EP-in-DP 域内通信</td></tr>
      <tr><td><code>PG.cpu_ep_in_dp</code></td><td>parallel_state.py:118</td><td><span class="badge hccl">gloo</span></td><td>同上</td><td>—</td><td>CPU 备份组</td></tr>
    </table>
    <div class="note">所有设备组都通过 <code>_split_group</code> → <code>dist.new_group(list(ranks), backend=backend, pg_options=pg_options)</code>(parallel_state.py:34)创建,<code>pg_options</code> 即 2.1 节的 CTA 配置;且经 <code>functools.lru_cache</code> 按 (ranks, backend, options) 去重(parallel_state.py:26-37),多 engine(多 tag)部署共享同一批 communicator。</div>

    <h3 style="color:#fff;font-size:17px;margin:18px 0 6px">2.3 eager 通信器建立:init_device_groups</h3>
    <p style="font-size:14px;color:var(--muted);margin-bottom:8px">默认 PG 改成 gloo 后,PyTorch 不再为 NCCL 子组做 eager/split 初始化,communicator 全部 lazy。DeepInfer 显式补了这一步:</p>
    <pre class="code"><span class="filepath">deepinfer/model_executor/parallel_utils/parallel_state.py:173-187</span>
<span class="k">def</span> <span class="f">init_device_groups</span>(<span class="k">self</span>) -> <span class="k">None</span>:
    <span class="s">"""默认 PG 改为 CPU(gloo) 后端后,NCCL/HCCL 子组失去 eager/split 初始化,全部 lazy:
    必须先跑一次 collective 才会真正建 comm。

    单 rank 组也不能跳过:engram deep_ep 经 `backend._comm_ptr()` 复用这里建出的 comm,
    空指针会直接段错误。"""</span>
    seen: set[int] = set()
    <span class="k">for</span> value <span class="k">in</span> <span class="k">self</span>.__dict__.<span class="f">values</span>():
        <span class="k">try</span>:
            <span class="k">if not</span> isinstance(value, ProcessGroup) <span class="k">or</span> dist.<span class="f">get_backend</span>(value) <span class="k">not in</span> (<span class="s">"nccl"</span>, <span class="s">"hccl"</span>):   <span class="c"># ← 181 行</span>
                <span class="k">continue</span>
        <span class="k">except</span> Exception:
            <span class="k">continue</span>
        <span class="k">if</span> id(value) <span class="k">not in</span> seen:
            seen.<span class="f">add</span>(id(value))
            dist.<span class="f">all_reduce</span>(torch.<span class="f">zeros</span>(<span class="n">1</span>).<span class="f">cuda</span>(), group=value)   <span class="c"># ← 187 行:eager 建立 communicator</span></pre>
    <ul class="feat">
      <li><strong>动机一(避免 lazy init 串入稳态):</strong>NCCL communicator 首次建链涉及 bootstrap、拓扑探测与 buffer 分配,若发生在第一个推理 step 中,会污染 latency 并与 CUDA graph capture 冲突。</li>
      <li><strong>动机二(DeepEP 硬依赖):</strong>DeepEP-V2 的 EngramBuffer 经 <code>backend._comm_ptr()</code> 直接取走这里建好的 NCCL communicator 做引导;组还没建过通信时该指针为空,DeepEP C++ 侧解引用空指针<strong>直接段错误</strong>——所以即使是单 rank 组也不能跳过。</li>
      <li><strong>seen 集合按对象 id 去重:</strong><code>PG.ep == PG.world</code>(全量 EP)、<code>PG.ep_in_dp == PG.local</code>(ep_size=1)的复用关系下不会重复 all_reduce。</li>
      <li>每次预热成本:1 个 <code>zeros(1).cuda()</code> 的 all_reduce,每张 NCCL 组一次,启动时一次性完成。</li>
    </ul>

    <h3 style="color:#fff;font-size:17px;margin:18px 0 6px">2.4 SM 共存动画:32 个 CTA 的通信内核与计算内核</h3>
    <div class="figure reveal">
      <svg viewBox="0 0 1180 470" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <linearGradient id="smg" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stop-color="#1e3a6e"/><stop offset="1" stop-color="#16233f"/>
          </linearGradient>
          <linearGradient id="smnccl" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stop-color="#7a5b16"/><stop offset="1" stop-color="#4a380e"/>
          </linearGradient>
          <linearGradient id="smep" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stop-color="#0e5a6e"/><stop offset="1" stop-color="#0a3c4a"/>
          </linearGradient>
        </defs>
        <!-- GPU 外框 -->
        <rect x="30" y="70" width="1120" height="330" rx="14" fill="#0e1729" stroke="#4f8cff" stroke-width="2"/>
        <text x="590" y="46" text-anchor="middle" fill="#fff" font-size="16" font-weight="800">单颗 SM100 GPU 的 SM 阵列(示意:每格一个 SM;NCCL 通信内核 ≤ 32 CTA 与计算内核共存)</text>

        <!-- SM 网格: 18 列 × 5 行 -->
        <!-- 前 4 列(20 格)NCCL 黄色区 -->
        <g>
          <!-- row 1 -->
          <rect x="60"  y="100" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="120" y="100" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="180" y="100" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="240" y="100" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <!-- row 2 -->
          <rect x="60"  y="160" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="120" y="160" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="180" y="160" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="240" y="160" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <!-- row 3 -->
          <rect x="60"  y="220" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="120" y="220" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="180" y="220" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="240" y="220" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <!-- row 4 -->
          <rect x="60"  y="280" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="120" y="280" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="180" y="280" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="240" y="280" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <!-- row 5 -->
          <rect x="60"  y="340" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="120" y="340" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="180" y="340" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
          <rect x="240" y="340" width="52" height="52" rx="7" fill="url(#smnccl)" stroke="#fbbf24" stroke-width="1.5"/>
        </g>
        <!-- 脉冲动画的 NCCL 活跃框 -->
        <rect x="60" y="100" width="232" height="292" rx="10" fill="none" stroke="#fbbf24" stroke-width="2" class="pulse"/>

        <!-- DeepEP 区域(2 列青色) -->
        <g>
          <rect x="330" y="100" width="52" height="52" rx="7" fill="url(#smep)" stroke="#22d3ee" stroke-width="1.5"/>
          <rect x="390" y="100" width="52" height="52" rx="7" fill="url(#smep)" stroke="#22d3ee" stroke-width="1.5"/>
          <rect x="330" y="160" width="52" height="52" rx="7" fill="url(#smep)" stroke="#22d3ee" stroke-width="1.5"/>
          <rect x="390" y="160" width="52" height="52" rx="7" fill="url(#smep)" stroke="#22d3ee" stroke-width="1.5"/>
          <rect x="330" y="220" width="52" height="52" rx="7" fill="url(#smep)" stroke="#22d3ee" stroke-width="1.5"/>
          <rect x="390" y="220" width="52" height="52" rx="7" fill="url(#smep)" stroke="#22d3ee" stroke-width="1.5"/>
          <rect x="330" y="280" width="52" height="52" rx="7" fill="url(#smep)" stroke="#22d3ee" stroke-width="1.5"/>
          <rect x="390" y="280" width="52" height="52" rx="7" fill="url(#smep)" stroke="#22d3ee" stroke-width="1.5"/>
          <rect x="330" y="340" width="52" height="52" rx="7" fill="url(#smep)" stroke="#22d3ee" stroke-width="1.5"/>
          <rect x="390" y="340" width="52" height="52" rx="7" fill="url(#smep)" stroke="#22d3ee" stroke-width="1.5"/>
        </g>
        <rect x="330" y="100" width="112" height="292" rx="10" fill="none" stroke="#22d3ee" stroke-width="2" class="pulse" style="animation-delay:.5s"/>

        <!-- 计算内核区(12 列蓝色) -->
        <g>
          <g class="pulse" style="animation-delay:.25s">
          <rect x="540" y="100" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="600" y="100" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="660" y="100" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="720" y="100" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="540" y="280" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="600" y="280" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          </g>
          <rect x="780" y="100" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="840" y="100" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="540" y="160" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="600" y="160" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="660" y="160" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="720" y="160" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="780" y="160" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="840" y="160" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="540" y="220" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="600" y="220" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="660" y="220" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="720" y="220" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="780" y="220" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="840" y="220" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="660" y="280" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="720" y="280" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="780" y="280" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="840" y="280" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="540" y="340" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="600" y="340" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="660" y="340" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="720" y="340" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="780" y="340" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
          <rect x="840" y="340" width="52" height="52" rx="7" fill="url(#smg)" stroke="#4f8cff" stroke-width="1.5"/>
        </g>

        <!-- 标注 -->
        <g font-size="12.5">
          <text x="176" y="470" text-anchor="middle" fill="#fbbf24" font-weight="700">NCCL 通信内核 CTA</text>
          <text x="176" y="452" text-anchor="middle" fill="#fbbf24" opacity=".8">max_ctas=min_ctas=32</text>
          <text x="386" y="452" text-anchor="middle" fill="#22d3ee" opacity=".9">DeepEP-V2</text>
          <text x="386" y="470" text-anchor="middle" fill="#22d3ee" font-weight="700">USERBUFFER_COMM_SMS</text>
          <text x="690" y="452" text-anchor="middle" fill="#4f8cff" opacity=".9">DeepGEMM / TileLang / FlashMLA</text>
          <text x="690" y="470" text-anchor="middle" fill="#4f8cff" font-weight="700">计算内核(受 limit_num_sms 约束)</text>
          <text x="1040" y="120" fill="#8ea0c2" font-size="12">NVLink / IB(RDMA)</text>
          <text x="1040" y="140" fill="#8ea0c2" font-size="11.5">集合通信数据经此处</text>
          <text x="1040" y="200" fill="#8ea0c2" font-size="12">platform.py:80-83</text>
          <text x="1040" y="220" fill="#8ea0c2" font-size="11.5">锁定 CTA 规模,</text>
          <text x="1040" y="238" fill="#8ea0c2" font-size="11.5">通信内核永不越界</text>
        </g>
        <!-- 通信链路示意 -->
        <line x1="920" y1="160" x2="1130" y2="160" stroke="#fbbf24" stroke-width="2" class="flowline"/>
        <line x1="1130" y1="150" x2="1150" y2="150" stroke="#fbbf24" stroke-width="2" class="flowline" transform="translate(-6,0)"/>
      </svg>
      <div class="cap">图 2-1 · SM 资源三分:NCCL 集合通信内核(黄色,≤ 32 CTA)、DeepEP-V2 通信内核(青色,USERBUFFER_COMM_SMS 预算)、计算内核(蓝色)。mlp.py:602 在共享专家前向期间还会用 limit_num_sms 主动收缩计算内核的 SM 数,给 combine 让路</div>
    </div>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🧮</span>DeepEP 的 SM 预算是另一套</h3>
        <p><code>userbuffer.py:86-92</code>:当 <code>DEEPINFER_USERBUFFER_COMM_SMS=0</code> 时自动推导 <code>min(num_sms, device_num_sms - compute_num_sms)</code>,其中 <code>compute_num_sms = min(32, device_num_sms//4)</code>——与 NCCL 的 32 CTA 是<strong>两个独立预算</strong>,分别约束各自的通信内核。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🚪</span>退出路径同样讲究</h3>
        <p>CUDA graph 内嵌的 NCCL 调用会持有额外 buffer(pytorch#115388),销毁顺序错误会导致 <code>destroy_process_group</code> 挂死。DeepInfer 在 <code>worker/base.py:142-148</code> 先 <code>destroy_cuda_graphs()</code>、清理 SHM,再 <code>dist.destroy_process_group()</code>;model_runner.py:633-639 有同样的注释。</p>
      </div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:18px 0 6px">2.5 NCCL 原生环境变量(runtime_config.py)</h3>
    <p style="font-size:14px;color:var(--muted);margin-bottom:8px">Worker 启动时 <code>configure_worker_environment()</code>(worker/base.py:183 调用)直接改写 NCCL 进程级行为:</p>
    <pre class="code"><span class="filepath">deepinfer/worker/runtime_config.py:29-40(节选)</span>
<span class="k">def</span> <span class="f">configure_worker_environment</span>() -> <span class="k">None</span>:
    os.environ[<span class="s">"EP_AVOID_RECORD_STREAM"</span>] = <span class="s">"1"</span>
    os.environ.<span class="f">pop</span>(<span class="s">"NCCL_NVLS_ENABLE"</span>, <span class="k">None</span>)          <span class="c"># ← 34 行:清除用户 NVLS 设置,交回默认策略</span>
    <span class="k">if</span> PLATFORM.is_gpu:
        os.environ[<span class="s">"NCCL_NO_CACHE"</span>] = <span class="s">"NCCL_WIN_STRIDE,NCCL_GIN_TYPE,NCCL_GIN_GDAKI_MAX_QP_RD_ATOMIC"</span>  <span class="c"># ← 36 行:禁用这些调优参数的缓存</span>
        os.environ[<span class="s">"NCCL_PXN_DISABLE"</span>] = <span class="s">"1"</span>        <span class="c"># ← 38 行:Disable peer access for NCCL for expert rearrangement</span>
        os.environ[<span class="s">"NCCL_CUMEM_ENABLE"</span>] = <span class="s">"1"</span>      <span class="c"># ← 39 行:启用 CUDA cuMem 分配</span>
        os.environ[<span class="s">"NCCL_GIN_ERROR_QUERY_SEC"</span>] = <span class="s">"432000"</span>  <span class="c"># ← 40 行:GIN 错误查询周期 5 天</span></pre>
    <ul class="feat">
      <li><code>NCCL_PXN_DISABLE=1</code>:注释明确写了动机——<strong>EPLB 专家重排的 P2P 走 NCCL 时禁用 PXN(peer access)</strong>,避免专家迁移路径出现非预期的跨 PCIe 中转。</li>
      <li><code>NCCL_NO_CACHE</code>:让 WinStride / GIN type / GDAKI_MAX_QP_RD_ATOMIC 三类调优参数每次建 communicator 时重新探测,不吃缓存。</li>
    </ul>
  </section>

  <!-- ============================================================ 3. 全景矩阵 ============================================================ -->
  <section id="s3">
    <h2 class="sec"><span class="num">3</span>NCCL 调用点全景矩阵</h2>
    <p class="lede">全仓库(csrc / scripts / tests / doc / vendor 逐目录 grep)核对后的<strong>完整清单</strong>。判别标准:调用显式落在 NCCL 设备组上,或操作 CUDA tensor 且组后端为 NCCL。共 18 个 NCCL 场景 + 6 个「形似 NCCL 实为 gloo/内核」的澄清项。</p>

    <h3 style="color:#fff;font-size:16px;margin-bottom:6px">3.1 启动阶段(一次性)</h3>
    <table class="tbl">
      <tr><th>#</th><th>场景</th><th>调用点(file:line)</th><th>进程组</th><th>集合操作</th><th>数据</th><th>目的</th><th>频率</th></tr>
      <tr><td>1</td><td>通信器 eager 预热</td><td><code>parallel_state.py:187</code></td><td>全部 7 张 NCCL 组</td><td><code>all_reduce</code>(SUM 默认)</td><td><code>torch.zeros(1).cuda()</code></td><td>强制建立 NCCL communicator,防 lazy init;为 deep_ep <code>_comm_ptr()</code> 兜底</td><td>每组启动一次</td></tr>
      <tr><td>2</td><td>KV 块数对齐</td><td><code>worker/base.py:265</code></td><td><code>PG.world</code></td><td><code>all_reduce(SUM)</code></td><td>int64 <code>num_gpu_blocks</code></td><td>各 rank 显存占用不同,求平均并向下取偶,统一 KV cache 块数</td><td>启动一次</td></tr>
      <tr><td>3</td><td>Engram FP8 scale 聚合</td><td><code>v4_modules/engram.py:100</code></td><td><code>PG.enp</code></td><td><code>all_gather_into_tensor</code></td><td>打包 ue8m0 的 scale factor 张量</td><td>把各 rank 分片的 n-gram embedding scale 拼成全局表,写入 EngramBuffer</td><td>模型加载一次(deepseek.py:440 触发)</td></tr>
      <tr><td>4</td><td>decode perf 曲线:graph replay 同步</td><td><code>worker/model_runner.py:597, 607</code></td><td><code>PG.ep</code></td><td><code>all_reduce</code> ×2</td><td><code>torch.zeros(1, device="cuda")</code></td><td>每档 batch size 预热 1 次 + 计时 5 次,EP 组内对齐 CUDA graph replay 完成点</td><td>启动 profiling:每档 bs × 6</td></tr>
      <tr><td>5</td><td>decode perf 曲线:跨 rank 平均</td><td><code>worker/model_runner.py:621</code></td><td><code>PG.ep</code></td><td><code>all_reduce(SUM)</code></td><td>float32[1] <code>sum_time</code>(去极值平均)</td><td>对 EP 各 rank 的 decode 时延求均值,得到统一性能曲线</td><td>启动 profiling:每档 bs × 1</td></tr>
      <tr><td>6</td><td>decode perf 缓存分发</td><td><code>worker/decode_perf_cache.py:143</code></td><td><code>PG.ep</code></td><td><code>broadcast_object_list</code></td><td>pickle 的 <code>[(bs, ms), ...]</code> 或 None</td><td>rank 0 读磁盘缓存(TTL 1h),经 NCCL 广播给 EP 全组,避免重复 profile</td><td>启动一次(设缓存目录时)</td></tr>
    </table>

    <h3 style="color:#fff;font-size:16px;margin:18px 0 6px">3.2 稳态推理(每 step / 周期性)</h3>
    <table class="tbl">
      <tr><th>#</th><th>场景</th><th>调用点(file:line)</th><th>进程组</th><th>集合操作</th><th>数据</th><th>目的</th><th>频率</th></tr>
      <tr><td>7</td><td>CP 输入元数据广播(leader 端)</td><td><code>worker/model_runner.py:212</code></td><td><code>PG.cp</code></td><td><code>broadcast</code>(经 broadcast_tensor_dict)</td><td>InputMetadata 展平后的 CUDA tensor + 非张量元数据(走 SHM)</td><td>CP rank 0 构造的输入元数据同步给 CP follower</td><td>每 step(CP&gt;1)</td></tr>
      <tr><td>8</td><td>CP 输入元数据广播(follower 端)</td><td><code>worker/model_runner.py:217</code></td><td><code>PG.cp</code></td><td>同上(接收方)</td><td>—</td><td>follower 重建 InputMetadata</td><td>每 step(CP&gt;1)</td></tr>
      <tr><td>9</td><td>采样输入广播</td><td><code>worker/model_runner.py:259, 261</code></td><td><code>PG.cp</code></td><td><code>broadcast</code>(broadcast_tensor_dict)</td><td><code>selected_token_indices / selected_prompt_indices / mtp_*</code></td><td>采样位置索引在 CP 组内对齐</td><td>每 step(CP&gt;1)</td></tr>
      <tr><td>10</td><td>CUDA Graph 内元数据广播</td><td><code>worker/cuda_graph_runner.py:65</code> → <code>input_metadata.py:167</code> → <code>communication_op.py:43</code></td><td><code>PG.cp</code></td><td><code>broadcast</code>(逐 tensor)</td><td>图内固定地址的 InputMetadata CUDA tensor 集</td><td>图捕获与每 step 重放时,驱动 rank 写入、广播到 follower 的固定地址缓冲</td><td>每 step(CP&gt;1 且走 graph)</td></tr>
      <tr><td>11</td><td>DFlash(MTP)draft 输入广播</td><td><code>models/mtp/dflash.py:365</code> → <code>communication_op.py:43</code></td><td><code>PG.cp</code></td><td><code>broadcast</code></td><td><code>last_valid_offset, golden_tokens</code></td><td>driver rank 的 draft 输入广播给 CP follower(follower 用 empty_like 接收)</td><td>每 decode step(DFlash+CP)</td></tr>
      <tr><td>12</td><td>DP 终止检测</td><td><code>engine/llm_engine.py:677</code></td><td><code>PG.dp</code>(NCCL)/ ZOS 时 <code>cpu_dp</code>(gloo)</td><td><code>all_reduce(MAX)</code></td><td>int64[1] 未完成标志</td><td>DP 各 rank 对「是否还有未完成请求」取 MAX,保证一致停机</td><td>每 engine step(DP&gt;1)</td></tr>
      <tr><td>13</td><td>EPLB 负载统计 flush</td><td><code>eplb/__init__.py:188</code></td><td><code>PG.ep</code></td><td><code>all_gather_into_tensor</code></td><td>[ep_size, interval, layers] long,本地每 step token 计数</td><td>聚合各 rank 的 MoE token 吞吐,算 moe_load_balance_ratio(avg/max)</td><td>每 128 step(默认 MOE_LB_STAT_INTERVAL)</td></tr>
      <tr><td>14</td><td>EPLB 重排前计数聚合</td><td><code>eplb/__init__.py:254</code></td><td><code>PG.ep</code></td><td><code>all_reduce</code>(SUM 默认)</td><td>[window, layers, num_logical] int,scatter_add_ 后的逻辑专家计数</td><td>窗口内全局逻辑专家 token 计数 → rebalance_experts_global 重算放置</td><td>每 REARRANGEMENT_STEP_INTERVAL(必设)step</td></tr>
      <tr><td>15</td><td>EPLB 跨机专家权重重排</td><td><code>eplb/shuffle.py:123, 132, 137</code></td><td><code>PG.ep</code></td><td><code>isend / irecv</code> 经 <code>batch_isend_irecv</code></td><td>专家权重张量按槽位切片</td><td>按新旧映射跨 rank 迁移 expert 权重(按 rank 差分桶批量收发)</td><td>每次 rearrange(跨机时)</td></tr>
      <tr><td>16</td><td>EPLB 单机重排 barrier</td><td><code>eplb/shuffle.py:192, 195</code></td><td><code>PG.ep</code></td><td><code>barrier().wait()</code> ×2</td><td>—(数据本身走 CUDA IPC 镜像)</td><td>「等所有 rank 读完上一层镜像」「等镜像就绪」两次同步</td><td>每次 rearrange(单机时,逐层 ×2)</td></tr>
      <tr><td>17</td><td>NCCL 内存采样(只读)</td><td><code>nccl_memory.py:47-53</code></td><td>全部 NCCL PG(遍历 pg_map)</td><td>无集合通信(<code>_comm_ptr()</code> + <code>memory_stats()</code>)</td><td>communicator total bytes</td><td>监控 NCCL 通信缓冲显存,变化时打日志</td><td>step 10 首采,之后每 1000 step(默认)</td></tr>
      <tr><td>18</td><td>communicator 销毁</td><td><code>worker/base.py:148</code>(配合 <code>model_runner.py:633-639</code>)</td><td>默认组</td><td><code>destroy_process_group</code></td><td>—</td><td>先销毁 CUDA graph 释放 NCCL 依赖再销毁 PG,防挂死(pytorch#115388)</td><td>进程退出一次</td></tr>
    </table>

    <h3 style="color:#fff;font-size:16px;margin:18px 0 6px">3.3 形似 NCCL、实际不是(逐个核对的澄清)</h3>
    <table class="tbl">
      <tr><th>调用点</th><th>表面印象</th><th>实际行为</th><th>证据</th></tr>
      <tr><td><code>worker/base.py:138, 140</code></td><td><code>dist.barrier()</code> ×2,像 NCCL barrier</td><td><strong>走默认 gloo 组</strong>:未传 group 参数,默认 PG 是 gloo(base.py:335)</td><td>stop() 退出路径,包裹 <code>userbuffer.close()</code></td></tr>
      <tr><td><code>distributed/shm_broadcast.py:454, 457</code></td><td><code>broadcast_object_list</code> ×2</td><td><strong>走 gloo</strong>:入参 pg 是 <code>cpu_cp_group</code>(parallel_state.py:124 传入)</td><td>引导 SHM MessageQueue:把共享内存 handle 从 writer 广播给读者</td></tr>
      <tr><td><code>worker/base.py:298-300</code></td><td>driver 向 worker 发方法调用</td><td><strong>走 SHM</strong>:<code>cp_broadcast_object((method, kwargs))</code> 经 MessageQueue</td><td>非驱动 worker 的 RPC 循环(base.py:129-133)</td></tr>
      <tr><td><code>layers/sampler.py:133, 141</code> 等</td><td>函数名 <code>gather()</code></td><td><strong>TileLang 索引内核</strong>,非 dist.gather:<code>from ...tilelang_ops.gather import gather</code></td><td>sampler.py:24 / vocab_parallel_embedding.py:6</td></tr>
      <tr><td><code>communication_op.py:24 / 28-33</code></td><td><code>dist.gather</code> / <code>dist.broadcast</code> 工具函数</td><td>代码库内<strong>当前无生产调用方</strong>(broadcast_tensor_dict 与 cp_broadcast_multi_tensor 才是被引用的入口)</td><td>全仓库 import 核对(仅 model_runner/dflash/input_metadata 三处 import)</td></tr>
      <tr><td><code>layers/sampler.py:378</code></td><td>grep 命中 "NCCL"</td><td><strong>仅注释</strong>:SO matcher 抛异常会连坐所有请求 + NCCL barrier 超时,故只判死单请求</td><td>结构化输出容错设计的动机说明</td></tr>
    </table>
    <div class="note good">另两处 grep 验证为空:<code>hugging_face/loading.py</code> 与 <code>structure_output/*</code> 均无任何 nccl/dist 引用(权重加载与结构化输出不走分布式集合通信);<code>csrc/</code>(C++ 侧)与 <code>doc/inference_deployment_qa.md</code> 亦无 NCCL 引用。<code>tests/</code> 侧的 NCCL 场景见 4.7 节。</div>
  </section>

  <!-- ============================================================ 4. 场景详解 ============================================================ -->
  <section id="s4">
    <h2 class="sec"><span class="num">4</span>重点场景逐一详解</h2>
    <p class="lede">按推理生命周期顺序展开:启动时序 → 每 step 的 CP 广播 → DP 终止检测 → EPLB 统计与重排 → 性能曲线与缓存 → 测试与 C++ 边界。</p>

    <h3 style="color:#fff;font-size:17px;margin-bottom:6px" id="s41">4.1 启动时序:NCCL communicator 的一生</h3>
    <div class="timeline">
      <div class="tl-item"><div class="tl-date">T0 · worker/base.py:328-341</div><div class="tl-body"><code>init_process_group(backend="gloo")</code> 建立<strong>默认组</strong>(CPU 消息通道,timeout 4h)。</div></div>
      <div class="tl-item"><div class="tl-date">T1 · parallel_state.py:70-118(create_process_groups)</div><div class="tl-body">读 <code>PLATFORM.distributed_backend</code>("nccl")与 <code>get_distributed_options()</code>(CTA=32),按 einops rank 重排切出 7 张设备组 + 3 张 gloo 组;所有 rank 都要参与每个 <code>dist.new_group</code>(split 组的集体语义)。</div></div>
      <div class="tl-item"><div class="tl-date">T2 · parallel_state.py:124</div><div class="tl-body">CP&gt;1 时,在 <code>cpu_cp_group</code>(gloo)上引导 SHM MessageQueue:<code>broadcast_object_list</code> 分发 shm handle(shm_broadcast.py:454/457)——<strong>gloo 只在这里出场</strong>。</div></div>
      <div class="tl-item"><div class="tl-date">T3 · parallel_state.py:173-187</div><div class="tl-body"><code>init_device_groups()</code> 对每张 NCCL/HCCL 组跑 <code>dist.all_reduce(torch.zeros(1).cuda(), group=value)</code>,eager 建立 communicator;单 rank 组也不能跳过(deep_ep <code>_comm_ptr()</code> 空指针会段错误)。</div></div>
      <div class="tl-item"><div class="tl-date">T4 · worker/base.py:203-209 → deepseek.py:440</div><div class="tl-body">加载模型与 userbuffer:EngramBuffer(经 <code>_comm_ptr()</code> 复用 T3 的 communicator)、EPBuffer/CPManager/SymmBuffer 建立;engram.py:100 在 <code>enp</code> 组上 <code>all_gather_into_tensor</code> 聚合 FP8 scale。</div></div>
      <div class="tl-item"><div class="tl-date">T5 · worker/base.py:212-268(profile_num_available_blocks)</div><div class="tl-body">profile run 后在 <strong>world 组</strong>上 <code>all_reduce(num_gpu_blocks, ReduceOp.SUM)</code>(base.py:265),各 rank KV 块数取平均并向下取偶(base.py:266)。</div></div>
      <div class="tl-item"><div class="tl-date">T6 · worker/base.py:274-288(warm_up_model)→ model_runner.py:562-631</div><div class="tl-body">CUDA graph capture;若 <code>DEEPINFER_ENABLE_MTP_VARLEN</code>,<code>profile_decode_perf()</code> 在 <strong>ep 组</strong>上跑 3 类 all_reduce(详见 4.6)。</div></div>
      <div class="tl-item"><div class="tl-date">T∞ · worker/base.py:135-151(stop)</div><div class="tl-body">gloo barrier → <code>userbuffer.close()</code> → gloo barrier → <code>destroy_cuda_graphs()</code>(先释放 NCCL-in-graph 依赖)→ <code>destroy_process_group()</code>。</div></div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:22px 0 6px" id="s42">4.2 CP 元数据广播:每 step 的 NCCL 主通道</h3>
    <p style="font-size:14px;color:var(--muted);margin-bottom:8px">Context Parallelism 下,只有 CP rank 0(driver worker)从调度器拿输入;follower 需要一份完全一致的 InputMetadata。广播按「数据形态」拆成两条通道:</p>
    <pre class="code"><span class="filepath">deepinfer/model_executor/parallel_utils/communication_op.py:51-82(broadcast_tensor_dict)</span>
<span class="k">def</span> <span class="f">broadcast_tensor_dict</span>(tensor_dict=<span class="k">None</span>, src=<span class="n">0</span>):
    <span class="s">"""Broadcast a dict across the CP group: cuda tensors via NCCL,
    everything else via shm object broadcast."""</span>              <span class="c"># ← 55 行:两条通道的分界写在 docstring 里</span>
    cp_group = PG.<span class="f">context_parallel_group</span>()
    ...
    <span class="k">for</span> key, value <span class="k">in</span> tensor_dict.<span class="f">items</span>():
        <span class="k">if</span> isinstance(value, torch.Tensor):
            <span class="k">assert</span> value.is_cuda                     <span class="c"># 只支持 CUDA tensor 走 NCCL 通道</span>
            metadata_list.<span class="f">append</span>((key, TensorMetadata(value.dtype, value.size())))
            tensors.<span class="f">append</span>(value)
        <span class="k">else</span>:
            metadata_list.<span class="f">append</span>((key, value))
    cp_broadcast_object(metadata_list)               <span class="c"># 非张量:dtype/size 元数据 → SHM 队列</span>
    ...
    cp_broadcast_multi_tensor(tensors, src)          <span class="c"># ← 81 行:CUDA tensor → NCCL broadcast(逐个,43 行)</span></pre>
    <ul class="feat">
      <li><strong>调用方一(每 step 输入):</strong><code>model_runner.py:212</code>(leader)与 <code>:217</code>(follower)——<code>broadcast_tensor_dict(input_metadata_dict, src=0)</code>,内容含 <code>is_prompt / type / run_cuda_graph / total_q / num_reqs</code> 与 InputMetadata 展平张量。</li>
      <li><strong>调用方二(采样输入):</strong><code>model_runner.py:259/261</code>——<code>selected_token_indices / selected_prompt_indices / mtp_first_token_positions / mtp_seqlens_q</code>,保证各 CP rank 的采样索引一致。</li>
      <li><strong>调用方三(图内):</strong><code>cuda_graph_runner.py:65</code> → <code>input_metadata.py:120-167</code> 的 <code>InputMetadata.broadcast()</code>——递归收集对象树中所有 CUDA tensor(<code>tensor_list</code>)与标量字段(<code>non_tensor_values</code>,走 SHM 按路径回填),张量逐个经 <code>communication_op.py:43</code> 的 <code>dist.broadcast</code> 就地写入<strong>图捕获时固定的缓冲地址</strong>,因此 broadcast 本身可被 capture/replay。</li>
      <li><strong>调用方四(DFlash):</strong><code>dflash.py:365</code> 广播 <code>last_valid_offset</code> 与 <code>golden_tokens</code>——MTP draft 的每 decode step 输入,同样是图内调用。</li>
    </ul>
    <div class="note">为什么张量不走 SHM?CUDA tensor 直连 NCCL broadcast 是<strong>零拷贝 GPU 通道</strong>,不经过 host pickle/中转;而 Python 对象(int、类型引用、路径字符串)流量小且没有设备驻留要求,SHM 队列(parallel_state.py:17-23 的 <code>cp_broadcast_object</code>)延迟更低且不占 NCCL communicator。<code>communication_op.py:41</code> 还留有 TODO:未来可用 deepep 的 multi_tensor_broadcast 替换逐张量循环。</div>

    <h3 style="color:#fff;font-size:17px;margin:22px 0 6px" id="s43">4.3 DP 终止检测:每 step 一次的 MAX</h3>
    <pre class="code"><span class="filepath">deepinfer/engine/llm_engine.py:665-679(has_unfinished_requests)</span>
<span class="k">def</span> <span class="f">has_unfinished_requests</span>(<span class="k">self</span>) -> <span class="k">bool</span>:
    <span class="k">if</span> envs.DEEPINFER_ZERO_OVERHEAD_SCHEDULING:
        dp_group = PG.<span class="f">cpu_data_parallel_group</span>(); device = <span class="s">"cpu"</span>   <span class="c"># gloo 组 + CPU tensor</span>
    <span class="k">else</span>:
        dp_group = PG.<span class="f">data_parallel_group</span>();         device = <span class="s">"cuda"</span>   <span class="c"># NCCL dp 组 + GPU tensor</span>
    unfinished = self.scheduler.<span class="f">has_unfinished_seqs</span>() <span class="k">or</span> self.<span class="f">so_builder_has_pending</span>()
    <span class="k">if</span> dp_group.size() > <span class="n">1</span>:
        unfinished = torch.<span class="f">full</span>((<span class="n">1</span>,), unfinished, dtype=torch.int64, device=device)
        dist.<span class="f">all_reduce</span>(unfinished, op=dist.ReduceOp.MAX, group=dp_group)   <span class="c"># ← 677 行</span>
        unfinished = unfinished.<span class="f">item</span>() > <span class="n">0</span>
    <span class="k">return</span> unfinished</pre>
    <ul class="feat">
      <li><strong>目的:</strong>DP 各 rank 的调度器独立调度,必须在「还有没有请求在跑」上达成一致,否则有的 rank 停了、有的还在等下一次集合通信——整组挂死。MAX 语义:只要有一个 rank 还有活,所有人继续。</li>
      <li><strong>频率:</strong>engine 主循环每 step 调一次(<code>entrypoints/llm.py:177</code>),是<strong>稳态中频率最高的 NCCL 调用</strong>。</li>
      <li><strong>ZOS 双路径:</strong>零开销调度(ZOS)模式下改走 <code>cpu_dp_group</code>(gloo)+ CPU tensor——因为 ZOS 下 step 末尾 GPU 正被异步占用,再加一次 NCCL all_reduce 就要同步 GPU;挪到 CPU/gloo 让驱动线程不碰 GPU。</li>
      <li>注意这不是「seq 长度同步」也不是「终止信号广播」,而是一个 1 元素 int64 的布尔聚合。</li>
    </ul>

    <h3 style="color:#fff;font-size:17px;margin:22px 0 6px" id="s44">4.4 EPLB:统计、聚合与专家迁移</h3>
    <div class="figure reveal">
      <svg viewBox="0 0 1180 420" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="arw2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#8ea0c2"/>
          </marker>
        </defs>
        <text x="590" y="30" text-anchor="middle" fill="#fff" font-size="15" font-weight="800">EPLB 一个重排周期内的三次 NCCL 通信(ep 组)</text>

        <!-- 步骤框 1 -->
        <rect x="30" y="70" width="250" height="120" rx="12" fill="#141d33" stroke="#fbbf24" stroke-width="1.6"/>
        <text x="155" y="98" text-anchor="middle" fill="#fbbf24" font-size="13.5" font-weight="700">① 每 step 本地累计</text>
        <text x="155" y="122" text-anchor="middle" fill="#dbe4f5" font-size="12">expert_count[num_moe_layers, local]</text>
        <text x="155" y="140" text-anchor="middle" fill="#8ea0c2" font-size="11.5">mlp dispatch 写入 recv stats</text>
        <text x="155" y="160" text-anchor="middle" fill="#8ea0c2" font-size="11.5">ExpertLoadBalancer.step 清零</text>

        <!-- 步骤框 2 -->
        <rect x="330" y="70" width="250" height="120" rx="12" fill="#141d33" stroke="#fbbf24" stroke-width="1.6"/>
        <text x="455" y="98" text-anchor="middle" fill="#fbbf24" font-size="13.5" font-weight="700">② 窗口 scatter_add_ 后聚合</text>
        <text x="455" y="122" text-anchor="middle" fill="#dbe4f5" font-size="12">dist.all_reduce(counts, ep)</text>
        <text x="455" y="140" text-anchor="middle" fill="#8ea0c2" font-size="11.5">eplb/__init__.py:254</text>
        <text x="455" y="160" text-anchor="middle" fill="#8ea0c2" font-size="11.5">→ rebalance_experts_global</text>

        <!-- 步骤框 3 -->
        <rect x="630" y="70" width="250" height="120" rx="12" fill="#141d33" stroke="#fbbf24" stroke-width="1.6"/>
        <text x="755" y="98" text-anchor="middle" fill="#fbbf24" font-size="13.5" font-weight="700">③ 专家权重迁移</text>
        <text x="755" y="122" text-anchor="middle" fill="#dbe4f5" font-size="12">batch_isend_irecv(NCCL P2P)</text>
        <text x="755" y="140" text-anchor="middle" fill="#8ea0c2" font-size="11.5">eplb/shuffle.py:123/132/137(跨机)</text>
        <text x="755" y="160" text-anchor="middle" fill="#8ea0c2" font-size="11.5">IPC 镜像 + ep.barrier(单机)</text>

        <!-- 旁路:LB 统计 -->
        <rect x="930" y="70" width="220" height="120" rx="12" fill="#141d33" stroke="#22d3ee" stroke-width="1.6"/>
        <text x="1040" y="98" text-anchor="middle" fill="#22d3ee" font-size="13.5" font-weight="700">LB 统计 flush(并行旁路)</text>
        <text x="1040" y="122" text-anchor="middle" fill="#dbe4f5" font-size="12">all_gather_into_tensor</text>
        <text x="1040" y="140" text-anchor="middle" fill="#8ea0c2" font-size="11.5">eplb/__init__.py:188</text>
        <text x="1040" y="160" text-anchor="middle" fill="#8ea0c2" font-size="11.5">每 128 step → ratio(avg,max)</text>

        <g stroke="#8ea0c2" stroke-width="1.6" marker-end="url(#arw2)">
          <line x1="280" y1="130" x2="326" y2="130" class="flowline"/>
          <line x1="580" y1="130" x2="626" y2="130" class="flowline"/>
        </g>

        <!-- 下方:P2P 分桶细节 -->
        <rect x="30" y="240" width="1120" height="150" rx="12" fill="#0e1729" stroke="#4f8cff" stroke-width="1.4"/>
        <text x="590" y="272" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">重排细节:按 (ep_rank − dst) mod P2P_GROUPS 分桶,逐桶批量 isend/irecv(shuffle.py:114-138)</text>
        <g font-size="12" fill="#8ea0c2">
          <rect x="70"  y="295" width="120" height="34" rx="8" fill="#16233f" stroke="#fbbf24" stroke-opacity=".6"/>
          <text x="130" y="317" text-anchor="middle" fill="#dbe4f5">bucket 0</text>
          <rect x="220" y="295" width="120" height="34" rx="8" fill="#16233f" stroke="#fbbf24" stroke-opacity=".6"/>
          <text x="280" y="317" text-anchor="middle" fill="#dbe4f5">bucket 1</text>
          <rect x="370" y="295" width="120" height="34" rx="8" fill="#16233f" stroke="#fbbf24" stroke-opacity=".6"/>
          <text x="430" y="317" text-anchor="middle" fill="#dbe4f5">bucket 2 …</text>
          <text x="560" y="317" fill="#8ea0c2">每桶内:P2POp(isend, weight[src], peer) + P2POp(irecv, buf[dst], peer) → batch_isend_irecv → req.wait()</text>
          <text x="560" y="345" fill="#8ea0c2">卡内可满足的槽位用本地 copy;跨卡按 _paired_sender 均分配对,收发两侧同一函数保证 P2P 两端一致</text>
          <text x="560" y="370" fill="#8ea0c2">NCCL_PXN_DISABLE=1(runtime_config.py:38)专为这条重排路径禁用 peer access</text>
        </g>
      </svg>
      <div class="cap">图 4-1 · EPLB 重排周期:ep 组上的 all_reduce(计数)→ 全局重算放置 → batch_isend_irecv 迁移权重;LB 统计 flush 是独立旁路(每 128 step)</div>
    </div>

    <pre class="code"><span class="filepath">deepinfer/model_executor/eplb/shuffle.py:113-138(跨机 P2P,节选)</span>
<span class="c"># 跨卡 p2p,按 (对端 rank 差 mod 组数) 分桶、逐桶批量收发。TODO: 这里可以考虑优先机器内通信和 broadcast</span>
p2p_buckets: list[list[dist.P2POp]] = [[] <span class="k">for</span> _ <span class="k">in</span> range(envs.DEEPINFER_REARRANGE_P2P_GROUPS)]   <span class="c"># ← 114 行</span>
<span class="k">for</span> expert, src <span class="k">in</span> <span class="f">_first_slot_per_expert</span>(origin_local):          <span class="c"># 发送方:配对到自己名下的 receivers</span>
    ...
    p2p_buckets[(ep_rank - dst) % len(p2p_buckets)].<span class="f">extend</span>(
        dist.<span class="f">P2POp</span>(dist.isend, weight[src], dist.<span class="f">get_global_rank</span>(ep, dst), ep) <span class="k">for</span> weight <span class="k">in</span> weights)   <span class="c"># ← 123 行</span>
<span class="k">for</span> expert, dst <span class="k">in</span> experts_to_recv:                                  <span class="c"># 接收方:收进 recv_buffers</span>
    ...
    p2p_buckets[(src_rank - ep_rank) % len(p2p_buckets)].<span class="f">extend</span>(
        dist.<span class="f">P2POp</span>(dist.irecv, buf[dst], dist.<span class="f">get_global_rank</span>(ep, src_rank), ep) <span class="k">for</span> buf <span class="k">in</span> recv_buffers)        <span class="c"># ← 132 行</span>
<span class="k">for</span> ops <span class="k">in</span> p2p_buckets:
    <span class="k">if</span> ops:
        <span class="k">for</span> req <span class="k">in</span> dist.<span class="f">batch_isend_irecv</span>(ops):            <span class="c"># ← 137 行:NCCL 批量 P2P</span>
            req.<span class="f">wait</span>()</pre>
    <ul class="feat">
      <li><strong>单机短路:</strong><code>eplb/__init__.py:200</code> 用 <code>PG.is_within_nvl_domain(ep_group)</code>(parallel_state.py:130-134,经 <code>deep_ep.get_physical_domain_size</code> 判断)决定是否走 IPC 镜像路径——数据不再过 NCCL,但 <strong>NCCL barrier 仍在</strong>:shuffle.py:192/195 每层两次 <code>ep.barrier().wait()</code> 保护镜像的读写时序。</li>
      <li><strong>统计通道与重排通道解耦:</strong>LB ratio 统计(188 行 all_gather)只算 avg/max 吞吐比,不触发重排;真正的重排由 <code>_update_rearrangement</code>(146-165 行)按 <code>DEEPINFER_EXPERT_REARRANGEMENT_STEP_INTERVAL</code> 触发,首个重排提前到 1/4 周期纠冷启动(121-123 行)。</li>
      <li>消息量级:all_reduce 的是 <code>[window, num_moe_layers, num_logical_experts]</code> int 计数(window 默认 100);P2P 搬运的是整个专家权重(每层每专家一个 hidden 切片),是低频大流量操作。</li>
    </ul>

    <h3 style="color:#fff;font-size:17px;margin:22px 0 6px" id="s45">4.5 KV 块数对齐:ReduceOp.SUM 而非 MAX</h3>
    <p style="font-size:14px;color:var(--muted)">内存 profile 之后,每个 rank 独立算出「我能放多少 KV block」;但 DP/EP 各 rank 的 KV cache 布局必须一致,所以取<strong>全组平均再向下取偶</strong>(base.py:266 的 <code>// world_size // 2 * 2</code>),而不是常见的取 MIN:</p>
    <pre class="code"><span class="filepath">deepinfer/worker/base.py:264-268(profile_num_available_blocks 尾部)</span>
num_gpu_blocks = torch.<span class="f">tensor</span>(num_gpu_blocks, device=<span class="s">"cuda"</span>, dtype=torch.int64)
dist.<span class="f">all_reduce</span>(num_gpu_blocks, op=dist.ReduceOp.SUM, group=PG.<span class="f">world_group</span>())   <span class="c"># ← 265 行:world 组,NCCL</span>
num_gpu_blocks = num_gpu_blocks.<span class="f">item</span>() // PG.<span class="f">world_group</span>().<span class="f">size</span>() // <span class="n">2</span> * <span class="n">2</span>
self.cache_config.num_gpu_blocks = num_gpu_blocks</pre>
    <div class="note">取平均而非 MIN 是深思熟虑的:EPLB 重排后各 rank 专家数动态变化,显存峰值也在漂移;按平均配 KV cache 让「稍紧的 rank」在 rearrangement 后仍有喘息空间,向下取偶保证 block 数为偶(对应 state cache 的双缓冲设计,base.py:241-243)。</div>

    <h3 style="color:#fff;font-size:17px;margin:22px 0 6px" id="s46">4.6 decode 性能曲线:用 NCCL all_reduce 当「同步栏杆」</h3>
    <p style="font-size:14px;color:var(--muted);margin-bottom:8px">MTP varlen 调度需要知道每个 batch size 的 decode step 耗时。<code>profile_decode_perf</code>(model_runner.py:562-631,由 <code>DEEPINFER_ENABLE_MTP_VARLEN</code> 打开)在 EP 组上用三段式 NCCL all_reduce 保证测量公平:</p>
    <pre class="code"><span class="filepath">deepinfer/worker/model_runner.py:594-623(节选)</span>
<span class="c"># Phase 1: Warmup</span>
<span class="k">for</span> _ <span class="k">in</span> range(NUM_WARMUP):
    graph.<span class="f">replay</span>()
    dist.<span class="f">all_reduce</span>(torch.<span class="f">zeros</span>(<span class="n">1</span>, device=<span class="s">"cuda"</span>), group=group)    <span class="c"># ← 597 行:EP 组内对齐 replay 完成</span>

<span class="c"># Phase 2: Timed measurements with CUDA events</span>
<span class="k">for</span> _ <span class="k">in</span> range(NUM_MEASURE):
    start_event.<span class="f">record</span>(); graph.<span class="f">replay</span>(); end_event.<span class="f">record</span>()
    dist.<span class="f">all_reduce</span>(torch.<span class="f">zeros</span>(<span class="n">1</span>, device=<span class="s">"cuda"</span>), group=group)    <span class="c"># ← 607 行:防跨 rank 拖尾污染计时</span>
    events.<span class="f">append</span>((start_event, end_event))

<span class="c"># Phase 3: Trimmed mean —— 丢弃最高/最低后求均值,再 SUM 平均到全组</span>
sum_time = torch.<span class="f">full</span>((<span class="n">1</span>,), avg_time_ms, dtype=torch.float32, device=<span class="s">"cuda"</span>)
dist.<span class="f">all_reduce</span>(sum_time, op=dist.ReduceOp.SUM, group=group)   <span class="c"># ← 621 行</span>
avg_time_ms = sum_time.<span class="f">item</span>() / group.<span class="f">size</span>()</pre>
    <ul class="feat">
      <li>两个 <code>zeros(1)</code> all_reduce 的用途是<strong>同步栏杆</strong>(全 rank 的 CUDA graph replay 都落盘后再继续),不是 EPLB 统计也不是内存信息。</li>
      <li>结果缓存:<code>DecodePerfCache</code>(decode_perf_cache.py)按 (model, batch_sizes, dp/cp/ep size) 的 sha256 存 JSON 文件,TTL 1 小时(<code>DEEPINFER_DECODE_PERF_CACHE_TTL_SEC</code>);rank 0 读写,随后 <strong>ep 组 NCCL <code>broadcast_object_list</code></strong>(decode_perf_cache.py:143)把缓存结果(或 None)分发给全组——这样多 rank 不会重复 profile。</li>
      <li>写文件只在组内 rank 0(decode_perf_cache.py:147),原子替换(.tmp → rename),清理阈值比读取 TTL 宽 2h(139 行注释:防止并发读到一半被删)。</li>
    </ul>

    <h3 style="color:#fff;font-size:17px;margin:22px 0 6px" id="s47">4.7 测试与边界:tests 中的 NCCL</h3>
    <table class="tbl">
      <tr><th>位置</th><th>内容</th><th>NCCL 角色</th></tr>
      <tr><td><code>tests/distributed/test_expert_shuffle.py:79, 100</code></td><td><code>dist.broadcast(expert_indices_tensor, 0)</code> 分发专家布局</td><td>落在<strong>默认 gloo 组</strong>上(测试经 <code>_init_distributed_environment</code> 初始化,gloo 对 CUDA broadcast 在 Linux 下可用);生产代码不走这条</td></tr>
      <tr><td><code>tests/distributed/test_expert_shuffle.py:91</code></td><td><code>dist.all_gather_object(ipc_experts_weight, ...)</code> 交换 IPC handle</td><td><strong>ep 组(NCCL)</strong>上的对象 gather</td></tr>
      <tr><td><code>tests/distributed/test_expert_shuffle.py:107</code></td><td>注释:<code># matches the production path; P2P CUDA tensors need an NCCL group</code></td><td>明确说明 <code>batch_isend_irecv</code> 的 CUDA tensor P2P 必须 NCCL 组——EPLB 重排的单测与生产同路径</td></tr>
      <tr><td><code>tests/distributed/test_expert_shuffle.py:134</code></td><td>docstring:「NCCL batched P2P shuffle: … each rank's local expert weights stay consistent with the global expert index」</td><td>200 步随机 shuffle 的不变量测试</td></tr>
      <tr><td><code>tests/distributed/test_shm_broadcast.py:90-119</code></td><td>gloo 组 + broadcast_object_list 引导 shm handle</td><td>纯 gloo/SHM,无 NCCL</td></tr>
      <tr><td><code>build.sh:17-18</code></td><td><code>pip install --no-deps --force-reinstall nvidia-nccl-cu13==2.32.3</code></td><td>构建期把 NCCL <strong>钉死在 2.32.3</strong>——仓库唯一一处 NCCL 版本约束,说明框架对 NCCL 行为(CTA config、GIN 等)有版本敏感依赖</td></tr>
      <tr><td><code>csrc/ 与 vendor/DeepEP</code></td><td>grep 无 NCCL 引用</td><td>自研 C++ 引擎侧与 DeepEP 源码侧均不直接链接/引用 NCCL API;DeepEP 只通过 <code>_comm_ptr()</code> 间接消费 PyTorch NCCL communicator</td></tr>
    </table>

    <h3 style="color:#fff;font-size:17px;margin:22px 0 6px" id="s48">4.8 「疑似 NCCL」调用点的最终裁决</h3>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">❓</span>stop() 里的两个 barrier</h3>
        <p><code>worker/base.py:138/140</code> 的 <code>dist.barrier()</code> 没有 group 参数 → <strong>默认 gloo 组</strong>。它们的作用是在 <code>userbuffer.close()</code>(销毁 DeepEP buffer,内部有自己的析构 barrier)前后保护各 rank 的销毁顺序,避免 <code>os._exit(0)</code> 跳过析构函数让驱动 worker 的 UB 卡在析构 barrier 上(136-137 行注释)。若在 NCCL 组上做同样的事,可以在 ep 组上 <code>ep.barrier().wait()</code>(eplb/shuffle.py:192 就是这么用的)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">❓</span>shm_broadcast 的 broadcast_object_list</h3>
        <p><code>distributed/shm_broadcast.py:454/457</code> 虽然是 <code>broadcast_object_list</code>,但 <code>create_from_process_group</code> 的唯一调用方传入的是 <code>cpu_cp_group</code>(parallel_state.py:124,gloo)。它把 writer 的 <strong>共享内存 handle</strong> 广播给读者,是 SHM 通道的引导步骤,不是 NCCL。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">❓</span>sampler 里的 gather</h3>
        <p><code>layers/sampler.py:133/141</code> 与 <code>vocab_parallel_embedding.py:23</code> 的 <code>gather(weight, indices)</code> 来自 <code>tilelang_ops.gather</code>(sampler.py:24)——是<strong>本卡内的索引/拷贝内核</strong>(hidden_states 按采样位置聚合),与 <code>dist.gather</code> 无关。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">❓</span>sampler.py:378 的 "NCCL"</h3>
        <p>唯一一处 sampler 中的 NCCL 字样是<strong>注释</strong>:在 CP rank 0 的采样主路径上直接 raise 会连坐所有请求并造成 NCCL barrier 超时,因此结构化输出的 matcher 异常只判死当前请求(<code>matcher.set_aborted</code>),不带崩 engine。它佐证了 CP 组集合通信的强耦合:主路径异常 = 全组挂死。</p>
      </div>
    </div>
  </section>

  <!-- ============================================================ 5. 内存监控 ============================================================ -->
  <section id="s5">
    <h2 class="sec"><span class="num">5</span>NCCL communicator 内存监控(nccl_memory.py)</h2>
    <p class="lede">NCCL 每个 communicator 都在 GPU 上持有发送/接收缓冲与内部 rendezvous 结构,在 H20/SM100 多组部署(world+local+dp+cp+ep+enp+ep_in_dp…)下动辄数 GiB。<code>NCCLMemoryStatsLogger</code> 把这笔「看不见的显存」变成每千步一条的日志。</p>

    <div class="figure reveal">
      <svg viewBox="0 0 1180 400" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="arw3" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#8ea0c2"/>
          </marker>
        </defs>
        <text x="590" y="32" text-anchor="middle" fill="#fff" font-size="15" font-weight="800">NCCLMemoryStatsLogger._collect():pg_map → _comm_ptr → memory_stats</text>

        <rect x="40" y="60" width="300" height="130" rx="12" fill="#141d33" stroke="#fbbf24" stroke-width="1.6"/>
        <text x="190" y="88" text-anchor="middle" fill="#fbbf24" font-size="13.5" font-weight="700">① 遍历 c10d._world.pg_map</text>
        <text x="190" y="112" text-anchor="middle" fill="#dbe4f5" font-size="12">进程内全部 ProcessGroup</text>
        <text x="190" y="132" text-anchor="middle" fill="#8ea0c2" font-size="11.5">dist.get_backend(group) != "nccl"</text>
        <text x="190" y="150" text-anchor="middle" fill="#8ea0c2" font-size="11.5">→ 跳过 gloo 组(nccl_memory.py:48)</text>

        <rect x="440" y="60" width="300" height="130" rx="12" fill="#141d33" stroke="#fbbf24" stroke-width="1.6"/>
        <text x="590" y="88" text-anchor="middle" fill="#fbbf24" font-size="13.5" font-weight="700">② _comm_ptr() 过滤</text>
        <text x="590" y="112" text-anchor="middle" fill="#dbe4f5" font-size="12">backend._comm_ptr() == 0 → 跳过</text>
        <text x="590" y="132" text-anchor="middle" fill="#8ea0c2" font-size="11.5">未真正建过通信的 lazy 组不计入</text>
        <text x="590" y="150" text-anchor="middle" fill="#8ea0c2" font-size="11.5">(nccl_memory.py:51)</text>

        <rect x="840" y="60" width="300" height="130" rx="12" fill="#141d33" stroke="#fbbf24" stroke-width="1.6"/>
        <text x="990" y="88" text-anchor="middle" fill="#fbbf24" font-size="13.5" font-weight="700">③ memory_stats()["total"]</text>
        <text x="990" y="112" text-anchor="middle" fill="#dbe4f5" font-size="12">读 communicator 总字节数</text>
        <text x="990" y="132" text-anchor="middle" fill="#8ea0c2" font-size="11.5">按 c10d._get_process_group_name</text>
        <text x="990" y="150" text-anchor="middle" fill="#8ea0c2" font-size="11.5">+ PG_dict 别名生成 label(53-57)</text>

        <g stroke="#8ea0c2" stroke-width="1.6" marker-end="url(#arw3)">
          <line x1="340" y1="125" x2="436" y2="125" class="flowline"/>
          <line x1="740" y1="125" x2="836" y2="125" class="flowline"/>
        </g>

        <!-- 输出日志条 -->
        <rect x="40" y="240" width="1100" height="130" rx="12" fill="#0d1424" stroke="#22d3ee" stroke-width="1.4"/>
        <text x="80" y="270" fill="#22d3ee" font-size="12.5" font-weight="700">输出(仅当与上次快照不同时,nccl_memory.py:64-65):</text>
        <text x="80" y="298" fill="#89ddff" font-size="12.5" font-family="monospace">RANK 3, GPU 7, step 1024, [nccl_memory] (total=1.912 GiB | communicator_count=7 |</text>
        <text x="80" y="320" fill="#89ddff" font-size="12.5" font-family="monospace"> groups=[0[world](0.331 GiB); 1[local](0.083 GiB); 2[dp](0.166 GiB); 3[cp](0.166 GiB); 4[ep](0.702 GiB); …])</text>
        <text x="80" y="346" fill="#5d7294" font-size="11.5" font-style="italic">(格式来自 nccl_memory.py:69-77;label = group_name[PG_dict 别名],多 tag 部署带 tag/ 前缀;数值为示意)</text>
        <g class="pulse"><circle cx="1090" cy="262" r="6" fill="#34d399"/><text x="1090" y="284" text-anchor="middle" fill="#34d399" font-size="10.5">变化才打</text></g>
      </svg>
      <div class="cap">图 5-1 · 内存采样流水线:每 step 被 log_nccl_memory() 调用(llm_engine.py:955 → stats_logger.py:432-434),但内部有三级节流:step≥10 首采 → 每 1000 步采样 → 快照变化才输出</div>
    </div>

    <pre class="code"><span class="filepath">deepinfer/model_executor/parallel_utils/nccl_memory.py:36-60(核心,节选)</span>
<span class="k">@classmethod</span>
<span class="k">def</span> <span class="f">_collect</span>(cls) -> list[tuple[<span class="k">str</span>, <span class="k">int</span>]]:
    <span class="s">"""Return (label, total_bytes) for every initialized NCCL communicator."""</span>
    <span class="k">if not</span> dist.<span class="f">is_initialized</span>():
        <span class="k">return</span> []
    c10d = dist.distributed_c10d
    aliases = cls.<span class="f">_get_group_aliases</span>()          <span class="c"># ← 27-34:从 PG_dict 反查每个组的语义别名(dp/cp/ep…)</span>
    <span class="c"># Split-share groups are counted separately because NCCL exposes no</span>
    <span class="c"># memory-manager identity for deduplication.</span>        <span class="c"># ← 44-45:NCCL 无内存管理器身份,复用组分别计数</span>
    collected = []
    <span class="k">for</span> group <span class="k">in</span> c10d._world.pg_map:               <span class="c"># ← 47:遍历所有 PG</span>
        <span class="k">if</span> dist.<span class="f">get_backend</span>(group) != <span class="s">"nccl"</span>:       <span class="c"># ← 48:只看 NCCL</span>
            <span class="k">continue</span>
        backend = group.<span class="f">_get_backend</span>(torch.<span class="f">device</span>(<span class="s">"cuda"</span>))
        <span class="k">if</span> backend.<span class="f">_comm_ptr</span>() == <span class="n">0</span>:              <span class="c"># ← 51:lazy 组(从未建链)不计</span>
            <span class="k">continue</span>
        total = backend.<span class="f">memory_stats</span>()[<span class="s">"total"</span>]  <span class="c"># ← 53:communicator 显存</span>
        group_name = c10d._get_process_group_name(group)
        group_aliases = <span class="s">"|"</span>.<span class="f">join</span>(sorted(aliases.<span class="f">get</span>(group, ())))
        label = f<span class="s">"{group_name}[{group_aliases}]"</span> <span class="k">if</span> group_aliases <span class="k">else</span> group_name
        collected.<span class="f">append</span>((label, total))
    <span class="k">return</span> collected</pre>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🎚️</span>三级节流设计</h3>
        <p>① 前 10 步不采(<code>_FIRST_SAMPLE_STEP=10</code>,nccl_memory.py:9,避开启动抖动);② 之后每 <code>DEEPINFER_NCCL_MEMORY_SAMPLE_INTERVAL_STEPS</code>(默认 1000,environ.py:190)步采一次;③ 与 <code>_last_collected</code> 完全一致则静默(nccl_memory.py:64-65)—— communicator 没新建/没增长就不刷屏。异常被捕获后按 <code>repr(error)</code> 去重输出 <code>stats_unavailable=…</code>(87-97 行)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🏷️</span>PG_dict 语义别名</h3>
        <p>PyTorch 的 PG 名只是序号("0","1"…),所以 <code>_get_group_aliases</code>(nccl_memory.py:27-34)反向遍历 <code>PG_dict[tag].__dict__</code>,把 <code>dp/cp/ep/…</code> 语义名标到 communicator 上;多 engine 部署(多 tag)时加 <code>tag/</code> 前缀消歧。日志里 <code>4[ep]</code> 一眼可读。</p>
      </div>
    </div>
    <div class="note warn"><b>工程含义:</b>NCCL 缓冲显存与「组数 × 最大消息」强相关。DeepInfer 把 NCCL 组数压到 7 张、消息规模控制在控制面量级(大流量交给 DeepEP 独立 buffer),正是为了让这一栏的 total 保持个位 GiB;一旦某部署看到 total 持续增长,通常意味着 communicator 泄漏或异常重建。</div>
  </section>

  <!-- ============================================================ 6. 选择逻辑 ============================================================ -->
  <section id="s6">
    <h2 class="sec"><span class="num">6</span>通信路径选择逻辑:NCCL vs DeepEP vs gloo vs SHM</h2>
    <p class="lede">DeepInfer 没有一个集中式的「通信路由器」,但所有调用点都遵循同一套决策准则。把准则画成决策流,可以看到每条边都能对上具体代码。</p>

    <div class="figure reveal">
      <svg viewBox="0 0 1180 620" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="arw4" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#8ea0c2"/>
          </marker>
        </defs>
        <text x="590" y="34" text-anchor="middle" fill="#fff" font-size="15" font-weight="800">一次通信的路径决策(动画流动方向 = 常见走向)</text>

        <!-- 起点 -->
        <rect x="470" y="60" width="240" height="56" rx="12" fill="#16233f" stroke="#4f8cff" stroke-width="1.8" class="pulse"/>
        <text x="590" y="94" text-anchor="middle" fill="#fff" font-size="13.5" font-weight="700">某处需要一次通信</text>

        <!-- Q1 -->
        <polygon points="590,150 750,196 590,242 430,196" fill="#141d33" stroke="#fbbf24" stroke-width="1.6"/>
        <text x="590" y="190" text-anchor="middle" fill="#fbbf24" font-size="12.5" font-weight="700">数据在 GPU 上?</text>
        <text x="590" y="208" text-anchor="middle" fill="#8ea0c2" font-size="11">CUDA tensor / 大张量</text>

        <!-- CPU 路径 -->
        <rect x="60" y="130" width="280" height="120" rx="12" fill="#141d33" stroke="#a78bfa" stroke-width="1.6"/>
        <text x="200" y="158" text-anchor="middle" fill="#a78bfa" font-size="13.5" font-weight="700">否 → gloo(CPU)</text>
        <text x="200" y="182" text-anchor="middle" fill="#dbe4f5" font-size="11.5">默认组 / cpu_dp / cpu_cp / cpu_ep_in_dp</text>
        <text x="200" y="202" text-anchor="middle" fill="#8ea0c2" font-size="11">barrier(base.py:138)、shm handle 广播、</text>
        <text x="200" y="220" text-anchor="middle" fill="#8ea0c2" font-size="11">ZOS 终止检测(llm_engine.py:668)</text>

        <!-- Q2 -->
        <polygon points="700,300 850,346 700,392 550,346" fill="#141d33" stroke="#fbbf24" stroke-width="1.6"/>
        <text x="700" y="340" text-anchor="middle" fill="#fbbf24" font-size="12.5" font-weight="700">MoE token / KV 大流量?</text>
        <text x="700" y="358" text-anchor="middle" fill="#8ea0c2" font-size="11">dispatch · combine · CP all-gather · engram fetch</text>

        <!-- DeepEP -->
        <rect x="880" y="286" width="280" height="120" rx="12" fill="#141d33" stroke="#22d3ee" stroke-width="1.6" class="pulse"/>
        <text x="1020" y="314" text-anchor="middle" fill="#22d3ee" font-size="13.5" font-weight="700">是 → DeepEP-V2(不经 NCCL)</text>
        <text x="1020" y="338" text-anchor="middle" fill="#dbe4f5" font-size="11.5">EPBuffer / CPManager(BucketBuffer) / EngramBuffer</text>
        <text x="1020" y="358" text-anchor="middle" fill="#8ea0c2" font-size="11">NVLink + RDMA 自建;num_sms=USERBUFFER_COMM_SMS</text>
        <text x="1020" y="376" text-anchor="middle" fill="#8ea0c2" font-size="11">bootstrap 经 _comm_ptr() 复用 NCCL communicator</text>

        <!-- Q3 -->
        <polygon points="560,430 716,476 560,522 404,476" fill="#141d33" stroke="#fbbf24" stroke-width="1.6"/>
        <text x="560" y="470" text-anchor="middle" fill="#fbbf24" font-size="12.5" font-weight="700">是单机且可零拷贝?</text>
        <text x="560" y="488" text-anchor="middle" fill="#8ea0c2" font-size="11">is_within_nvl_domain(PG)(parallel_state.py:130-134)</text>

        <!-- SHM/IPC -->
        <rect x="120" y="430" width="250" height="110" rx="12" fill="#141d33" stroke="#34d399" stroke-width="1.6"/>
        <text x="245" y="458" text-anchor="middle" fill="#34d399" font-size="13.5" font-weight="700">是 → SHM / IPC / SymmMem</text>
        <text x="245" y="482" text-anchor="middle" fill="#dbe4f5" font-size="11.5">EPLB 单机权重镜像(IPC)</text>
        <text x="245" y="500" text-anchor="middle" fill="#8ea0c2" font-size="11">CP 对象广播(MessageQueue)</text>
        <text x="245" y="518" text-anchor="middle" fill="#8ea0c2" font-size="11">DeepGEMM SymmBuffer(NVLink 对称内存)</text>

        <!-- NCCL -->
        <rect x="850" y="500" width="310" height="96" rx="12" fill="url(#gnccl)" stroke="#fbbf24" stroke-width="2" class="pulse"/>
        <text x="1005" y="528" text-anchor="middle" fill="#fbbf24" font-size="14" font-weight="800">否/其余 → NCCL(本档主题)</text>
        <text x="1005" y="552" text-anchor="middle" fill="#dbe4f5" font-size="11.5">7 张设备组:控制面集合通信与同步</text>
        <text x="1005" y="570" text-anchor="middle" fill="#8ea0c2" font-size="11">all_reduce / broadcast / all_gather / batch_isend_irecv / barrier</text>
        <text x="1005" y="586" text-anchor="middle" fill="#8ea0c2" font-size="11">CTA ≤ 32 · NCCL 2.32.3 · 内存可观测</text>

        <!-- 连线 -->
        <g stroke="#8ea0c2" stroke-width="1.6" marker-end="url(#arw4)">
          <line x1="590" y1="116" x2="590" y2="146" class="flowline"/>
          <line x1="430" y1="196" x2="344" y2="190" class="flowline"/>
          <line x1="705" y1="230" x2="698" y2="296" class="flowline"/>
          <line x1="852" y1="346" x2="876" y2="346" class="flowline"/>
          <line x1="620" y1="390" x2="568" y2="426" class="flowline"/>
          <line x1="404" y1="476" x2="374" y2="486" class="flowline"/>
          <line x1="668" y1="512" x2="846" y2="540" class="flowline"/>
        </g>
        <text x="300" y="420" fill="#8ea0c2" font-size="10.5" text-anchor="middle">否(P2P 不可零拷贝)</text>
      </svg>
      <div class="cap">图 6-1 · 通信路径决策流:GPU 数据 → (大流量?DeepEP : 单机零拷贝?SHM/IPC : NCCL);CPU 数据一律 gloo。每个分支都标注了真实 file:line</div>
    </div>

    <h3 style="color:#fff;font-size:17px;margin:10px 0 6px">6.1 NCCL 与 DeepEP-V2 的精确边界</h3>
    <table class="tbl">
      <tr><th>维度</th><th>NCCL</th><th>DeepEP-V2</th></tr>
      <tr><td>承担流量</td><td>控制面集合通信:元数据广播、终止检测、EPLB 统计、专家 P2P 迁移、启动同步</td><td>数据面:MoE dispatch/combine、CP all-gather(BucketBuffer)、Engram 稀疏检索</td></tr>
      <tr><td>通信实现</td><td>NCCL 2.32.3 库(<code>nvidia-nccl-cu13</code>,build.sh:17-18)</td><td>自建 NVLink + RDMA 内核(userbuffer.py 管理的 EPBuffer/CPManager/EngramBuffer)</td></tr>
      <tr><td>SM 预算</td><td><code>DEEPINFER_NCCL_NUM_SMS=32</code> → ProcessGroupNCCL max/min_ctas(platform.py:80-83)</td><td><code>DEEPINFER_USERBUFFER_COMM_SMS</code>(mlp.py:471/504,自动推导见 userbuffer.py:86-92)</td></tr>
      <tr><td>buffer 归属</td><td>NCCL communicator 内部持有,<code>memory_stats()</code> 可观测(nccl_memory.py:53)</td><td>DeepInfer 自己分配(userbuffer.py 记录 num_bytes 并打日志),不走 NCCL 缓冲</td></tr>
      <tr><td>交集点 1</td><td colspan="2"><code>init_device_groups</code>(parallel_state.py:187)eager 建立 communicator,DeepEP 经 <code>backend._comm_ptr()</code> 复用之做引导(parallel_state.py:176 注释)——<strong>NCCL 是 DeepEP 的启动依赖</strong></td></tr>
      <tr><td>交集点 2</td><td colspan="2"><code>PG.is_within_nvl_domain()</code> 用 <code>deep_ep.get_physical_domain_size(group)</code> 查询组跨越的物理域(parallel_state.py:130-134)——DeepEP 的拓扑知识反哺 NCCL 组的使用决策(EPLB 单机/跨机选择)</td></tr>
      <tr><td>交集点 3</td><td colspan="2">EPLB 单机路径:symm_mem 镜像搬运数据,但 <strong>NCCL ep 组 barrier</strong>(shuffle.py:192/195)做时序保护——两套栈在同一函数里协作</td></tr>
    </table>
    <div class="note good"><b>为什么大流量不走 NCCL?</b>MoE dispatch/combine 需要:token 级动态路由、低延迟小消息内核、与 DeepGEMM 的 contiguous layout 精确对齐、NVSHMEM 式单边 RDMA。NCCL 的集合通信原语 none of these;DeepEP-V2 直接自建 kernel(并接管 NVLink/RDMA),NCCL 只留在大粒度同步与控制面上。这就是「<strong>NCCL 管同步、DeepEP 管搬运</strong>」。</div>
  </section>

  <!-- ============================================================ 7. 环境变量 ============================================================ -->
  <section id="s7">
    <h2 class="sec"><span class="num">7</span>环境变量速查表</h2>
    <p class="lede">全部与 NCCL 相关的环境变量,按「DeepInfer 抽象层」与「NCCL 原生层」分列,均给出定义位置(environ.py / runtime_config.py)与消费位置。</p>

    <h3 style="color:#fff;font-size:16px;margin-bottom:6px">7.1 DeepInfer 侧(environ.py 集中定义)</h3>
    <table class="tbl">
      <tr><th>变量</th><th>默认</th><th>定义</th><th>消费点</th><th>含义</th></tr>
      <tr><td><code>DEEPINFER_NCCL_NUM_SMS</code></td><td>32</td><td>environ.py:115</td><td>platform.py:81-82</td><td>每张 NCCL 组的通信内核 CTA 上/下限(<code>ProcessGroupNCCL.Options.config.max_ctas/min_ctas</code>)</td></tr>
      <tr><td><code>DEEPINFER_USERBUFFER_COMM_SMS</code></td><td>未设(0=自动)</td><td>environ.py:116</td><td>userbuffer.py:86-92;mlp.py:471/504/602</td><td>DeepEP-V2 EPBuffer 通信内核 SM 数;0 时按 <code>min(num_sms, device_sms − min(32, device_sms//4))</code> 自动推导</td></tr>
      <tr><td><code>DEEPINFER_GLOO_TIMEOUT</code></td><td>14400s(4h)</td><td>environ.py:117</td><td>worker/base.py:339</td><td>默认 gloo PG 的超时;模型加载/预热阶段耗时长,给足余量</td></tr>
      <tr><td><code>DEEPINFER_NCCL_MEMORY_SAMPLE_INTERVAL_STEPS</code></td><td>1000</td><td>environ.py:190</td><td>nccl_memory.py:19-21</td><td>NCCL communicator 内存采样间隔(步);必须为正</td></tr>
      <tr><td><code>DEEPINFER_REARRANGE_P2P_GROUPS</code></td><td>1</td><td>environ.py:118</td><td>eplb/shuffle.py:114</td><td>EPLB 跨机重排的 P2P 分桶数(按 rank 差取模分桶,批量收发)</td></tr>
      <tr><td><code>DEEPINFER_EXPERT_COUNT_WINDOW_SIZE</code></td><td>100</td><td>environ.py:122</td><td>eplb/__init__.py:102-120</td><td>重排统计窗口(决定 all_reduce 的 counts 形状 [window, layers, logical])</td></tr>
      <tr><td><code>DEEPINFER_EXPERT_REARRANGEMENT_STEP_INTERVAL</code></td><td>必须显式设置</td><td>environ.py:123</td><td>eplb/__init__.py:103,146-165</td><td>两次专家重排的 step 间隔(0 = 关闭重排)</td></tr>
      <tr><td><code>DEEPINFER_MOE_LB_STAT_INTERVAL</code></td><td>128</td><td>environ.py:125</td><td>eplb/__init__.py:125-188</td><td>LB 统计 flush(all_gather_into_tensor)的间隔</td></tr>
      <tr><td><code>DEEPINFER_ZERO_OVERHEAD_SCHEDULING</code></td><td>关</td><td>environ.py:186</td><td>llm_engine.py:667-672</td><td>ZOS 时终止检测改走 gloo CPU 组,把 NCCL 从热路径摘除</td></tr>
      <tr><td><code>DEEPINFER_ENABLE_MTP_VARLEN</code></td><td>关</td><td>environ.py:138</td><td>base.py:280-281;model_runner.py:562-</td><td>打开才会跑 profile_decode_perf(ep 组三类 all_reduce)</td></tr>
      <tr><td><code>DEEPINFER_DECODE_PERF_CACHE_DIR / _TTL_SEC</code></td><td>None / 3600</td><td>environ.py:165-166</td><td>decode_perf_cache.py:34-35</td><td>decode 性能曲线磁盘缓存;设置后启动时走 NCCL broadcast_object_list 分发</td></tr>
    </table>

    <h3 style="color:#fff;font-size:16px;margin:18px 0 6px">7.2 NCCL 原生(runtime_config.py:34-40 / build.sh:17-18)</h3>
    <table class="tbl">
      <tr><th>变量</th><th>设置</th><th>位置</th><th>目的</th></tr>
      <tr><td><code>NCCL_NVLS_ENABLE</code></td><td><strong>pop(删除)</strong></td><td>runtime_config.py:34</td><td>清除外部传入的 NVLS 开关,让 NCCL 按硬件默认策略决定 NVLS(NVLS buffer 也占显存,与 NCCLMemoryStatsLogger 观测直接相关)</td></tr>
      <tr><td><code>NCCL_NO_CACHE</code></td><td><code>NCCL_WIN_STRIDE,NCCL_GIN_TYPE,NCCL_GIN_GDAKI_MAX_QP_RD_ATOMIC</code></td><td>runtime_config.py:36</td><td>禁用这三项调优参数的结果缓存,每次建 communicator 重新探测(适配不同机型混部)</td></tr>
      <tr><td><code>NCCL_PXN_DISABLE</code></td><td><code>1</code></td><td>runtime_config.py:38</td><td>注释原文:「Disable peer access for NCCL for expert rearrangement」——EPLB 专家 P2P 迁移不希望走 PXN(PCIe×NVLink)代理路径</td></tr>
      <tr><td><code>NCCL_CUMEM_ENABLE</code></td><td><code>1</code></td><td>runtime_config.py:39</td><td>NCCL 用 CUDA cuMem(VMM)分配通信缓冲,与 expandable_segments 的分配策略协同</td></tr>
      <tr><td><code>NCCL_GIN_ERROR_QUERY_SEC</code></td><td><code>432000</code>(5 天)</td><td>runtime_config.py:40</td><td>GIN(NVLink 域)错误查询周期拉满,避免常驻推理服务被周期性查询扰动</td></tr>
      <tr><td>NCCL 版本</td><td><code>nvidia-nccl-cu13==2.32.3</code></td><td>build.sh:17-18</td><td>构建期强制钉版;<code>ProcessGroupNCCL.Options.config.max_ctas/min_ctas</code> 依赖新版 NCCL config API</td></tr>
      <tr><td><code>HCCL_*</code>(NPU 对照)</td><td>BUFFSIZE=16 等</td><td>platform.py:110-115</td><td>HCCL 侧对应调优;GPU 路径不设置这些</td></tr>
    </table>
  </section>

  <!-- ============================================================ 8. 总结 ============================================================ -->
  <section id="s8">
    <h2 class="sec"><span class="num">8</span>总结</h2>
    <p class="lede">一句话:DeepInfer 里的 NCCL 是<strong>「被精确定量的控制面」</strong>——组数固定 7 张、CTA 锁 32 个、调用点全部显式传组、内存每千步可观测;而所有大流量都流向 DeepEP-V2 与 SHM/IPC。</p>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📐</span>架构层面</h3>
        <ul class="feat">
          <li>默认 PG 是 gloo;NCCL 只在 7 张显式设备组上(world/local/dp/cp/ep/ep_in_dp/enp,parallel_state.py:86-118)。</li>
          <li>每张 NCCL 组带 CTA 预算 32(platform.py:80-83),与 DeepEP 的 USERBUFFER_COMM_SMS、计算内核的 limit_num_sms 构成三段式 SM 划分。</li>
          <li>init_device_groups(parallel_state.py:187)用 1 元素 all_reduce 换取:无 lazy init 污染 + DeepEP <code>_comm_ptr()</code> 依赖兜底。</li>
        </ul>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🔁</span>稳态热路径</h3>
        <ul class="feat">
          <li>每 step:CP 组 broadcast(输入元数据 ×1 + 采样输入 ×1 + 图内/ DFlash 广播)+ DP 组终止检测 all_reduce(MAX)(llm_engine.py:677)。</li>
          <li>每 128 step:EP 组 LB 统计 all_gather_into_tensor(eplb/__init__.py:188)。</li>
          <li>每 rearrangement 周期:EP 组 all_reduce(254)+ batch_isend_irecv 权重迁移(shuffle.py:137)或 IPC + NCCL barrier(192/195)。</li>
        </ul>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🧪</span>验证方法复现</h3>
        <ul class="feat">
          <li>判据:<code>dist.*</code> 是否显式携带 NCCL 设备组;默认组与 cpu_* 组一律 gloo。</li>
          <li>grep 命中但非 NCCL 的 6 处见 3.3 节(barrier ×2、shm handle 广播 ×2、sampler gather、SO 注释)。</li>
          <li>反链:tests/distributed/test_expert_shuffle.py 是唯一 NCCL 单测(与生产同路径);csrc/、vendor/DeepEP、doc/ 均无 NCCL 直接引用。</li>
        </ul>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">🔭</span>观测与运维</h3>
        <ul class="feat">
          <li>NCCLMemoryStatsLogger:pg_map → _comm_ptr → memory_stats,别名标注,变化才输出(nccl_memory.py 全文)。</li>
          <li>退出纪律:先销毁 CUDA graph(NCCL-in-graph 依赖,pytorch#115388)再 destroy_process_group(base.py:142-148)。</li>
          <li>版本纪律:NCCL 钉死 2.32.3(build.sh:17-18);原生 env 由 configure_worker_environment 统一收口(runtime_config.py:29-40)。</li>
        </ul>
      </div>
    </div>
    <div class="note"><b>阅读建议:</b>结合 <a href="/docs/inference-engines/deepinfer/02-parallelism/">② 并行策略 DP/CP/EP+EPLB</a> 理解组拓扑,结合 <a href="/docs/inference-engines/deepinfer/10-cross-card-comm/">⑩ 跨卡通信行为全景</a> 看 DeepEP 数据面;本文的所有 file:line 均在当前仓库 HEAD 验证。</div>
  </section>

  <div class="pgnav">
    <span>DeepInfer 代码分析系列 · 由 ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/deepinfer/">← 返回系列总览</a></span>
  </div>
<script>
// 滚动显现动画
const io=new IntersectionObserver(es=>{es.forEach(e=>{if(e.isIntersecting){e.target.classList.add('on');io.unobserve(e.target)}})},{threshold:.12});
document.querySelectorAll('.reveal').forEach(el=>io.observe(el));
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item></channel></rss>