<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title>通信专题 - 标签 - 集合通信博客</title><link>https://hccl.club/tags/%E9%80%9A%E4%BF%A1%E4%B8%93%E9%A2%98/</link><description>通信专题 - 标签 - 集合通信博客</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/%E9%80%9A%E4%BF%A1%E4%B8%93%E9%A2%98/" rel="self" type="application/rss+xml"/><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><item><title>NCCL 相关 PR 合入历史全景</title><link>https://hccl.club/docs/inference-engines/deepinfer/09-nccl-pr-history/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/09-nccl-pr-history/</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 .badge.feat{background:rgba(52,211,153,.10);color:var(--good);border:1px solid rgba(52,211,153,.35)}
.fwdoc .badge.fix{background:rgba(251,191,36,.10);color:var(--warn);border:1px solid rgba(251,191,36,.35)}
.fwdoc .tcat{display:inline-block;font-size:11px;padding:2px 9px;border-radius:6px;font-weight:600;white-space:nowrap}
.fwdoc .tcat.adapt{background:rgba(167,139,250,.13);color:#c4b5fd;border:1px solid rgba(167,139,250,.35)}
.fwdoc .tcat.engram{background:rgba(34,211,238,.11);color:#67e8f9;border:1px solid rgba(34,211,238,.35)}
.fwdoc .tcat.deepep{background:rgba(79,140,255,.13);color:#93c5fd;border:1px solid rgba(79,140,255,.35)}
.fwdoc .tcat.pg{background:rgba(52,211,153,.11);color:#6ee7b7;border:1px solid rgba(52,211,153,.35)}
.fwdoc .tcat.eplb{background:rgba(251,191,36,.11);color:#fcd34d;border:1px solid rgba(251,191,36,.35)}
.fwdoc .tcat.shm{background:rgba(251,146,60,.11);color:#fdba74;border:1px solid rgba(251,146,60,.35)}
.fwdoc .tcat.hang{background:rgba(248,113,113,.11);color:#fca5a5;border:1px solid rgba(248,113,113,.35)}
.fwdoc .tcat.misc{background:rgba(148,163,184,.11);color:#cbd5e1;border:1px solid rgba(148,163,184,.35)}
.fwdoc .tcat.sched{background:rgba(244,114,182,.11);color:#f9a8d4;border:1px solid rgba(244,114,182,.35)}
.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 .tl-item.gold::before{background:var(--good);box-shadow:0 0 0 4px rgba(52,211,153,.22)}
.fwdoc .tl-day{font-size:15px;font-weight:700;color:#fff}
.fwdoc .tl-meta{font-size:11.5px;color:var(--muted);margin-left:8px}
.fwdoc .chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
.fwdoc .pchip{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;padding:3px 10px;border-radius:999px;
  border:1px solid var(--border);background:rgba(20,29,51,.7);color:var(--text);text-decoration:none;transition:all .25s}
.fwdoc .pchip:hover{border-color:var(--accent);transform:translateY(-2px)}
.fwdoc .pchip b{color:var(--accent2);font-family:Consolas,monospace;font-weight:700}
.fwdoc .pchip .st-o{color:var(--accent);font-size:10px}
.fwdoc .pchip .st-c{color:var(--bad);font-size:10px}
.fwdoc .pchip .st-m{color:var(--good);font-size:10px}
.fwdoc .pchip.hot{border-color:rgba(251,191,36,.45);background:rgba(251,191,36,.07)}
.fwdoc .pchip.gold{border-color:rgba(52,211,153,.5);background:rgba(52,211,153,.08)}
.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 .statrow{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px;margin:18px 0}
.fwdoc .stat{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);border-radius:12px;
  padding:16px 18px;text-align:center;position:relative;overflow:hidden}
.fwdoc .stat::after{content:"";position:absolute;left:0;right:0;bottom:0;height:3px;
  background:linear-gradient(90deg,var(--accent),var(--accent2));transform:scaleX(0);transform-origin:left;transition:transform 1s .3s}
.fwdoc .reveal.on .stat::after{transform:scaleX(1)}
.fwdoc .stat .v{font-size:30px;font-weight:800;color:#fff;font-family:Consolas,monospace}
.fwdoc .stat .v .u{font-size:13px;color:var(--muted);font-weight:600}
.fwdoc .stat .k{font-size:11.5px;color:var(--muted);margin-top:2px;letter-spacing:.3px}
.fwdoc .stat.g .v{color:var(--good)}
.fwdoc .stat.r .v{color:var(--bad)}
.fwdoc .stat.p .v{color:var(--purple)}
.fwdoc .stat.c .v{color:var(--accent2)}
.fwdoc .stat.w .v{color:var(--warn)}
.fwdoc .barchart{display:flex;align-items:stretch;gap:8px;height:240px;padding:8px 4px 0}
.fwdoc .bcol{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;gap:6px;min-width:0}
.fwdoc .bval{font-size:10.5px;color:var(--muted);font-family:Consolas,monospace;white-space:nowrap}
.fwdoc .bval b{color:var(--accent2)}
.fwdoc .bpair{display:flex;gap:3px;align-items:flex-end;height:170px;width:100%;justify-content:center}
.fwdoc .bar{width:16px;border-radius:5px 5px 0 0;height:0;transition:height 1.4s cubic-bezier(.2,.7,.3,1);position:relative}
.fwdoc .bar.total{background:linear-gradient(180deg,rgba(79,140,255,.85),rgba(79,140,255,.15));box-shadow:0 0 12px rgba(79,140,255,.25)}
.fwdoc .bar.comm{background:linear-gradient(180deg,rgba(34,211,238,.95),rgba(34,211,238,.15));box-shadow:0 0 12px rgba(34,211,238,.3)}
.fwdoc .reveal.on .bar{height:var(--h)}
.fwdoc .bday{font-size:10px;color:var(--muted);font-family:Consolas,monospace;white-space:nowrap}
.fwdoc .blegend{display:flex;gap:18px;justify-content:center;margin-top:10px;font-size:11.5px;color:var(--muted)}
.fwdoc .blegend i{display:inline-block;width:11px;height:11px;border-radius:3px;vertical-align:-1px;margin-right:5px}
.fwdoc .blegend .l1{background:linear-gradient(180deg,rgba(79,140,255,.85),rgba(79,140,255,.3))}
.fwdoc .blegend .l2{background:linear-gradient(180deg,rgba(34,211,238,.95),rgba(34,211,238,.3))}
.fwdoc .stackbar{display:flex;height:26px;border-radius:8px;overflow:hidden;border:1px solid var(--border);margin:10px 0 6px}
.fwdoc .stackbar div{display:flex;align-items:center;justify-content:center;font-size:10.5px;font-weight:700;color:#0b1020;
  width:0;transition:width 1.4s cubic-bezier(.2,.7,.3,1);white-space:nowrap}
.fwdoc .reveal.on .stackbar div{width:var(--w)}
.fwdoc .stackbar .s-open{background:linear-gradient(90deg,#4f8cff,#6ea0ff)}
.fwdoc .stackbar .s-closed{background:linear-gradient(90deg,#f87171,#fca5a5)}
.fwdoc .stackbar .s-merged{background:linear-gradient(90deg,#34d399,#6ee7b7)}
.fwdoc .qb{animation:fw-bob 4.2s ease-in-out infinite;transform-box:fill-box;transform-origin:center}
@keyframes fw-bob{0%,100%{transform:translateY(0)}50%{transform:translateY(-6px)}}
.fwdoc .qring{animation:fw-qpulse 2.2s ease-in-out infinite;transform-box:fill-box;transform-origin:center}
@keyframes fw-qpulse{0%,100%{opacity:.25;r:20}50%{opacity:.9;r:24}}
.fwdoc .qtext{fill:#0b1020;font-size:9.5px;font-weight:800;font-family:Consolas,monospace;text-anchor:middle;dominant-baseline:central;pointer-events:none}
.fwdoc .qlabel{font-size:13px;font-weight:700;fill:#fff}
.fwdoc .qsub{font-size:10.5px;fill:#8ea0c2}
.fwdoc .qaxis{stroke:#263352;stroke-width:1.5}
.fwdoc .qaxislabel{font-size:11px;fill:#8ea0c2;letter-spacing:1px}
.fwdoc .qlegend{font-size:10.5px;fill:#8ea0c2}
.fwdoc .qdot{width:10px;height:10px;border-radius:3px;display:inline-block;vertical-align:-1px;margin:0 5px 0 12px}
.fwdoc .prbox{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);border-radius:var(--radius);
  padding:24px 26px;margin:18px 0;position:relative;overflow:hidden}
.fwdoc .prbox::before{content:"";position:absolute;left:0;top:0;bottom:0;width:4px;background:linear-gradient(180deg,var(--accent),var(--purple))}
.fwdoc .prbox.gold::before{background:linear-gradient(180deg,var(--good),var(--accent2))}
.fwdoc .prbox.dead::before{background:linear-gradient(180deg,var(--bad),var(--purple))}
.fwdoc .prhead{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:10px}
.fwdoc .prhead .prno{font-size:20px;font-weight:800;color:#fff;font-family:Consolas,monospace}
.fwdoc .prhead .prtitle{font-size:14.5px;color:var(--text);font-weight:600}
.fwdoc .prbox h4{font-size:14px;color:var(--accent2);margin:14px 0 6px;letter-spacing:.5px}
.fwdoc .prbox p{font-size:13.5px;color:var(--text);margin:7px 0}
.fwdoc .prbox p.dim{color:var(--muted)}
.fwdoc .files{display:flex;flex-wrap:wrap;gap:7px;margin-top:10px}
.fwdoc .files .filepath{margin-bottom:0}
.fwdoc .mini-tbl{width:100%;border-collapse:collapse;font-size:12.5px;margin:10px 0}
.fwdoc .mini-tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:7px 10px;font-size:11.5px}
.fwdoc .mini-tbl td{padding:6px 10px;border-top:1px solid var(--border);color:var(--text)}
.fwdoc .mini-tbl td:first-child{font-family:Consolas,monospace;color:var(--accent2);white-space:nowrap}
.fwdoc .anchor-flow{display:flex;align-items:center;gap:10px;flex-wrap:wrap;justify-content:center;margin:14px 0}
.fwdoc .anchor-flow .fnode{background:rgba(20,29,51,.85);border:1px solid var(--border);border-radius:10px;padding:8px 14px;
  font-size:12px;color:var(--text);text-align:center;transition:all .3s}
.fwdoc .anchor-flow .fnode:hover{border-color:var(--accent);transform:translateY(-3px)}
.fwdoc .anchor-flow .fnode b{display:block;color:#fff;font-size:12.5px;font-family:Consolas,monospace}
.fwdoc .anchor-flow .arr{color:var(--accent2);font-size:16px;animation:fw-flowx 1.4s ease-in-out infinite}
@keyframes fw-flowx{0%,100%{transform:translateX(0);opacity:.5}50%{transform:translateX(4px);opacity:1}}
/* ===== 导入面板附加样式 ===== */
.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>仓库 PR 全景与通信相关 PR 识别</h2>
    <p class="lede">DeepInfer 于 2026-10-20 开源,本地 git 历史仅 5 个提交,但 GitHub 上社区贡献极其活跃。本章先给出仓库全量统计,再说明「NCCL/通信相关」的识别口径与总量。</p>

    <div class="statrow reveal">
      <div class="stat c"><div class="v" data-count="224">0</div><div class="k">PR 总数(#23~#256)</div></div>
      <div class="stat"><div class="v" data-count="203">0</div><div class="k">待评审 open</div></div>
      <div class="stat r"><div class="v" data-count="19">0</div><div class="k">已关闭 closed</div></div>
      <div class="stat g"><div class="v" data-count="2">0</div><div class="k">已合入 merged</div></div>
      <div class="stat w"><div class="v" data-count="42">0</div><div class="k">NCCL/通信相关</div></div>
      <div class="stat p"><div class="v" data-count="34">0</div><div class="k">通信 PR 贡献者</div></div>
    </div>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📊</span>全仓库状态分布:合入率不足 1%</h3>
        <p>224 个 PR 中,仅 <b>#157</b>(Bump DeepEP)与 <b>#218</b>(环境变量严格校验)被合入——而且这两个 PR 恰好都属于通信/配置域。开源后 11 天内,DeepSeek 官方对社区贡献保持了极其严格的评审节奏:大特性(SM90/ROCm/SM120 平台移植、Engram 替代路径)全部处于 open 待评审状态。</p>
        <div class="stackbar">
          <div class="s-open" style="--w:90.6%">open 203</div>
          <div class="s-closed" style="--w:8.5%">closed 19</div>
          <div class="s-merged" style="--w:0.9%"></div>
        </div>
        <p style="font-size:11.5px">merged 仅 0.9%(条宽按比例,绿色段为 2 个 PR)。closed 的 19 个中 9 个与通信相关(详见第 4 章关闭原因分析)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🔍</span>识别口径:如何界定「NCCL/通信相关」</h3>
        <p>对 224 个 PR 的 <code>title + body</code> 做词边界精确匹配(nccl / hccl / rccl / gloo / collective / allreduce / engram / rdma / nvlink / deepep / eplb / shm / broadcast / topology / distributed / hang / deadlock / rank …),再逐个人工复核正文,剔除误命中(如 "engineering" 命中 "gin"、"change" 命中 "hang"、"shared-pool" 属显存池而非 IPC)。</p>
        <p>最终锁定 <b>42 个 PR</b>(占全仓 18.8%),覆盖 9 大主题:通信库适配 12、Engram 通信路径 5、SHM/IPC 7、DeepEP 版本 3、进程组与启动拓扑 4、EPLB 3、挂死与配置 2、Engram 周边 5、调度耦合 1。</p>
      </div>
    </div>

    <div class="figure reveal">
      <div style="display:flex;justify-content:space-between;align-items:baseline;flex-wrap:wrap;gap:8px">
        <div style="font-size:14.5px;color:#fff;font-weight:700">📦 每日 PR 创建量(2026-10-20 开源 → 10-30)</div>
        <div style="font-size:11.5px;color:var(--muted)">青色 = 其中 NCCL/通信相关 · 合计 224 / 42</div>
      </div>
      <div class="barchart">
        <div class="bcol"><div class="bval">98<br><b>15</b></div><div class="bpair"><div class="bar total" style="--h:100%"></div><div class="bar comm" style="--h:15.3%"></div></div><div class="bday">10-20</div></div>
        <div class="bcol"><div class="bval">73<br><b>11</b></div><div class="bpair"><div class="bar total" style="--h:74.5%"></div><div class="bar comm" style="--h:11.2%"></div></div><div class="bday">10-21</div></div>
        <div class="bcol"><div class="bval">15<br><b>9</b></div><div class="bpair"><div class="bar total" style="--h:15.3%"></div><div class="bar comm" style="--h:9.2%"></div></div><div class="bday">10-22</div></div>
        <div class="bcol"><div class="bval">7<br><b>1</b></div><div class="bpair"><div class="bar total" style="--h:7.1%"></div><div class="bar comm" style="--h:1.1%"></div></div><div class="bday">10-23</div></div>
        <div class="bcol"><div class="bval">2<br><b>0</b></div><div class="bpair"><div class="bar total" style="--h:2.1%"></div><div class="bar comm" style="--h:0.4%"></div></div><div class="bday">10-24</div></div>
        <div class="bcol"><div class="bval">5<br><b>0</b></div><div class="bpair"><div class="bar total" style="--h:5.1%"></div><div class="bar comm" style="--h:0.4%"></div></div><div class="bday">10-25</div></div>
        <div class="bcol"><div class="bval">7<br><b>2</b></div><div class="bpair"><div class="bar total" style="--h:7.1%"></div><div class="bar comm" style="--h:2.1%"></div></div><div class="bday">10-26</div></div>
        <div class="bcol"><div class="bval">4<br><b>1</b></div><div class="bpair"><div class="bar total" style="--h:4.1%"></div><div class="bar comm" style="--h:1.1%"></div></div><div class="bday">10-27</div></div>
        <div class="bcol"><div class="bval">4<br><b>1</b></div><div class="bpair"><div class="bar total" style="--h:4.1%"></div><div class="bar comm" style="--h:1.1%"></div></div><div class="bday">10-28</div></div>
        <div class="bcol"><div class="bval">1<br><b>1</b></div><div class="bpair"><div class="bar total" style="--h:1.1%"></div><div class="bar comm" style="--h:1.1%"></div></div><div class="bday">10-29</div></div>
        <div class="bcol"><div class="bval">8<br><b>1</b></div><div class="bpair"><div class="bar total" style="--h:8.2%"></div><div class="bar comm" style="--h:1.1%"></div></div><div class="bday">10-30</div></div>
      </div>
      <div class="blegend">
        <span><i class="l1"></i>全仓 PR 创建量</span>
        <span><i class="l2"></i>NCCL/通信相关</span>
        <span style="color:#5a6b92">开源首日 98 个 PR 中 15 个与通信相关(15.3%)</span>
      </div>
      <div class="cap">图 1-1 · PR 创建时间分布(CSS 生长动画)。开源前三天贡献了 224 个 PR 中的 186 个(83%),通信相关 PR 的分布与之同步(35/42)。</div>
    </div>

    <div class="grid c3">
      <div class="card reveal">
        <h3><span class="ico">✅</span>唯二合入:都是通信/配置域小 PR</h3>
        <p><b>#157</b>:DeepEP 子模块升级(2 文件,+3/-5),2026-10-21 合入,仓库<b>首个</b>合入 PR;<b>#218</b>:<code>environ.py</code> 布尔环境变量严格解析(1 文件,+8/-1),10-25 合入。两者均由 DeepSeek 成员(wx-csy / Inference1)提交。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧑‍🤝‍🧑</span>通信 PR 贡献者:34 人,高度分散</h3>
        <p>42 个 PR 来自 34 位贡献者,仅 <b>vivienfanghuagood</b>(ROCm 后端 6 个)、Blade-of-Mikasa、Afloat16、RichealYoung 各 2 个,其余 30 人各 1 个。单人贡献 6 个的 vivienfanghuagood 同时也是全仓 top 贡献者之一。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🧭</span>特性 vs 修复:20 : 22 基本对半</h3>
        <p>42 个通信 PR 中,「特性支持」(平台移植、Engram 替代路径、vendor-neutral 化等)20 个,「问题解决」(挂死、导入崩溃、安全加固、均衡错配等)22 个。问题解决类全部为社区自发排查,其中 3 个挂死类 PR(#57/#50/#48)复现路径完整、带 CPU/Gloo 回归测试。</p>
      </div>
    </div>
  </section>

  <!-- ================= 2 时间线 ================= -->
  <section id="s2">
    <h2 class="sec"><span class="num">2</span>动画时间线:11 天合入史</h2>
    <p class="lede">从 2026-10-20 开源到 10-30,通信相关 PR 的提交与合入节奏。绿色节点 = 合入事件;<span class="badge nccl">HOT</span> 标记 Engram/NCCL 核心路径 PR。</p>

    <div class="timeline">
      <div class="tl-item reveal">
        <div class="tl-date">2026-10-20(开源首日 · 全仓 98 PR · 通信 15)</div>
        <div class="tl-body">
          <span class="tl-day">开源即涌入:启动拓扑与挂死修复打头阵</span>
          <div class="chips">
            <span class="pchip"><b>#40</b> 拓扑校验 <span class="st-c">closed</span></span>
            <span class="pchip"><b>#45</b> MQ 超时 <span class="st-o">open</span></span>
            <span class="pchip"><b>#50</b> 空 DP 分片挂死 <span class="st-o">open</span></span>
            <span class="pchip"><b>#57</b> DP launcher 挂死 <span class="st-o">open</span></span>
            <span class="pchip"><b>#64</b> 设备可见性中立化 <span class="st-o">open</span></span>
            <span class="pchip"><b>#70</b> Engram 跨 shard <span class="st-o">open</span></span>
            <span class="pchip"><b>#76</b> shm unlink <span class="st-o">open</span></span>
            <span class="pchip"><b>#81</b> IPv6 URL <span class="st-o">open</span></span>
            <span class="pchip"><b>#92</b> SM90 H20 <span class="st-o">open</span></span>
            <span class="pchip hot"><b>#99</b> NVLink Engram fetch <span class="st-o">open</span></span>
            <span class="pchip"><b>#106</b> Engram 设备拓宽 <span class="st-o">open</span></span>
            <span class="pchip"><b>#107</b> EPLB 窗口 <span class="st-o">open</span></span>
            <span class="pchip"><b>#38</b> 共享池分配 <span class="st-c">closed</span></span>
            <span class="pchip"><b>#46</b> Ascend 910C RFC <span class="st-o">open</span></span>
            <span class="pchip"><b>#48</b> 共享池死锁 <span class="st-o">open</span></span>
          </div>
          <p class="dim" style="font-size:12px;margin-top:6px">首日即出现本轮最重磅的 Engram 替代方案 #99(NVLink 集合版 fetch);#40/#38 属 Blade-of-Mikasa 早期快速修复批次,后均被关闭。</p>
        </div>
      </div>

      <div class="tl-item reveal">
        <div class="tl-date">2026-10-21(全仓 73 PR · 通信 11)</div>
        <div class="tl-body">
          <span class="tl-day">平台移植集中爆发 + 仓库首个合入 PR</span>
          <div class="chips">
            <span class="pchip"><b>#126</b> perf cache key <span class="st-o">open</span></span>
            <span class="pchip"><b>#128</b> 广播前崩溃 <span class="st-o">open</span></span>
            <span class="pchip hot"><b>#138</b> SM120+PyTorch collectives <span class="st-o">open</span></span>
            <span class="pchip"><b>#148</b> SM90 Hopper <span class="st-o">open</span></span>
            <span class="pchip gold"><b>#157</b> DeepEP bump <span class="st-m">MERGED</span></span>
            <span class="pchip"><b>#158</b> shm pickle <span class="st-o">open</span></span>
            <span class="pchip"><b>#179</b> DeepEP import guard <span class="st-c">closed</span></span>
            <span class="pchip"><b>#180</b> SM90 平台层 <span class="st-o">open</span></span>
            <span class="pchip"><b>#186</b> 构建前置文档 <span class="st-o">open</span></span>
            <span class="pchip"><b>#191</b> EPLB 平局 <span class="st-o">open</span></span>
            <span class="pchip"><b>#193</b> Ascend 910B <span class="st-o">open</span></span>
          </div>
          <p class="dim" style="font-size:12px;margin-top:6px"><b>04:55 UTC,#157 合入</b>——DeepEP 子模块升级到 f6aa38fe,成为仓库历史上第一个被合入的 PR(本地 git 提交 <code>9bd9cf2</code>)。</p>
        </div>
      </div>

      <div class="tl-item reveal">
        <div class="tl-date">2026-10-22(全仓 15 PR · 通信 9)</div>
        <div class="tl-body">
          <span class="tl-day">ROCm 五连发与 UVA Engram</span>
          <div class="chips">
            <span class="pchip hot"><b>#200</b> UVA Engram fetch <span class="st-o">open</span></span>
            <span class="pchip"><b>#201</b> ROCm 单 PR <span class="st-o">open</span></span>
            <span class="pchip"><b>#202</b> ROCm 1/5 <span class="st-c">closed</span></span>
            <span class="pchip"><b>#203</b> ROCm 2/5 <span class="st-c">closed</span></span>
            <span class="pchip"><b>#204</b> ROCm 3/5 <span class="st-c">closed</span></span>
            <span class="pchip hot"><b>#205</b> ROCm 4/5 通信层 <span class="st-c">closed</span></span>
            <span class="pchip"><b>#206</b> ROCm 5/5 文档 <span class="st-c">closed</span></span>
            <span class="pchip"><b>#209</b> map_engram 越界 <span class="st-o">open</span></span>
            <span class="pchip"><b>#212</b> EPLB 峰值削减 <span class="st-o">open</span></span>
          </div>
          <p class="dim" style="font-size:12px;margin-top:6px">vivienfanghuagood 提交 ROCm 五部曲(#202~#206)后又以单 PR #201 整合重发,五个拆分 PR 随即关闭(合并评审);#200 揭出 GDAKI 静默 CPU proxy 回退问题。</p>
        </div>
      </div>

      <div class="tl-item reveal">
        <div class="tl-date">2026-10-23(全仓 7 PR · 通信 1)</div>
        <div class="tl-body">
          <span class="tl-day">第二个(也是最后一个)合入 PR 出现</span>
          <div class="chips">
            <span class="pchip gold"><b>#218</b> 环境变量严格校验 <span class="st-m">open→merged</span></span>
          </div>
          <p class="dim" style="font-size:12px;margin-top:6px">Inference1(DeepSeek)提交 <code>_bool()</code> 严格解析:此后 <code>EP_DISABLE_GIN</code>、<code>DEEPINFER_ENGRAM_*</code> 等通信开关拼错将显式报错而非静默视为 true。</p>
        </div>
      </div>

      <div class="tl-item gold reveal">
        <div class="tl-date">2026-10-25 · 11:59 UTC</div>
        <div class="tl-body">
          <span class="tl-day" style="color:var(--good)">🟢 #218 合入(本地 git 提交 <code>5537415</code>)</span>
          <p class="dim" style="font-size:12px">至此仓库 224 个 PR 中仅有的 2 个合入全部落定,且都与通信/配置域相关。此后再无任何 PR 被合入。</p>
        </div>
      </div>

      <div class="tl-item reveal">
        <div class="tl-date">2026-10-26(全仓 7 PR · 通信 2)</div>
        <div class="tl-body">
          <span class="tl-day">重复修复与调度耦合测试</span>
          <div class="chips">
            <span class="pchip"><b>#232</b> 与 #106 同根因 <span class="st-o">open</span></span>
            <span class="pchip"><b>#236</b> mtp_varlen 零速率 <span class="st-o">open</span></span>
          </div>
        </div>
      </div>

      <div class="tl-item reveal">
        <div class="tl-date">2026-10-27(全仓 4 PR · 通信 1)</div>
        <div class="tl-body">
          <span class="tl-day">Engram QP 平台期问题浮出水面(后被关闭)</span>
          <div class="chips">
            <span class="pchip hot"><b>#243</b> Engram buffer 解耦 <span class="st-c">closed</span></span>
          </div>
          <p class="dim" style="font-size:12px;margin-top:6px">ShawnZL 用 A/B 实验证明 8→25 QP 可换 +10.7% prefill 吞吐;关闭原因未公开说明,但其主题被两天后的 #248 以环境变量覆盖的方式接力。</p>
        </div>
      </div>

      <div class="tl-item reveal">
        <div class="tl-date">2026-10-28(全仓 4 PR · 通信 1)</div>
        <div class="tl-body">
          <span class="tl-day">LocalEngram:对称内存方案登场</span>
          <div class="chips">
            <span class="pchip hot"><b>#246</b> LocalEngram NVLink <span class="st-o">open</span></span>
          </div>
        </div>
      </div>

      <div class="tl-item reveal">
        <div class="tl-date">2026-10-29(全仓 1 PR · 通信 1)</div>
        <div class="tl-body">
          <span class="tl-day">当天全仓唯一 PR 也是通信域:RDMA QP 调优</span>
          <div class="chips">
            <span class="pchip hot"><b>#248</b> Engram RDMA QP 覆盖 <span class="st-o">open</span></span>
          </div>
        </div>
      </div>

      <div class="tl-item reveal">
        <div class="tl-date">2026-10-30(全仓 8 PR · 通信 1)</div>
        <div class="tl-body">
          <span class="tl-day">月末:共享内存池自旋问题的第二波修复</span>
          <div class="chips">
            <span class="pchip"><b>#251</b> 超容量分配拒绝 <span class="st-o">open</span></span>
          </div>
          <p class="dim" style="font-size:12px;margin-top:6px">与 10-20 被关闭的 #38 同主题(共享内存池对永远放不下的分配无限自旋),以更完整的论证重提。</p>
        </div>
      </div>
    </div>
  </section>

  <!-- ================= 3 全景矩阵 ================= -->
  <section id="s3">
    <h2 class="sec"><span class="num">3</span>全景矩阵:主题分类 × 状态</h2>
    <p class="lede">42 个 NCCL/通信相关 PR 的完整清单,按 9 大主题分组。规模 = 变更文件数与增删行数(取自 GitHub API)。</p>

    <h3 style="color:#fff;font-size:15px;margin:20px 0 4px">3.1 状态总览</h3>
    <div class="grid c3" style="margin-bottom:16px">
      <div class="card reveal"><h3><span class="ico">🟦</span>待评审 open:31 个(73.8%)</h3><p>含全部平台移植大特性与 Engram 替代路径,等待官方评审。</p></div>
      <div class="card reveal d1"><h3><span class="ico">🟥</span>已关闭 closed:9 个(21.4%)</h3><p>#202~#206 合并入 #201;#179 作者侧主动关闭;#38/#40/#243 无公开说明。</p></div>
      <div class="card reveal d2"><h3><span class="ico">🟩</span>已合入 merged:2 个(4.8%)</h3><p>#157(DeepEP bump)与 #218(环境变量校验),均为小体量关键修复。</p></div>
    </div>

    <h3 style="color:#fff;font-size:15px;margin:26px 0 4px">3.2 完整矩阵(42 行)</h3>
    <div class="reveal">
    <table class="tbl">
      <tr><th style="width:52px">PR</th><th>标题</th><th style="width:76px">状态</th><th style="width:104px">主题</th><th style="width:58px">类型</th><th style="width:118px">规模</th><th style="width:34%">一句话内容</th></tr>
      <!-- A 通信库适配 -->
      <tr><td><b>#138</b></td><td>Enable experimental SM120 inference with FlashInfer and PyTorch collectives</td><td><span class="badge open">open</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>65 文件 +4283/-105</td><td>SM120 消费卡上以 PyTorch collectives 实现 CP/Engram/专家交换,摆脱 DeepEP 依赖</td></tr>
      <tr><td><b>#201</b></td><td>Add AMD ROCm backend: DeepSeek-V4.1-Flash on MI350X/MI355X</td><td><span class="badge open">open</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>67 文件 +9766/-24</td><td>ROCm 完整后端,RCCL 经 nccl backend,整合原 #202~#206 五连发</td></tr>
      <tr><td><b>#202</b></td><td>ROCm 1/5: platform and TileLang HIP backend</td><td><span class="badge closed">closed</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>17 文件 +961/-9</td><td>PlatformROCm + KFD 拓扑探测 + TileLang HIP 补丁(630 行);合并入 #201</td></tr>
      <tr><td><b>#203</b></td><td>ROCm 2/5: dense GEMM kernels for the deep_gemm API</td><td><span class="badge closed">closed</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>35 文件 +3363/-14</td><td>deep_gemm API 的 dense GEMM HIP 内核;合并入 #201</td></tr>
      <tr><td><b>#204</b></td><td>ROCm 3/5: sparse attention, indexer and top-k</td><td><span class="badge closed">closed</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>47 文件 +5955/-17</td><td>稀疏注意力 / indexer / top-k 的 ROCm 移植;合并入 #201</td></tr>
      <tr><td><b>#205</b></td><td>ROCm 4/5: MoE, expert-parallel exchange, Engram and CP buffers</td><td><span class="badge closed">closed</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>62 文件 +9036/-23</td><td>EPBuffer/EngramBuffer/BucketBuffer 改走 torch 对称内存 + async RCCL;合并入 #201</td></tr>
      <tr><td><b>#206</b></td><td>ROCm 5/5: documentation and results</td><td><span class="badge closed">closed</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>64 文件 +9121/-23</td><td>ROCm 文档与端到端结果(与 4/5 同栈);合并入 #201</td></tr>
      <tr><td><b>#92</b></td><td>SM90 (Hopper) support: DeepSeek-V4.1-Flash end to end on 8x/4x H20-3e</td><td><span class="badge open">open</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>56 文件 +9159/-72</td><td>Hopper 端到端:attention DP/CP + MoE EP 全链路 + CUDA graphs</td></tr>
      <tr><td><b>#148</b></td><td>[Feat] Add NVIDIA Hopper (SM90) Support.</td><td><span class="badge open">open</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>22 文件 +985/-40</td><td>H100/H200/H20 支持,验证 EP/CP 通信与 eager EP8;Engram GIN 验证进行中</td></tr>
      <tr><td><b>#180</b></td><td>feat(platform): add SM90 (Hopper) support for DeepInfer inference</td><td><span class="badge open">open</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>48 文件 +4562/-78</td><td>SM90 平台层:替换 Blackwell 假设四层中的三层(#235 叠加其上)</td></tr>
      <tr><td><b>#46</b></td><td>[RFC] Add Ascend 910C support</td><td><span class="badge open">open</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>1 文件 +30/-0</td><td>910C/A3 RFC:MoE/Engram/设备间通信适配路线图(W8A8, CANN 9.2)</td></tr>
      <tr><td><b>#193</b></td><td>Ascend 910B: DeepSeek-V4-0731 end-to-end reference runner (8x910B4)</td><td><span class="badge open">open</span></td><td><span class="tcat adapt">通信库适配</span></td><td><span class="badge feat">特性</span></td><td>4 文件 +705/-0</td><td>910B 八卡 EP8 参考运行器(独立示例,非生产引擎)</td></tr>
      <!-- B Engram 路径 -->
      <tr><td><b>#99</b></td><td>Add an NVLink Engram fetch for single-node runs without NCCL GIN</td><td><span class="badge open">open</span></td><td><span class="tcat engram">Engram 路径</span></td><td><span class="badge feat">特性</span></td><td>16 文件 +485/-7</td><td>NVLinkEngramBuffer:all_to_all_single 集合替代 NCCL GIN 单边 get,无 RDMA 单节点可跑</td></tr>
      <tr><td><b>#200</b></td><td>Add opt-in UVA Engram fetch for single-node deployments</td><td><span class="badge open">open</span></td><td><span class="tcat engram">Engram 路径</span></td><td><span class="badge feat">特性</span></td><td>5 文件 +304/-1</td><td>UVA 读 pinned host 表;诊断并绕开 GDAKI 静默 CPU proxy 回退(7.95→67-90 Mpps)</td></tr>
      <tr><td><b>#246</b></td><td>feat: add opt-in LocalEngram fetch over NVLink</td><td><span class="badge open">open</span></td><td><span class="tcat engram">Engram 路径</span></td><td><span class="badge feat">特性</span></td><td>5 文件 +526/-6</td><td>LocalEngramBuffer:GPU 对称内存 + NVLink peer domain,性能达官方曲线 94%~101%</td></tr>
      <tr><td><b>#248</b></td><td>perf: allow overriding the Engram RDMA QP configuration</td><td><span class="badge open">open</span></td><td><span class="tcat engram">Engram 路径</span></td><td><span class="badge feat">特性</span></td><td>4 文件 +99/-0</td><td>DEEPINFER_ENGRAM_NUM_QPS / RESTRICT_RD_ATOMIC 覆盖 QP 理论值,B300 prefill 最高 +3.2%</td></tr>
      <tr><td><b>#243</b></td><td>perf: decouple the Engram buffer size from max_num_batched_tokens</td><td><span class="badge closed">closed</span></td><td><span class="tcat engram">Engram 路径</span></td><td><span class="badge feat">特性</span></td><td>2 文件 +18/-1</td><td>buffer 大小与调度参数解耦,8→25 QP 换 +10.7% prefill;关闭原因未公开</td></tr>
      <!-- C DeepEP -->
      <tr><td><b>#157</b></td><td>Bump DeepEP to f6aa38fe and drop the SSH→HTTPS rewrite</td><td><span class="badge merged">merged</span></td><td><span class="tcat deepep">DeepEP 版本</span></td><td><span class="badge feat">维护</span></td><td>2 文件 +3/-5</td><td>子模块升级;DeepEP 改记 HTTPS DeepJIT URL,build_vendor 免去 git rewrite</td></tr>
      <tr><td><b>#179</b></td><td>parallel_utils: guard DeepEP-V2 imports so non-DeepEP platforms stay importable</td><td><span class="badge closed">closed</span></td><td><span class="tcat deepep">DeepEP 版本</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +12/-2</td><td>userbuffer.py/cp.py 镜像 mlp.py 的 import guard;纯 DeepEP v1 轮子不再导入即崩</td></tr>
      <tr><td><b>#186</b></td><td>README: list libdw-dev and pciutils as NVIDIA build prerequisites</td><td><span class="badge open">open</span></td><td><span class="tcat deepep">DeepEP 版本</span></td><td><span class="badge feat">文档</span></td><td>1 文件 +2/-0</td><td>补齐 DeepEP/vendor 构建的系统依赖说明(libdw-dev、pciutils)</td></tr>
      <!-- D 进程组/拓扑 -->
      <tr><td><b>#81</b></td><td>Bracket IPv6 addresses in distributed initialization URLs</td><td><span class="badge open">open</span></td><td><span class="tcat pg">进程组/拓扑</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +17/-0</td><td>MASTER_ADDR 为 IPv6 字面量时加方括号,消除歧义 TCP URL</td></tr>
      <tr><td><b>#40</b></td><td>fix: validate distributed launch topology</td><td><span class="badge closed">closed</span></td><td><span class="tcat pg">进程组/拓扑</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +49/-1</td><td>启动断言改显式校验:非正 world/rank 越界/不整除拓扑;关闭原因未公开</td></tr>
      <tr><td><b>#57</b></td><td>Fix DP launcher hangs after worker failures</td><td><span class="badge open">open</span></td><td><span class="tcat pg">进程组/拓扑</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +197/-10</td><td>launcher 改等进程 sentinel:任意 worker 失败立即上报全局 rank 并清理余部</td></tr>
      <tr><td><b>#64</b></td><td>Use vendor-neutral visible-device helpers</td><td><span class="badge open">open</span></td><td><span class="tcat pg">进程组/拓扑</span></td><td><span class="badge feat">重构</span></td><td>6 文件 +26/-27</td><td>CUDA_VISIBLE_DEVICES 直读替换为硬件层 helper,支撑 Biren SUPA_VISIBLE_DEVICES</td></tr>
      <!-- E EPLB -->
      <tr><td><b>#107</b></td><td>eplb: aggregate the expert-count window by logical expert at record time</td><td><span class="badge open">open</span></td><td><span class="tcat eplb">EPLB 通信</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +136/-21</td><td>计数窗口记录时即按逻辑专家聚合,消除重排后死放置污染均衡决策</td></tr>
      <tr><td><b>#191</b></td><td>Fix EPLB replica allocation for tied expert loads</td><td><span class="badge open">open</span></td><td><span class="tcat eplb">EPLB 通信</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +49/-3</td><td>去掉 FP32 抖动、显式平局规则:热度并列时副本不再全给空闲专家</td></tr>
      <tr><td><b>#212</b></td><td>fix(eplb): select replicas by peak-load reduction</td><td><span class="badge open">open</span></td><td><span class="tcat eplb">EPLB 通信</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +82/-10</td><td>以「峰值削减」替代绝对成本求和,额外覆盖长历史 FP32 精度问题(#191 竞合)</td></tr>
      <!-- F SHM -->
      <tr><td><b>#45</b></td><td>fix: honor message queue dequeue timeouts</td><td><span class="badge open">open</span></td><td><span class="tcat shm">SHM/广播</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +130/-3</td><td>dequeue(timeout) 同样约束 socket 接收与本地溢出负载,共享单调 deadline</td></tr>
      <tr><td><b>#48</b></td><td>fix: prevent multimodal shared-pool deadlocks and allocation leaks</td><td><span class="badge open">open</span></td><td><span class="tcat shm">SHM/广播</span></td><td><span class="badge fix">修复</span></td><td>3 文件 +193/-7</td><td>多模态共享池改整请求原子发布,消除跨 worker 循环等待死锁</td></tr>
      <tr><td><b>#76</b></td><td>Allow unlinking shared memory after closing the mapping</td><td><span class="badge open">open</span></td><td><span class="tcat shm">SHM/广播</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +24/-1</td><td>close() 清掉 IPC handle 后按名字独立 unlink,修复命名段泄漏</td></tr>
      <tr><td><b>#128</b></td><td>fix(worker): skip overflowing decode perf cache entries</td><td><span class="badge open">open</span></td><td><span class="tcat shm">SHM/广播</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +37/-1</td><td>cache 含 inf batch size 时 rank0 广播前 OverflowError 崩溃,改为跳过回退</td></tr>
      <tr><td><b>#158</b></td><td>harden: replace unsafe pickle usage in shm_broadcast.py</td><td><span class="badge open">open</span></td><td><span class="tcat shm">SHM/广播</span></td><td><span class="badge fix">修复</span></td><td>1 文件 +7/-1</td><td>shm_broadcast 反序列化弃用 pickle 改 JSON(semgrep 自动安全修复)</td></tr>
      <tr><td><b>#251</b></td><td>fix: reject oversized shared-pool allocations instead of spinning forever</td><td><span class="badge open">open</span></td><td><span class="tcat shm">SHM/广播</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +44/-0</td><td>超容量分配立即报错而非 100 行/秒日志自旋(#38 主题重提)</td></tr>
      <tr><td><b>#38</b></td><td>fix: reject oversized shared-pool allocations</td><td><span class="badge closed">closed</span></td><td><span class="tcat shm">SHM/广播</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +34/-0</td><td>同主题早期版本;关闭原因未公开</td></tr>
      <!-- G 挂死/配置 -->
      <tr><td><b>#50</b></td><td>Fix evaluation hangs on empty DP shards</td><td><span class="badge open">open</span></td><td><span class="tcat hang">挂死/配置</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +84/-3</td><td>空分片 rank 也调用 generate([]) 参与跨 DP 完成集合,eval 不再挂死</td></tr>
      <tr><td><b>#218</b></td><td>fix: validate boolean environment variables with strict parsing</td><td><span class="badge merged">merged</span></td><td><span class="tcat hang">挂死/配置</span></td><td><span class="badge fix">修复</span></td><td>1 文件 +8/-1</td><td>_bool() 只认 1/true/0/false/空串,通信开关拼错显式报错</td></tr>
      <!-- H Engram 周边 -->
      <tr><td><b>#70</b></td><td>fix: load Engram scales from their indexed shard</td><td><span class="badge open">open</span></td><td><span class="tcat misc">Engram 周边</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +53/-4</td><td>Engram scale 与 weight 分属不同 safetensors shard 时独立解析句柄</td></tr>
      <tr><td><b>#106</b></td><td>fix(worker): tolerate unset CUDA_VISIBLE_DEVICES in Engram driver widening</td><td><span class="badge open">open</span></td><td><span class="tcat misc">Engram 周边</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +58/-1</td><td>GPU 存储模式下设备拓宽对未导出的 CUDA_VISIBLE_DEVICES 免疫</td></tr>
      <tr><td><b>#126</b></td><td>fix(worker): key decode perf cache by execution config</td><td><span class="badge open">open</span></td><td><span class="tcat misc">Engram 周边</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +91/-0</td><td>cache key 补上 engram_parallel_size / batch-invariant / engine type</td></tr>
      <tr><td><b>#209</b></td><td>fix: validate golden token IDs against the model vocabulary</td><td><span class="badge open">open</span></td><td><span class="tcat misc">Engram 周边</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +126/-2</td><td>golden ID 入队前校验,防止 map_engram 表越界查找</td></tr>
      <tr><td><b>#232</b></td><td>Fix expose_all_gpus_to_cuda_driver crash when CUDA_VISIBLE_DEVICES is unset</td><td><span class="badge open">open</span></td><td><span class="tcat misc">Engram 周边</span></td><td><span class="badge fix">修复</span></td><td>2 文件 +84/-2</td><td>与 #106 同根因的独立重复提交(不同作者)</td></tr>
      <!-- I 调度耦合 -->
      <tr><td><b>#236</b></td><td>test(mtp_varlen): pin zero-rate slack in confidence-based seqlens_q allocation</td><td><span class="badge open">open</span></td><td><span class="tcat sched">调度耦合</span></td><td><span class="badge fix">测试</span></td><td>1 文件 +29/-0</td><td>零置信行不得抢占 extra 验证预算;seqlens_q 决定各 rank 集合通信的 ragged 形状</td></tr>
    </table>
    </div>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🧮</span>主题规模分布</h3>
        <ul class="feat">
          <li>通信库适配(NCCL/RCCL/collectives/HCCL):<b>12</b> 个——最大主题,SM90×3、ROCm×6、SM120×1、Ascend×2</li>
          <li>SHM/消息队列/广播 IPC:<b>7</b> 个——全部为问题解决类</li>
          <li>Engram 通信路径(NVLink/UVA/QP):<b>5</b> 个——全部为特性/性能类</li>
          <li>进程组与启动拓扑:<b>4</b>;Engram 周边修复:<b>5</b>;DeepEP 版本:<b>3</b>;EPLB:<b>3</b>;挂死/配置:<b>2</b>;调度耦合:<b>1</b></li>
        </ul>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">⚖️</span>变更体量两极分化</h3>
        <p>大特性 PR 体量惊人:ROCm 后端(#201)+9766 行、SM90(#92)+9159 行、ROCm 4/5(#205)+9036 行、SM120(#138)+4283 行;而问题解决类 PR 普遍在 2 文件、百行以内——最小的是 #186(2 行)与 #158(7 行)。唯二合入的 #157(+3/-5)与 #218(+8/-1)正是「小而关键」的典型。</p>
      </div>
    </div>
  </section>

  <!-- ================= 4 重点 PR 详解 ================= -->
  <section id="s4">
    <h2 class="sec"><span class="num">4</span>重点 PR 详解</h2>
    <p class="lede">对通信域核心 PR 逐个展开:动机、机制、验证与涉及文件,全部摘自 PR 描述原文与 GitHub API 文件列表。</p>

    <h3 style="color:#fff;font-size:15px;margin:24px 0 4px">4.1 Engram 通信路径演进(本轮最活跃战场)</h3>

    <div class="prbox reveal">
      <div class="prhead">
        <span class="prno">PR #99</span>
        <span class="prtitle">Add an NVLink Engram fetch for single-node runs without NCCL GIN</span>
        <span class="badge open">open</span><span class="badge nccl">NCCL GIN 替代</span>
      </div>
      <p class="dim">algebra-MCX · 2026-10-20 15:48 · 16 文件 +485/-7 · 测试环境:1 节点 4×B200(NVLink,GIN 不可用),driver 580.178 / CUDA 13.1 / torch 2.13.0+cu132 / NCCL 2.32.3</p>
      <h4>■ 动机:NCCL GIN 成为单节点硬依赖</h4>
      <p>DeepSeek-V4.1 在 <b>NCCL GIN(GPU-initiated RDMA)不可用</b>的节点上完全无法运行——即使全部 GPU 都在同一 NVLink 域内。典型场景:云上无 RDMA 的单机 GPU 实例、网卡未接线/被禁用的实验节点、NIC/固件/驱动不支持 GDAKI 的主机。根因在于 <code>deep_ep.EngramBuffer.fetch</code> 只实现了 GIN 路径:<code>engram_fetch.cuh</code> 即使在 <code>num_rdma_ranks == 1</code> 时也发出 <code>comm::NCCLGin</code> get(shard 位于其他 rank 的 host 内存):默认情况下 <code>EngramBuffer</code> 创建直接报 <code>GIN: DevComm setup failed on all available backends</code>;设置 <code>EP_DISABLE_GIN=1</code> 后,首次前向(profile run)在 Engram fetch 内核中触发 <code>CUDA_ERROR_ILLEGAL_ADDRESS</code>——DeepEP 自带的 <code>tests/engram/test_engram.py</code> 以同样方式失败。</p>
      <h4>■ 机制:集合通信替代单边 get</h4>
      <ul class="feat">
        <li><b>write</b>:每 rank 把自己的 shard 保存在 pinned host 内存,通过 UVA 读取;开启 <code>DEEPINFER_ENGRAM_FORCE_GPU_STORAGE</code> 时改存 GPU。完整 FP8 scale 表常驻 GPU(V4.1 约 6 GB/rank)。</li>
        <li><b>fetch</b>:索引 pad 到 <code>max_num_tokens</code> 后 all-gather;各 rank <code>index_select</code> 自己拥有的行、其余补零;一次 <code>all_to_all_single</code> 把行归还请求方;按 owner rank 选行。输出与 DeepEP 一致:<code>[T, E·H]</code> 行 + TMA 对齐(4)列主序 scales。</li>
        <li><b>无 host sync</b>:整个 fetch 可被既有 CUDA graph 捕获。</li>
      </ul>
      <p><b>权衡</b>:这是集合通信而非单边 get——每次 fetch 都要在 NVLink 上搬运 pad 到 <code>max_num_tokens</code> 的缓冲,且需要所有 rank 参与。目标是「让这类节点能跑」,而非匹配 GIN 性能。默认行为不变:开关关闭时 <code>EngramBuffer</code> 照旧使用。开关 <code>DEEPINFER_ENGRAM_NVLINK_FETCH</code> 未设置时跟随 <code>EP_DISABLE_GIN</code>。</p>
      <h4>■ 验证</h4>
      <p>ruff 通过;<code>tests/distributed/test_engram_nvlink.py</code>(2 GPU)1 项通过——FP8 行与 scales 与全表直查 <b>byte-identical</b>(含跨 rank 不齐整的 token 数 64/…);DeepEP <code>test_barrier.py</code>、<code>test_ep.py</code>(<code>--allow-hybrid-mode 0</code>)与 DeepGEMM <code>test_mega_moe.py</code> 在 <code>EP_DISABLE_GIN=1</code> 下全部通过,证明「其余一切在 NVLink 上都正常,Engram 是唯一 blocker」。</p>
      <div class="files">
        <span class="filepath">parallel_utils/engram_nvlink.py +108(新增)</span>
        <span class="filepath">parallel_utils/userbuffer.py +10</span>
        <span class="filepath">v4_modules/engram.py +3/-1</span>
        <span class="filepath">deepinfer/environ.py +2</span>
        <span class="filepath">tests/distributed/test_engram_nvlink.py +117(新增)</span>
        <span class="filepath">doc/single_node_nvlink.md +71(新增)</span>
        <span class="filepath">doc/validation/nvlink-2026-10-22/*(验证记录)</span>
        <span class="filepath">deep_cluster/topology/bind.py +7/-1</span>
      </div>
    </div>

    <div class="prbox reveal">
      <div class="prhead">
        <span class="prno">PR #246</span>
        <span class="prtitle">feat: add opt-in LocalEngram fetch over NVLink</span>
        <span class="badge open">open</span><span class="badge nccl">NVLink 对称内存</span>
      </div>
      <p class="dim">wukehu · 2026-10-28 13:12 · 5 文件 +526/-6 · 默认路径不变,由 <code>DEEPINFER_ENGRAM_LOCAL</code> 选择启用</p>
      <h4>■ 机制:GPU 对称内存 + peer domain 直读</h4>
      <ul class="feat">
        <li>每 rank 拥有每个 Engram 层的确定性 shard;对称内存在所有 rank 上分配等大小 GPU buffer 并映射 peer buffer;</li>
        <li>全局行号 <code>g</code> 路由到 <code>owner = g // rows_per_rank</code>,<code>local_row = g % rows_per_rank</code>;</li>
        <li>设备侧 gather 直接经 NVLink peer domain 读取 owner shard;保留既有 <code>write()/fetch()</code> 契约、BF16/FP8 数据与 scale 布局、无效索引行零填充。</li>
      </ul>
      <h4>■ 性能:贴近官方曲线</h4>
      <table class="mini-tbl">
        <tr><th>场景</th><th>LocalEngram</th><th>官方参考(读图估算)</th><th>比值</th></tr>
        <tr><td>Prefill 65,536 tok/s/GPU</td><td>85,572.6</td><td>~89,544.7</td><td>95.6%</td></tr>
        <tr><td>Prefill 4,096 tok/s/GPU</td><td>60,054.9</td><td>~60,033.7</td><td>100.0%</td></tr>
        <tr><td>Prefill 8,192 tok/s/GPU</td><td>72,386.2</td><td>~71,669.5</td><td>101.0%</td></tr>
        <tr><td>Decode 256 req/rank 输出 tok/s/GPU</td><td>23,741.4</td><td>~24,800</td><td>95.73%</td></tr>
        <tr><td>Decode 8 req/rank 输出 tok/s/GPU</td><td>1,818.5</td><td>~1,900</td><td>95.71%</td></tr>
      </table>
      <p class="dim">Decode 为 EP8/DP8、nextn=3、τ=3.25;Prefill 对照官方 EP4/DP4。相比 #99 的「能跑就行」,#246 目标直指官方性能。</p>
      <div class="files">
        <span class="filepath">parallel_utils/engram_local.py +404(新增)</span>
        <span class="filepath">parallel_utils/userbuffer.py +34/-2</span>
        <span class="filepath">v4_modules/engram.py +11/-4</span>
        <span class="filepath">deepinfer/environ.py +3</span>
        <span class="filepath">tests/worker/test_engram_local.py +74(新增)</span>
      </div>
    </div>

    <div class="prbox reveal">
      <div class="prhead">
        <span class="prno">PR #248</span>
        <span class="prtitle">perf: allow overriding the Engram RDMA QP configuration</span>
        <span class="badge open">open</span><span class="badge nccl">RDMA QP 调优</span>
      </div>
      <p class="dim">tangxin-hn · 2026-10-29 13:32 · 4 文件 +99/-0 · 实测节点:8×B300</p>
      <h4>■ 问题:NIC 速率猜测失准 → QP 不足</h4>
      <p>DeepEP 从 buffer 的 <code>max_num_tokens</code> 和一个 NIC 速率猜测推导 Engram QP 数:仅当 <code>mlx5_0</code> 上报 MT4131 才取 90 Mpps,否则 45 Mpps。但 <code>mlx5_0</code> 未必是 Engram 流量所走的网卡——该 B300 节点上 <code>mlx5_0/mlx5_1</code> 是 200G MT4126(NCCL 根本不用),真正的 RDMA 流量(<code>NCCL_IB_HCA=mlx5_bond</code>)走 8×400G MT4131,两个 NIC 之间 3 个并发 <code>ib_read_bw</code>(64 QPs、32-WQE post list)可达 <b>123 Mpps</b> 的 64 字节读。而检查仍落入 45 Mpps 分支:EP4 下每 RDMA peer 仅 8 QPs、EP8 仅 4 QPs,prefill 每_rank ~20K token 时 Engram fetch 成为瓶颈。</p>
      <h4>■ 方案与结果</h4>
      <p>新增 <code>DEEPINFER_ENGRAM_NUM_QPS</code> 与 <code>DEEPINFER_ENGRAM_RESTRICT_RD_ATOMIC</code>,在不 resize 任何 buffer 的前提下覆盖理论 <code>(num_qps, restrict_rd_atomic)</code>(<code>qp_depth</code> 保持理论值,因此低于理论值的 QP 数会被拒绝)。EP4DP4 prefill(131072 上下文,4096 新 token/请求):B=4096 时 59.53→58.74 ms/step(<b>+1.3%</b>),B=8192 时 103.16→99.94(<b>+3.2%</b>),B=16384 增益进一步扩大。</p>
      <div class="files">
        <span class="filepath">parallel_utils/userbuffer.py +8</span>
        <span class="filepath">deepinfer/environ.py +9</span>
        <span class="filepath">examples/README.md +2</span>
        <span class="filepath">tests/worker/test_userbuffer.py +80</span>
      </div>
      <div class="note warn" style="margin-bottom:0"><b>关联:</b>三天前被关闭的 <b>#243</b>(decouple the Engram buffer size from max_num_batched_tokens,2 文件 +18/-1)针对同一瓶颈:8-QP 平台期(16K~20K)使 Engram 每 token 成本从 8K 的线性外推多出 ~21.8 ms/step;A/B(4×B200,EP4DP4,buffer 8→25 QPs)prefill 72,409→80,140 tok/s/GPU(<b>+10.7%</b>)。#248 以「覆盖理论值」的更轻量方式接力了这一主题。</div>
    </div>

    <div class="prbox reveal">
      <div class="prhead">
        <span class="prno">PR #200</span>
        <span class="prtitle">Add opt-in UVA Engram fetch for single-node deployments</span>
        <span class="badge open">open</span><span class="badge nccl">GDAKI 诊断</span>
      </div>
      <p class="dim">JohnQin-llm · 2026-10-22 01:08 · 5 文件 +304/-1 · <code>DEEPINFER_ENGRAM_UVA_FETCH=1</code> 启用,默认不变</p>
      <h4>■ 发现:GDAKI 静默回退 CPU proxy,fetch 慢 5~10 倍</h4>
      <p><code>EngramBuffer.fetch</code> 对每个 (token, n-gram entry) 发一次 256 B GIN get,按 CX7 45 Mpps / CX8 90 Mpps 设计。但 DOCA GPUNetIO(NCCL GDAKI 后端)需要用 <code>cudaHostRegister(..., cudaHostRegisterIoMemory)</code> 把 NIC doorbell 页映射进 GPU;该调用失败且 NIC handler 为 <code>AUTO</code> 时,DOCA 切到 <b>CPU proxy 模式</b>——WARN 级别无任何日志,一切照常工作,只是变慢。8×B200 KVM guest(ConnectX-7 NDR,driver 580.126.09,NCCL 2.32.3,DeepEP 93eb6eb)实测:65,536 tokens × 24 entries × 2 层 FP8 仅 <b>7.95 Mpps</b>(395 ms),而同 NIC 的 CPU 发起 RDMA 读(256 B、25 QPs、目标 GPU 内存)可达 <b>67~90 Mpps</b>;gdb 抓到 busy 线程停在 <code>ncclGinProgress (gin/gin_host.cc:85)</code>,设 <code>NCCL_GIN_GDAKI_NIC_HANDLER=2</code>(GPU_SM_DB)则初始化即 <code>DOCA Error 21</code>。</p>
      <h4>■ 方案与结果</h4>
      <p>单节点改用 UVA 从 shared pinned host 内存读表,绕开 GIN fetch:该节点上 EP4 prefill 提速 <b>1.44~1.79×</b>、EP8 decode 提速 <b>1.06~1.29×</b>,分别达到 README 曲线的 91%~104% 与 91%~99%;输出与默认路径 <b>bit-identical</b>。</p>
      <div class="files"><span class="filepath">5 文件:environ.py + UVA fetch 实现 + 测试(+304/-1)</span></div>
    </div>

    <h3 style="color:#fff;font-size:15px;margin:28px 0 4px">4.2 通信库适配:平台移植三线作战</h3>

    <div class="prbox reveal">
      <div class="prhead">
        <span class="prno">PR #138</span>
        <span class="prtitle">Enable experimental SM120 inference with FlashInfer and PyTorch collectives</span>
        <span class="badge open">open</span><span class="badge nccl">PyTorch collectives</span>
      </div>
      <p class="dim">pood1e · 2026-10-21 02:00 · 65 文件 +4283/-105 · 验证:两台 4×RTX PRO 6000 Blackwell Server 96GB;attention DP8/MoE EP8;CUDA 13.4.92 / NCCL 2.32.3</p>
      <h4>■ 核心思路:用 PyTorch collectives 重写通信层</h4>
      <p>在 PCIe-only 的 SM120 GPU 上以维护中的 FlashInfer/DeepGEMM 内核 + <b>PyTorch collectives</b> 跑通 DeepSeek-V4.1:稀疏 prefill/decode、paged indexer、dense/MoE GEMM、投影与 mHC 全部适配 SM12x;通信侧以纯集合原语实现 CP、Engram 与专家交换,支持空/ragged 输入、编码 scale 布局与 changed-input graph replay——<b>单源 decode 广播活跃 payload 并规约专家输出;多源使用对齐的 AllGather/ReduceScatter</b>。CPU Engram 载入可复用 pinned 存储;DeepEP 仅在被选中时导入。验证含 CPU/Gloo 契约与八 rank NCCL CP/Engram/EP eager/graph 套件(覆盖 ragged/空 rank、取消、打包字节/scale、路由与输入变化重放),52 项聚焦检查 + 72+16 个历史请求匹配。</p>
      <div class="files">
        <span class="filepath">parallel_utils/torch_cp.py +113(新增)</span>
        <span class="filepath">parallel_utils/torch_engram.py +179(新增)</span>
        <span class="filepath">parallel_utils/token_exchange.py +135(新增)</span>
        <span class="filepath">parallel_utils/cp.py +51/-6</span>
        <span class="filepath">parallel_utils/userbuffer.py +62/-10</span>
        <span class="filepath">tests/sm120/test_torch_cp.py +69</span>
        <span class="filepath">tests/sm120/test_torch_engram.py +69</span>
        <span class="filepath">tests/sm120/test_engram_cuda.py +55</span>
      </div>
    </div>

    <div class="prbox reveal">
      <div class="prhead">
        <span class="prno">PR #201 + #202~#206</span>
        <span class="prtitle">AMD ROCm 后端:五连发拆分栈 → 单 PR 整合</span>
        <span class="badge open">open</span><span class="badge closed">closed ×5</span><span class="badge hccl">RCCL</span>
      </div>
      <p class="dim">vivienfanghuagood · 2026-10-22 · #201:67 文件 +9766/-24;#202~#206 拆分栈累计 225 文件,全部关闭并合并入 #201</p>
      <h4>■ 拆分栈(已关闭)</h4>
      <table class="mini-tbl">
        <tr><th>PR</th><th>内容</th><th>规模</th></tr>
        <tr><td>#202 ROCm 1/5</td><td>PlatformROCm(RCCL 经 nccl backend)+ KFD sysfs 拓扑探测 + TileLang 0.1.15 HIP 补丁(630 行,含 match_sync 仿真等)</td><td>+961/-9</td></tr>
        <tr><td>#203 ROCm 2/5</td><td>deep_gemm API 的 dense GEMM HIP 内核</td><td>+3363/-14</td></tr>
        <tr><td>#204 ROCm 3/5</td><td>稀疏注意力、indexer 与 top-k</td><td>+5955/-17</td></tr>
        <tr><td>#205 ROCm 4/5</td><td>MoE、专家并行交换、Engram 与 CP buffer(通信核心)</td><td>+9036/-23</td></tr>
        <tr><td>#206 ROCm 5/5</td><td>文档与端到端结果(与 4/5 同栈)</td><td>+9121/-23</td></tr>
      </table>
      <p>作者随后留言:「<i>Consolidated into #201 to keep review in one place</i>」——五 PR 关闭、#201 按组件逐 commit 重发。</p>
      <h4>■ #205 的通信要点(ROCm 上重写 DeepEP 三大 buffer)</h4>
      <ul class="feat">
        <li><b>EPBuffer</b>:单节点交换改走 torch 对称内存——dispatch 只发给拥有该 token 专家的 rank;combine 每 (token, rank) 拉一行预求和;prefill 在 side stream 上流水;decode 固定槽位、可 graph 捕获;EPLB per-expert 接收计数器;</li>
        <li><b>EngramBuffer</b>:shard 存 shared pinned host 内存(或 <code>DEEPINFER_ENGRAM_FORCE_GPU_STORAGE</code> 下 HIP-IPC HBM),每层一个持久 Triton gather,无 host sync;</li>
        <li><b>BucketBuffer / BucketSession</b>:构建于 <b>async RCCL collectives</b> 之上;另因 <code>hipMemcpyAsync</code> 在对称内存 peer 映射上会 fault,EPLB 的节点内 shuffle 改为 kernel 直接读 peer 内存;ROCm 上设 <code>NCCL_RAS_ENABLE=0</code>。</li>
      </ul>
      <p>MoE decode 在 EP1 下达到 5.7~6.8 TB/s 有效权重读取;MI355X 上 12 项 vendor 测试 + 8 GPU 专家 shuffle 测试通过。</p>
      <div class="files">
        <span class="filepath">vendor/rocm/deep_ep/_ep.py +599</span>
        <span class="filepath">vendor/rocm/deep_ep/_engram.py +476</span>
        <span class="filepath">vendor/rocm/deep_ep/_bucket.py +210</span>
        <span class="filepath">vendor/rocm/deep_ep/_hip.py +100</span>
        <span class="filepath">deep_cluster/hardware/rocm.py +82</span>
        <span class="filepath">deepinfer/rocm_compat.py +92</span>
        <span class="filepath">vendor/rocm/patches/tilelang-0.1.15-hip.patch +630</span>
      </div>
      <div class="note" style="margin-bottom:0"><b>同赛道:</b>SM90 方向另有 #92(H20-3e 端到端,56 文件 +9159/-72)、#148(H100/H200/H20,22 文件)、#180(平台层,48 文件)三个 open PR 竞争;Ascend 方向有 #46(910C RFC)与 #193(910B EP8 参考运行器)。加上 #64(vendor-neutral 设备可见性)与 #179 的 MUSA 背景,「把 DeepEP/NCCL 假设从引擎里解耦」是跨平台社区的一致诉求。</div>
    </div>

    <h3 style="color:#fff;font-size:15px;margin:28px 0 4px">4.3 唯二合入的 PR</h3>

    <div class="prbox gold reveal">
      <div class="prhead">
        <span class="prno">PR #157</span>
        <span class="prtitle">Bump DeepEP to f6aa38fe and drop the SSH→HTTPS rewrite</span>
        <span class="badge merged">merged 2026-10-21 04:55</span><span class="badge deepep">仓库首个合入</span>
      </div>
      <p class="dim">wx-csy(DeepSeek,co-authored chensy@deepseek.com)· 2 文件 +3/-5 · 本地提交 <code>9bd9cf2</code></p>
      <p>DeepEP 上游开始记录 HTTPS 的 DeepJIT URL,<code>scripts/build_vendor.sh</code> 不再需要 <code>git@github.com</code> 到 HTTPS 的 rewrite 规则;子模块指针升级至 <code>f6aa38fe</code>。这是 224 个 PR 中<b>第一个</b>被合入的——官方用一次依赖升级为社区贡献定调:通信栈(vendor/DeepEP)的版本管理优先级极高。</p>
      <div class="files"><span class="filepath">scripts/build_vendor.sh +2/-4</span><span class="filepath">vendor/DeepEP +1/-1(子模块)</span></div>
    </div>

    <div class="prbox gold reveal">
      <div class="prhead">
        <span class="prno">PR #218</span>
        <span class="prtitle">fix: validate boolean environment variables with strict parsing</span>
        <span class="badge merged">merged 2026-10-25 11:59</span><span class="badge deepep">第 2 个也是最后 1 个合入</span>
      </div>
      <p class="dim">Inference1(DeepSeek)· 1 文件 +8/-1 · 本地提交 <code>5537415</code></p>
      <p>旧 <code>_bool()</code> 把除 <code>"0"/""/"false"/"False"</code> 之外的一切值都当 <code>True</code>——拼错的 <code>"FALSE"</code>、<code>"no"</code>、<code>"invalid"</code> 会静默开启特性。修复后大小写不敏感地只接受 <code>1/true/0/false/空串</code>,其余抛 <code>ValueError</code>。对通信域的意义直接:DeepInfer 的大量通信开关都是布尔环境变量——<code>EP_DISABLE_GIN</code>、<code>DEEPINFER_ENGRAM_FORCE_GPU_STORAGE</code>、<code>DEEPINFER_REARRANGE_AFTER_PREFILL_IN_NORMAL_ENGINE</code>,以及本系列 PR 新增的 <code>DEEPINFER_ENGRAM_NVLINK_FETCH / UVA_FETCH / LOCAL</code> 等;严格解析让「开关拼错导致 GIN 未按预期禁用」这类问题显式化。</p>
      <div class="files"><span class="filepath">deepinfer/environ.py +8/-1</span></div>
    </div>

    <h3 style="color:#fff;font-size:15px;margin:28px 0 4px">4.4 被关闭的通信 PR:三类结局</h3>

    <div class="prbox dead reveal">
      <div class="prhead">
        <span class="prno">PR #179</span>
        <span class="prtitle">parallel_utils: guard DeepEP-V2 imports so non-DeepEP platforms stay importable</span>
        <span class="badge closed">closed</span><span class="badge deepep">非技术原因关闭</span>
      </div>
      <p class="dim">yeahdongcn · 2026-10-21 09:13 · 2 文件 +12/-2</p>
      <p><code>parallel_utils/userbuffer.py</code> 与 <code>cp.py</code> 无条件 <code>from deep_ep import EngramBuffer…</code>,导致只带 DeepEP v1 的平台(MUSA/S5000,deep_ep 仅提供 EventOverlap/Buffer/Config)在 8 rank <code>--ep 8</code> 启动时<b>模块导入即 ImportError</b>——运行期 guard 根本来不及执行。修复镜像 <code>mlp.py</code> 既有模式(None fallback + <code># pragma: no cover</code>),DeepEP v2 平台行为不变。结局:作者留言「<i>Closing as requested by the author-side owner…Nothing here was rejected on technical grounds</i>」——按所有方要求关闭,分支留在 fork 上,并非技术否决。</p>
      <div class="files"><span class="filepath">parallel_utils/userbuffer.py +6/-1</span><span class="filepath">parallel_utils/cp.py +6/-1</span></div>
      <div class="note warn" style="margin-bottom:0"><b>关闭原因盘点(9 个):</b>#202~#206 ×5 = 合并入 #201(主动整合);#179 = 作者侧非技术关闭;#38 / #40 / #243 ×3 = 无公开评论关闭——其中 #38 的主题(共享池超容量分配)由 #251 重提,#243 的主题(QP 不足)由 #248 接力,#40 的启动拓扑校验暂无直接继任者。</div>
    </div>

    <h3 style="color:#fff;font-size:15px;margin:28px 0 4px">4.5 进程组初始化与分布式挂死修复</h3>

    <div class="grid c2">
      <div class="prbox reveal" style="margin:0">
        <div class="prhead">
          <span class="prno">PR #81</span>
          <span class="prtitle">Bracket IPv6 addresses in distributed initialization URLs</span>
          <span class="badge open">open</span>
        </div>
        <p class="dim">Afloat16 · 2 文件 +17/-0 · 6 项单测通过(修复前 3 失败)</p>
        <p>未加方括号的 IPv6 <code>MASTER_ADDR</code> 生成歧义的分布式 TCP URL;为 IPv6 字面量加 <code>[]</code> 同时保留其他主机写法与 engine-group 端口偏移。</p>
        <div class="files"><span class="filepath">deepinfer/utils.py +2</span><span class="filepath">tests/test_distributed_init_url.py +15(新增)</span></div>
      </div>
      <div class="prbox reveal" style="margin:0">
        <div class="prhead">
          <span class="prno">PR #50</span>
          <span class="prtitle">Fix evaluation hangs on empty DP shards</span>
          <span class="badge open">open</span><span class="badge nccl">集合参与修复</span>
        </div>
        <p class="dim">Baili23 · 2 文件 +84/-3 · 6 回归用例 + 真 Gloo 10 项检查</p>
        <p>请求数少于 DP rank 时(如 <code>--limit 1 --n-sample 1</code>),空分片 rank 直接关闭 engine,其余 rank 仍进入跨 DP 完成集合,超时或对端连接错误。修复:空 rank 以空 prompt 列表调用 <code>generate</code>,参与直到 DP 组整体生成结束。</p>
        <div class="files"><span class="filepath">eval/run_eval.py +4/-3</span><span class="filepath">tests/eval/test_run_eval.py +80(新增)</span></div>
      </div>
    </div>

    <div class="prbox reveal">
      <div class="prhead">
        <span class="prno">PR #57</span>
        <span class="prtitle">Fix DP launcher hangs after worker failures</span>
        <span class="badge open">open</span><span class="badge nccl">launcher 挂死</span>
      </div>
      <p class="dim">fffzlfk · 2 文件 +197/-10 · 8 项子进程回归测试(Python 3.12.13 与 3.14.3 双版本);原实现下失败回归用例 15 秒超时</p>
      <p>后续 DP worker 失败时,<code>run_dp</code> 阻塞在<b>更早</b> worker 的 <code>join()</code> 上而不检查退出码;若该 worker 正在集合通信中等待,launcher 既无法上报原始失败也无法清理其余 local rank。修复:改为等待进程 <b>sentinel</b>,任意 local rank 的失败立即被察觉;上报全局 DP rank ID;终止并回收剩余 worker(中断等待与部分启动失败后同样清理);忽略 SIGTERM 的 worker 在共享的 5 秒宽限期后被 kill。</p>
      <div class="files"><span class="filepath">examples/_launch.py +35/-10</span><span class="filepath">tests/examples/test_launch.py +162(新增)</span></div>
      <div class="note" style="margin-bottom:0"><b>同文件战场:</b>被关闭的 <b>#40</b>(validate distributed launch topology,2 文件 +49/-1)把启动期断言改成显式拓扑校验(非正 world/DP 尺寸、越界 rank、不整除拓扑),同样落在 <code>examples/_launch.py</code>——分布式启动路径是早期修复的高频碰撞区。</div>
    </div>

    <h3 style="color:#fff;font-size:15px;margin:28px 0 4px">4.6 SHM / 广播 / 消息队列 IPC</h3>

    <div class="grid c3">
      <div class="prbox reveal" style="margin:0">
        <div class="prhead"><span class="prno">#158</span><span class="badge open">open</span></div>
        <p class="dim" style="font-size:12px">anupamme · 1 文件 +7/-1 · semgrep 自动安全修复(OrbisAI Security)</p>
        <p style="font-size:13px"><code>shm_broadcast.py:392</code> 处 unpickle 可被构造数据执行任意代码;改用 JSON 等文本序列化。作者自评「防御性收窄,非已证可利用」,可随意关闭。</p>
        <div class="files"><span class="filepath">distributed/shm_broadcast.py +7/-1</span></div>
      </div>
      <div class="prbox reveal d1" style="margin:0">
        <div class="prhead"><span class="prno">#76</span><span class="badge open">open</span></div>
        <p class="dim" style="font-size:12px">Afloat16 · 2 文件 +24/-1 · 2 项单测通过(修复前 1 失败)</p>
        <p style="font-size:13px"><code>SharedMemory.close()</code> 会清掉 IPC handle,之后再 <code>unlink</code> 抛 AttributeError、命名段泄漏;改为按保存的名字独立于映射生命周期 unlink。</p>
        <div class="files"><span class="filepath">deepinfer/shared_memory.py +1/-1</span><span class="filepath">tests/test_shared_memory_lifecycle.py +23(新增)</span></div>
      </div>
      <div class="prbox reveal d2" style="margin:0">
        <div class="prhead"><span class="prno">#45</span><span class="badge open">open</span></div>
        <p class="dim" style="font-size:12px">xili-ytl · 2 文件 +130/-3 · 12 项回归(原实现 4 项超时失败)</p>
        <p style="font-size:13px"><code>MessageQueue.dequeue(timeout=…)</code> 只约束共享内存槽等待;远端接收与本地溢出负载走阻塞 <code>recv()</code> 可无限超时。修复:socket polling 共享同一单调 deadline;溢出标记延迟 ack 以保序。</p>
        <div class="files"><span class="filepath">tests/distributed/test_message_queue_timeout.py(新增)</span><span class="filepath">test_shm_broadcast.py</span></div>
      </div>
    </div>
    <div class="note warn"><b>共享内存池三连:</b>#48(死锁:分张量发布导致循环等待,+193/-7)、closed #38 与 open #251(超容量分配在 <code>SharedTorchMemoryPool.alloc()</code> 的 <code>while True</code> 中无限自旋,日志 100 行/秒)共同指向 <code>deepinfer/shared_memory.py</code> 的容量上界与发布原子性缺失。另 #128:decode perf cache 中 <code>1e309</code> 解析为 inf,<code>int(batch_size)</code> 抛 OverflowError 且发生在 rank0 <b>广播结果之前</b>,两 rank Gloo 验证修复后均回退到旧曲线。</div>

    <h3 style="color:#fff;font-size:15px;margin:28px 0 4px">4.7 EPLB 均衡通信三部曲</h3>

    <div class="prbox reveal">
      <div class="prhead">
        <span class="prno">#107 → #191 ⇄ #212</span>
        <span class="prtitle">专家负载均衡的三个正交修复</span>
        <span class="badge open">open ×3</span><span class="badge nccl">EPLB</span>
      </div>
      <p class="dim">syang-genai(#107,+136/-21)· cyanseek(#191,+49/-3)· AEGO-WRJ(#212,+82/-10)· 均落在 <code>deepinfer/model_executor/eplb/</code></p>
      <ul class="feat">
        <li><b>#107(窗口语义)</b>:<code>ExpertLoadBalancer</code> 的 per-step 计数环按<b>物理槽</b>记录,重排后未清窗/重键,旧放置的计数被记到「现在占据该槽的逻辑专家」头上;连续批处理 + <code>DEEPINFER_REARRANGE_AFTER_PREFILL_IN_NORMAL_ENGINE=1</code> 时窗口大部分是死放置数据——热专家欠副本、冷专家过副本、每次 prefill 后放置震荡还白付一次全层权重 shuffle。修复:窗口按 <code>[window_size, num_moe_layers, num_logical_experts]</code> 在记录时聚合。</li>
        <li><b>#191(平局规则)</b>:<code>expert_id * 1e-4</code> 的 FP32 抖动在热度并列时被舍入抹平,<code>argmin</code> 反复选中 expert 0——<code>[[0,5000,5000,0]]</code> 六物理专家返回 <code>[3,1,1,1]</code> 而非 <code>[1,2,2,1]</code>,256 逻辑/288 物理专家下 32 个额外副本全给 expert 0。修复:去浮点抖动,显式平局规则(先最小峰值成本和,再最高单副本聚合负载,最后最低 expert ID)。</li>
        <li><b>#212(精度竞合)</b>:指出 #191 之外的第二精度问题——<b>绝对</b>候选成本求和会在 FP32 中抹掉严格改进(999 步 <code>[0,32768,32768,0]</code> 后接 <code>[0,0,0,1]</code>,复制 expert 3 是唯一降峰选择,成本 32735232.5 vs 32735233,FP32 都舍入到 32735232)。改为最大化<b>峰值削减</b>(代数等价但避开大共享基线);作者声明为 #191 的独立竞合实现,「若 #191 先落地可拆为后续 PR」。</li>
      </ul>
      <p class="dim">#191 与 #212 互为替代方案、各自携带 exhaustive 测试(#191:64 个两步三专家历史的精确有理数枚举 + 四进程 CPU/Gloo 真实 scatter/all-reduce 验证;#212:729 个历史 + Fraction oracle)。二者的通信相关性:EPLB 重排本身即一次全层专家权重 shuffle,而其统计数据又来自 EP 交换中的 per-expert 计数。</p>
    </div>

    <h3 style="color:#fff;font-size:15px;margin:28px 0 4px">4.8 调度与通信耦合:mtp_varlen</h3>

    <div class="prbox reveal">
      <div class="prhead">
        <span class="prno">PR #236</span>
        <span class="prtitle">test(mtp_varlen): pin zero-rate slack in confidence-based seqlens_q allocation</span>
        <span class="badge open">open</span><span class="badge nccl">ragged 集合形状</span>
      </div>
      <p class="dim">Jackxiaozhiren · 1 文件 +29/-0 · schedule_mtp_varlen.py</p>
      <p>置信度驱动的 <code>seqlens_q</code> 分配把所有 (seq,pos) cumprod 单元放进一个全局 top-k,但 cumprod 为 <code>0.0</code> 的单元<b>未被排除</b>:新序列(<code>remap == -1</code> → rates 0.0)与刚吐出 stop token 的请求(confidence 被 <code>masked_fill_</code> 置零)都会以零置信参与竞争,在 <code>extra_budget</code> 超过正单元数时按批序瓜分额外验证 token——顺序相关、任意性分配。与通信的耦合点:<code>seqlens_q</code> 决定各 rank 参与集合通信的 ragged 形状,零置信行抢占预算会直接扰动跨 rank 的 token 分布。该 PR 钉死零速率 slack 的语义。</p>
      <div class="files"><span class="filepath">tilelang_ops/schedule_mtp_varlen.py +29</span></div>
    </div>
  </section>

  <!-- ================= 5 象限图 ================= -->
  <section id="s5">
    <h2 class="sec"><span class="num">5</span>特性支持 / 问题解决象限图</h2>
    <p class="lede">42 个 PR 按横轴(特性支持 ←→ 问题解决)与纵轴(待评审 open ↑ / 已定局 merged+closed ↓)落入四象限;气泡按主题着色并持续浮动,两个已合入 PR(#157/#218)带脉冲光环。</p>

    <div class="figure reveal">
      <svg viewBox="0 0 960 660" xmlns="http://www.w3.org/2000/svg">
        <!-- 象限底色 -->
        <rect x="60" y="60" width="400" height="230" rx="10" fill="rgba(251,191,36,.045)"/>
        <rect x="500" y="60" width="400" height="230" rx="10" fill="rgba(52,211,153,.05)"/>
        <rect x="60" y="320" width="400" height="230" rx="10" fill="rgba(248,113,113,.045)"/>
        <rect x="500" y="320" width="400" height="230" rx="10" fill="rgba(79,140,255,.05)"/>
        <!-- 轴 -->
        <line class="qaxis" x1="60" y1="305" x2="900" y2="305"/>
        <line class="qaxis" x1="480" y1="60" x2="480" y2="550"/>
        <text class="qaxislabel" x="70" y="80" text-anchor="start">← 问题解决</text>
        <text class="qaxislabel" x="890" y="80" text-anchor="end">特性支持 →</text>
        <text class="qaxislabel" x="470" y="72" text-anchor="end">待评审 open</text>
        <text class="qaxislabel" x="470" y="544" text-anchor="end">已定局 merged / closed</text>
        <!-- 象限标签 -->
        <text class="qlabel" x="80" y="105">问题解决 · 待评审(18)</text>
        <text class="qsub" x="80" y="120">挂死 / IPC / EPLB / Engram 周边修复主力区</text>
        <text class="qlabel" x="880" y="105" text-anchor="end">特性支持 · 待评审(13)</text>
        <text class="qsub" x="880" y="120" text-anchor="end">平台移植 + Engram 替代路径</text>
        <text class="qlabel" x="80" y="348">问题解决 · 已定局(4)</text>
        <text class="qsub" x="80" y="363">#218 已合入 · #179/#40/#38 已关闭</text>
        <text class="qlabel" x="880" y="348" text-anchor="end">特性支持 · 已定局(7)</text>
        <text class="qsub" x="880" y="363" text-anchor="end">#157 已合入 · ROCm 栈与 #243 已关闭</text>

        <!-- 左上:问题解决 open(18) -->
        <g transform="translate(110,175)"><g class="qb" style="animation-delay:0s"><circle r="16" fill="#fb923c" opacity=".9"/><text class="qtext">45</text></g></g>
        <g transform="translate(174,175)"><g class="qb" style="animation-delay:.3s"><circle r="16" fill="#fb923c" opacity=".9"/><text class="qtext">48</text></g></g>
        <g transform="translate(238,175)"><g class="qb" style="animation-delay:.6s"><circle r="16" fill="#fb923c" opacity=".9"/><text class="qtext">76</text></g></g>
        <g transform="translate(302,175)"><g class="qb" style="animation-delay:.9s"><circle r="16" fill="#fb923c" opacity=".9"/><text class="qtext">128</text></g></g>
        <g transform="translate(366,175)"><g class="qb" style="animation-delay:1.2s"><circle r="16" fill="#fb923c" opacity=".9"/><text class="qtext">158</text></g></g>
        <g transform="translate(430,175)"><g class="qb" style="animation-delay:1.5s"><circle r="16" fill="#fb923c" opacity=".9"/><text class="qtext">251</text></g></g>
        <g transform="translate(110,240)"><g class="qb" style="animation-delay:.15s"><circle r="16" fill="#34d399" opacity=".9"/><text class="qtext">81</text></g></g>
        <g transform="translate(174,240)"><g class="qb" style="animation-delay:.45s"><circle r="16" fill="#34d399" opacity=".9"/><text class="qtext">57</text></g></g>
        <g transform="translate(238,240)"><g class="qb" style="animation-delay:.75s"><circle r="16" fill="#f87171" opacity=".9"/><text class="qtext">50</text></g></g>
        <g transform="translate(302,240)"><g class="qb" style="animation-delay:1.05s"><circle r="16" fill="#fbbf24" opacity=".9"/><text class="qtext">107</text></g></g>
        <g transform="translate(366,240)"><g class="qb" style="animation-delay:1.35s"><circle r="16" fill="#fbbf24" opacity=".9"/><text class="qtext">191</text></g></g>
        <g transform="translate(430,240)"><g class="qb" style="animation-delay:1.65s"><circle r="16" fill="#fbbf24" opacity=".9"/><text class="qtext">212</text></g></g>
        <g transform="translate(110,140)"><g class="qb" style="animation-delay:.22s"><circle r="16" fill="#94a3b8" opacity=".9"/><text class="qtext">106</text></g></g>
        <g transform="translate(174,140)"><g class="qb" style="animation-delay:.52s"><circle r="16" fill="#94a3b8" opacity=".9"/><text class="qtext">232</text></g></g>
        <g transform="translate(238,140)"><g class="qb" style="animation-delay:.82s"><circle r="16" fill="#94a3b8" opacity=".9"/><text class="qtext">70</text></g></g>
        <g transform="translate(302,140)"><g class="qb" style="animation-delay:1.12s"><circle r="16" fill="#94a3b8" opacity=".9"/><text class="qtext">126</text></g></g>
        <g transform="translate(366,140)"><g class="qb" style="animation-delay:1.42s"><circle r="16" fill="#94a3b8" opacity=".9"/><text class="qtext">209</text></g></g>
        <g transform="translate(430,140)"><g class="qb" style="animation-delay:1.72s"><circle r="16" fill="#f472b6" opacity=".9"/><text class="qtext">236</text></g></g>

        <!-- 右上:特性支持 open(13) -->
        <g transform="translate(530,150)"><g class="qb" style="animation-delay:.1s"><circle r="17" fill="#a78bfa" opacity=".92"/><text class="qtext">138</text></g></g>
        <g transform="translate(594,150)"><g class="qb" style="animation-delay:.4s"><circle r="17" fill="#a78bfa" opacity=".92"/><text class="qtext">201</text></g></g>
        <g transform="translate(658,150)"><g class="qb" style="animation-delay:.7s"><circle r="16" fill="#a78bfa" opacity=".92"/><text class="qtext">92</text></g></g>
        <g transform="translate(722,150)"><g class="qb" style="animation-delay:1s"><circle r="16" fill="#a78bfa" opacity=".92"/><text class="qtext">148</text></g></g>
        <g transform="translate(786,150)"><g class="qb" style="animation-delay:1.3s"><circle r="16" fill="#a78bfa" opacity=".92"/><text class="qtext">180</text></g></g>
        <g transform="translate(530,230)"><g class="qb" style="animation-delay:.25s"><circle r="15" fill="#a78bfa" opacity=".92"/><text class="qtext">46</text></g></g>
        <g transform="translate(594,230)"><g class="qb" style="animation-delay:.55s"><circle r="15" fill="#a78bfa" opacity=".92"/><text class="qtext">193</text></g></g>
        <g transform="translate(658,230)"><g class="qb" style="animation-delay:.85s"><circle r="15" fill="#34d399" opacity=".92"/><text class="qtext">64</text></g></g>
        <g transform="translate(722,230)"><g class="qb" style="animation-delay:1.15s"><circle r="16" fill="#22d3ee" opacity=".92"/><text class="qtext">99</text></g></g>
        <g transform="translate(786,230)"><g class="qb" style="animation-delay:1.45s"><circle r="16" fill="#22d3ee" opacity=".92"/><text class="qtext">200</text></g></g>
        <g transform="translate(850,230)"><g class="qb" style="animation-delay:1.75s"><circle r="16" fill="#22d3ee" opacity=".92"/><text class="qtext">246</text></g></g>
        <g transform="translate(530,280)"><g class="qb" style="animation-delay:.6s"><circle r="16" fill="#22d3ee" opacity=".92"/><text class="qtext">248</text></g></g>
        <g transform="translate(594,280)"><g class="qb" style="animation-delay:.95s"><circle r="15" fill="#4f8cff" opacity=".92"/><text class="qtext">186</text></g></g>

        <!-- 左下:问题解决 已定局(4) -->
        <g transform="translate(150,420)"><g class="qb" style="animation-delay:.2s"><circle r="16" fill="#34d399" opacity=".9"/><text class="qtext">40</text></g></g>
        <g transform="translate(230,420)"><g class="qb" style="animation-delay:.5s"><circle r="16" fill="#fb923c" opacity=".9"/><text class="qtext">38</text></g></g>
        <g transform="translate(310,420)"><g class="qb" style="animation-delay:.8s"><circle r="16" fill="#4f8cff" opacity=".9"/><text class="qtext">179</text></g></g>
        <g transform="translate(390,420)">
          <circle class="qring" r="20" fill="none" stroke="#34d399" stroke-width="2"/>
          <g class="qb" style="animation-delay:1.1s"><circle r="16" fill="#f87171" opacity=".95"/><text class="qtext">218</text></g>
        </g>
        <text class="qsub" x="390" y="455" text-anchor="middle">已合入 ✓</text>

        <!-- 右下:特性支持 已定局(7) -->
        <g transform="translate(560,420)">
          <circle class="qring" r="20" fill="none" stroke="#34d399" stroke-width="2"/>
          <g class="qb" style="animation-delay:.3s"><circle r="16" fill="#4f8cff" opacity=".95"/><text class="qtext">157</text></g>
        </g>
        <text class="qsub" x="560" y="455" text-anchor="middle">已合入 ✓</text>
        <g transform="translate(650,400)"><g class="qb" style="animation-delay:.6s"><circle r="15" fill="#a78bfa" opacity=".85"/><text class="qtext">202</text></g></g>
        <g transform="translate(714,400)"><g class="qb" style="animation-delay:.9s"><circle r="15" fill="#a78bfa" opacity=".85"/><text class="qtext">203</text></g></g>
        <g transform="translate(778,400)"><g class="qb" style="animation-delay:1.2s"><circle r="15" fill="#a78bfa" opacity=".85"/><text class="qtext">204</text></g></g>
        <g transform="translate(842,400)"><g class="qb" style="animation-delay:1.5s"><circle r="15" fill="#a78bfa" opacity=".85"/><text class="qtext">205</text></g></g>
        <g transform="translate(650,460)"><g class="qb" style="animation-delay:.75s"><circle r="15" fill="#a78bfa" opacity=".85"/><text class="qtext">206</text></g></g>
        <g transform="translate(714,460)"><g class="qb" style="animation-delay:1.05s"><circle r="15" fill="#22d3ee" opacity=".85"/><text class="qtext">243</text></g></g>
        <text class="qsub" x="778" y="464" text-anchor="middle">并入 #201 / 主题被 #248 接力</text>

        <!-- 图例 -->
        <text class="qlegend" x="60" y="590">主题图例:</text>
        <rect x="130" y="581" width="11" height="11" rx="3" fill="#a78bfa"/><text class="qlegend" x="146" y="591">通信库适配(12)</text>
        <rect x="252" y="581" width="11" height="11" rx="3" fill="#22d3ee"/><text class="qlegend" x="268" y="591">Engram 路径(5)</text>
        <rect x="368" y="581" width="11" height="11" rx="3" fill="#4f8cff"/><text class="qlegend" x="384" y="591">DeepEP(3)</text>
        <rect x="470" y="581" width="11" height="11" rx="3" fill="#34d399"/><text class="qlegend" x="486" y="591">进程组/拓扑(4)</text>
        <rect x="604" y="581" width="11" height="11" rx="3" fill="#fbbf24"/><text class="qlegend" x="620" y="591">EPLB(3)</text>
        <rect x="694" y="581" width="11" height="11" rx="3" fill="#fb923c"/><text class="qlegend" x="710" y="591">SHM/IPC(7)</text>
        <rect x="796" y="581" width="11" height="11" rx="3" fill="#f87171"/><text class="qlegend" x="812" y="591">挂死/配置(2)</text>
        <rect x="130" y="606" width="11" height="11" rx="3" fill="#94a3b8"/><text class="qlegend" x="146" y="616">Engram 周边(5)</text>
        <rect x="252" y="606" width="11" height="11" rx="3" fill="#f472b6"/><text class="qlegend" x="268" y="616">调度耦合(1)</text>
        <text class="qlegend" x="368" y="616">气泡 = PR 编号;浮动动画;✓ = 已合入</text>
      </svg>
      <div class="cap">图 5-1 · 特性支持 / 问题解决 × 待评审 / 已定局 四象限(42 个气泡,SVG 浮动动画)。问题解决类集中在左上(18 个待评审),特性支持类集中在右上(13 个);已定局的 11 个中仅 #157/#218 两个真正合入。</div>
    </div>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🎯</span>象限读法一:修复类几乎全部滞留评审</h3>
        <p>22 个问题解决 PR 中 18 个 open、3 个 closed、<b>仅 #218 一个合入</b>。挂死三连(#57/#50/#48)、IPC 加固(#158/#76/#45)、EPLB 三部曲都带着完整复现与 CPU/Gloo 回归测试,但仍未获官方合入——社区修复的「验证充分度」与「合入速度」明显不成比例。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🚀</span>象限读法二:特性类的三种归宿</h3>
        <p>20 个特性 PR:13 个 open 待评审(SM90×3、ROCm×1、SM120×1、Ascend×2、Engram×4、其他×2);6 个 closed 中 5 个是 ROCm 拆分栈自主并入 #201(流程性关闭,非否决),#243 主题被 #248 接力;<b>唯一合入的特性 PR 是 #157</b>——一次 3 行的依赖升级。</p>
      </div>
    </div>
  </section>

  <!-- ================= 6 趋势洞察 ================= -->
  <section id="s6">
    <h2 class="sec"><span class="num">6</span>趋势洞察:NCCL 生态的三个演进方向</h2>
    <p class="lede">把 42 个 PR 放回时间轴,可以清晰读出社区对 DeepInfer 通信栈的三条改造主线。</p>

    <h3 style="color:#fff;font-size:15px;margin:20px 0 4px">6.1 方向一:Engram 通信演进——从「唯一 GIN 路径」到「多路径可选」</h3>
    <div class="figure reveal">
      <div class="anchor-flow">
        <div class="fnode"><b>DeepEP 默认</b>NCCL GIN / GDAKI<br><span style="color:var(--muted);font-size:11px">单边 RDMA get · 硬依赖</span></div>
        <span class="arr">➤</span>
        <div class="fnode"><b>#99 · 10-20</b>NVLink 集合版<br><span style="color:var(--muted);font-size:11px">all_to_all_single · 目标「能跑」</span></div>
        <span class="arr">➤</span>
        <div class="fnode"><b>#200 · 10-22</b>UVA 读 host 表<br><span style="color:var(--muted);font-size:11px">绕开 CPU proxy · 1.44-1.79×</span></div>
        <span class="arr">➤</span>
        <div class="fnode"><b>#246 · 10-28</b>对称内存直读<br><span style="color:var(--muted);font-size:11px">NVLink peer domain · 94-101%</span></div>
        <span class="arr">➤</span>
        <div class="fnode"><b>#248 · 10-29</b>RDMA QP 调优<br><span style="color:var(--muted);font-size:11px">NUM_QPS 覆盖 · 多网卡拓扑</span></div>
      </div>
      <div class="cap">图 6-1 · Engram fetch 路径演进流(箭头流动动画)。旁支:#243(10-27,closed)尝试从 buffer 尺寸侧解耦 QP 数;#138(10-21)在 SM120 上用 PyTorch collectives 重写 Engram 交换。</div>
    </div>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🧩</span>五天之内三种替代路径并存</h3>
        <p>10-20 ~ 10-29 之间出现了<b>三条并行的 Engram 替代路径</b>(集合通信 #99、UVA #200、对称内存 #246)加<b>一条调优路径</b>(QP 覆盖 #248)。这说明 <code>EngramBuffer.fetch</code> 对 NCCL GIN 的硬依赖是社区感知最强的单点风险:云单机、实验室节点、KVM guest(GDAKI 静默 CPU proxy)全都会踩中。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">📉</span>问题从「不能跑」升级到「不够快」</h3>
        <p>#99/#200 解决可用性(GIN 缺失/静默回退),#246/#248 已转向性能(对齐官方曲线 94-101%、QP 数与真实 NIC 拓扑匹配)。诊断手段也在进化:从 <code>EP_DISABLE_GIN=1</code> 二分,到 <code>NCCL_GIN_GDAKI_NIC_HANDLER</code>、<code>ib_read_bw</code>、gdb 抓 <code>ncclGinProgress</code> 的系统级排查。</p>
      </div>
    </div>

    <h3 style="color:#fff;font-size:15px;margin:26px 0 4px">6.2 方向二:通信库生态适配——NCCL 之外的后备役</h3>
    <div class="reveal">
    <table class="tbl">
      <tr><th>平台方向</th><th>PR</th><th>通信库策略</th><th>状态</th></tr>
      <tr><td>AMD ROCm(MI350X/MI355X)</td><td>#201(原 #202~#206)</td><td><b>RCCL 经 nccl backend</b>;EPBuffer/EngramBuffer/BucketBuffer 重写为 torch 对称内存 + async RCCL;<code>NCCL_RAS_ENABLE=0</code></td><td><span class="badge open">open</span></td></tr>
      <tr><td>NVIDIA SM120(RTX PRO 6000)</td><td>#138</td><td><b>PyTorch collectives</b>(AllGather/ReduceScatter/broadcast+reduce)整体替换 DeepEP 专用路径;DeepEP 按需导入</td><td><span class="badge open">open</span></td></tr>
      <tr><td>NVIDIA SM90(Hopper)</td><td>#92 / #148 / #180 / #235</td><td>沿用 NCCL;验证 EP/CP 通信与 CUDA graphs;Engram GIN 原生验证进行中(#148)</td><td><span class="badge open">open</span></td></tr>
      <tr><td>华为 Ascend(910B/910C/950)</td><td>#193 / #46</td><td>HCCL 体系;910C RFC 明确「MoE/Engram/设备间通信」为适配重点</td><td><span class="badge open">open</span></td></tr>
      <tr><td>其他(Biren/MUSA/MPS/XPU)</td><td>#64 / #179 背景 / #59 / #67</td><td>vendor-neutral 设备可见性(#64);DeepEP 导入解耦诉求(#179 的 MUSA 场景)</td><td><span class="badge open">open</span></td></tr>
    </table>
    </div>
    <div class="note"><b>关键信号:</b>#138 在 SM120 上直接选择 PyTorch collectives 而非寻找 DeepEP 替代品、#179 因 MUSA 平台只有 DeepEP v1 而在导入期崩溃——两条线索共同指向:<b>「没有 DeepEP/NCCL 定制路径也要能跑」正在成为事实上的架构需求</b>。#205 在 ROCm 上的做法(把 DeepEP 三大 buffer 全部重写在 torch 对称内存上)则是同一需求的另一种实现。</div>

    <h3 style="color:#fff;font-size:15px;margin:26px 0 4px">6.3 方向三:分布式正确性与挂死治理</h3>
    <ul class="feat reveal">
      <li><b>集合参与完整性</b>:#50(空 DP 分片必须参与跨 DP 完成集合)、#57(launcher 不得在 join() 中对 worker 失败失明)——两 PR 共同界定「谁必须留在集合里、谁负责看门」;</li>
      <li><b>初始化与拓扑</b>:#81(IPv6 URL)、closed #40(启动拓扑显式校验)、#64(设备可见性中立化)覆盖进程组建立的前置条件;</li>
      <li><b>IPC 生命周期</b>:#76(shm unlink)、#45(MQ 超时)、#158(pickle→JSON)、#48/#38/#251(共享池死锁与自旋)——shm_broadcast 与 SharedTorchMemoryPool 是 worker 间控制面/数据面的两块共享地基;</li>
      <li><b>配置健壮性</b>:已合入的 #218 让全部布尔通信开关(EP_DISABLE_GIN、DEEPINFER_ENGRAM_* 等)获得严格解析——这是唯一进入主干的问题解决类通信修复。</li>
    </ul>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🔁</span>竞争性提交:同一问题两拨人修</h3>
        <p>42 个 PR 中有四组「撞车」:<b>#106 vs #232</b>(Engram 设备拓宽崩溃,不同作者同根因)、<b>#38 vs #251</b>(共享池超容量自旋,前者被关后者重提)、<b>#191 vs #212</b>(EPLB 平局,互为竞合方案且互相验证)、<b>#202~#206 vs #201</b>(同一作者自我整合)。开源首日爆发的必然结果,也说明这些问题真实而高频。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🌐</span>外围生态:不走集合通信的跨节点传输</h3>
        <p>PD 分离方向的 #197(两主机 prefill/decode 分离,KV+SWA 状态走 TCP)、#214(Mooncake Transfer Engine 数据面,--kv-transport mooncake)、#216(Mooncake Store 作为 L3 前缀缓存)不属于 NCCL 集合通信域,但共享「跨主机数据面」的工程关切——RDMA/TCP 传输与集合通信构成 DeepInfer 通信版图的两个半球。</p>
      </div>
    </div>
  </section>

  <!-- ================= 7 总结 ================= -->
  <section id="s7">
    <h2 class="sec"><span class="num">7</span>总结</h2>
    <p class="lede">11 天、224 个 PR、42 个通信相关——一张高度活跃但几乎未开始合入的通信生态全景。</p>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📌</span>核心数字</h3>
        <ul class="feat">
          <li>NCCL/通信相关 PR <b>42 / 224(18.8%)</b>,来自 34 位贡献者,覆盖 9 大主题;</li>
          <li>状态:<b>open 31 · closed 9 · merged 2</b>;象限:特性 20 · 问题解决 22;</li>
          <li>唯二合入 <b>#157</b>(DeepEP bump,仓库首个合入)与 <b>#218</b>(布尔环境变量严格解析)——均为 DeepSeek 成员提交的小体量关键改动;</li>
          <li>通信主题最大两类:平台/通信库适配 12 个、SHM/IPC 7 个;Engram 直接相关 5 + 周边 5 个。</li>
        </ul>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧭</span>三条主线结论</h3>
        <ul class="feat">
          <li><b>Engram/DeepEP 是最大战场</b>:GIN 硬依赖催生 3 条替代路径 + 1 条调优路径(五天内密集出现),外加导入解耦(#179)与版本管理(#157/#186);</li>
          <li><b>通信栈解耦是跨平台共识</b>:RCCL/PyTorch collectives/HCCL 三线并进,#138 与 #205 展示了「不用 DeepEP 也能跑」的两种工程答案;</li>
          <li><b>分布式正确性修复验证充分但合入停滞</b>:挂死/IPC/EPLB 修复普遍自带 CPU/Gloo 回归与独立验证,却仅有 #218 一个进入主干。</li>
        </ul>
      </div>
    </div>
    <div class="note good"><b>展望:</b>随着 #99/#246/#248 等 Engram 路径 PR 与 #201 ROCm 后端进入评审深水区,DeepInfer 的通信层很可能从「DeepEP+NCCL 单栈」演进为「默认 GIN + 可选 NVLink/UVA/对称内存 + 平台 collectives」的多层可选架构;而 DP/CP/EP 启动与 SHM 控制面的正确性修复(#57/#50/#45/#76/#158)一旦合入,将显著改善多机多卡场景的工程可靠性。对二次开发者的建议:优先跟踪 <code>parallel_utils/</code>(userbuffer.py/cp.py 是 9 个 PR 的共同落点)与 <code>deepinfer/environ.py</code>(6 个 PR 新增通信开关)两个热点文件。</div>
    <div class="note warn"><b>数据口径说明:</b>本页全部 PR 数据取自 GitHub REST API(pulls 列表与单 PR 详情、files、issue comments),统计截至 2026-11-01;PR 标题/正文为英文原文的中文摘要,机制与性能数字均引自 PR 描述原文,未做推测。closed 但无评论的 PR(#38/#40/#243)关闭原因标注为「未公开说明」。</div>
  </section>

  <div class="pgnav">
    <span>DeepInfer 代码分析系列 · 由 ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/deepinfer/">← 返回系列总览</a> · <a href="/docs/inference-engines/deepinfer/08-nccl-usage/">⑧ NCCL 使用场景</a> · <a href="/docs/inference-engines/deepinfer/10-cross-card-comm/">⑩ 跨卡通信行为 →</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));
// 统计数字滚动动画
const cio=new IntersectionObserver(es=>{es.forEach(e=>{
  if(!e.isIntersecting)return; cio.unobserve(e.target);
  const el=e.target, target=parseInt(el.dataset.count,10), dur=1300, t0=performance.now();
  (function tick(t){const p=Math.min(1,(t-t0)/dur), k=1-Math.pow(1-p,3);
    el.textContent=Math.round(target*k); if(p<1)requestAnimationFrame(tick);})(t0);
})},{threshold:.4});
document.querySelectorAll('[data-count]').forEach(el=>cio.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/10-cross-card-comm/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/10-cross-card-comm/</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 .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 的跨卡通信不是"一个 NCCL 搞定"，而是一个清晰的四层栈：应用行为层定义<b>通信什么</b>，框架抽象层定义<b>如何组织</b>，通信库层定义<b>谁发报文</b>，链路层定义<b>走哪条线</b>。重数据面（MoE token、Engram 表项、CP 聚合）全部绕开 NCCL 走 DeepEP-V2 / SymmBuffer，NCCL/HCCL 只承担控制面与轻量数据面。</p>

    <div class="figure">
      <svg viewBox="0 0 960 700" xmlns="http://www.w3.org/2000/svg">
        <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="#4f8cff"/>
          </marker>
          <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="#22d3ee"/>
          </marker>
          <linearGradient id="lg1" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stop-color="#1b2a4a" stop-opacity=".25"/><stop offset="1" stop-color="#4f8cff" stop-opacity=".55"/>
          </linearGradient>
        </defs>

        <!-- Layer 1 应用行为层 -->
        <rect x="20" y="16" width="920" height="150" rx="14" fill="#101b33" stroke="#4f8cff" stroke-opacity=".55"/>
        <text x="40" y="42" fill="#fff" font-size="15" font-weight="700">① 应用行为层（通信什么）</text>
        <text x="330" y="42" fill="#8ea0c2" font-size="11">parallel_utils + models/v4_modules + eplb + engine/worker</text>
        <g font-size="11.5" fill="#dbe4f5">
          <rect x="40" y="58" width="200" height="34" rx="8" fill="rgba(34,211,238,.12)" stroke="#22d3ee" stroke-opacity=".5"/>
          <text x="52" y="79" fill="#22d3ee">MoE dispatch / combine</text>
          <rect x="252" y="58" width="170" height="34" rx="8" fill="rgba(34,211,238,.12)" stroke="#22d3ee" stroke-opacity=".5"/>
          <text x="264" y="79" fill="#22d3ee">Engram fetch / write</text>
          <rect x="434" y="58" width="160" height="34" rx="8" fill="rgba(34,211,238,.12)" stroke="#22d3ee" stroke-opacity=".5"/>
          <text x="446" y="79" fill="#22d3ee">CP all-gather 会话</text>
          <rect x="606" y="58" width="160" height="34" rx="8" fill="rgba(52,211,153,.12)" stroke="#34d399" stroke-opacity=".5"/>
          <text x="618" y="79" fill="#34d399">EPLB 计数/重排</text>
          <rect x="778" y="58" width="148" height="34" rx="8" fill="rgba(79,140,255,.12)" stroke="#4f8cff" stroke-opacity=".5"/>
          <text x="790" y="79" fill="#4f8cff">引擎/调度同步</text>
          <rect x="40" y="112" width="286" height="34" rx="8" fill="rgba(79,140,255,.12)" stroke="#4f8cff" stroke-opacity=".5"/>
          <text x="52" y="133" fill="#4f8cff">元数据/张量广播（broadcast_tensor_dict）</text>
          <rect x="338" y="112" width="240" height="34" rx="8" fill="rgba(167,139,250,.12)" stroke="#a78bfa" stroke-opacity=".5"/>
          <text x="350" y="133" fill="#a78bfa">mega-MoE 对称内存直读</text>
          <rect x="590" y="112" width="140" height="34" rx="8" fill="rgba(251,191,36,.10)" stroke="#fbbf24" stroke-opacity=".5"/>
          <text x="602" y="133" fill="#fbbf24">采样：无集合通信</text>
          <rect x="742" y="112" width="184" height="34" rx="8" fill="rgba(248,113,113,.10)" stroke="#f87171" stroke-opacity=".5"/>
          <text x="754" y="133" fill="#f87171">权重加载：各自读盘</text>
        </g>

        <!-- vertical flows -->
        <g stroke="#4f8cff" stroke-width="1.6">
          <line x1="230" y1="166" x2="230" y2="208" class="flowline" marker-end="url(#arr)"/>
          <line x1="480" y1="166" x2="480" y2="208" class="flowline" marker-end="url(#arr)"/>
          <line x1="730" y1="166" x2="730" y2="208" class="flowline" marker-end="url(#arr)"/>
        </g>

        <!-- Layer 2 框架抽象层 -->
        <rect x="20" y="212" width="920" height="128" rx="14" fill="#101b33" stroke="#a78bfa" stroke-opacity=".55"/>
        <text x="40" y="238" fill="#fff" font-size="15" font-weight="700">② 框架抽象层（如何组织）</text>
        <text x="330" y="238" fill="#8ea0c2" font-size="11">进程组拓扑 · 会话 · 事件重叠 · SM 配额</text>
        <g font-size="11.5">
          <rect x="40" y="254" width="270" height="34" rx="8" fill="rgba(167,139,250,.12)" stroke="#a78bfa" stroke-opacity=".5"/>
          <text x="52" y="275" fill="#a78bfa">userbuffer（_UserBufferManager）</text>
          <rect x="322" y="254" width="170" height="34" rx="8" fill="rgba(167,139,250,.12)" stroke="#a78bfa" stroke-opacity=".5"/>
          <text x="334" y="275" fill="#a78bfa">CPManager 会话聚合</text>
          <rect x="504" y="254" width="200" height="34" rx="8" fill="rgba(167,139,250,.12)" stroke="#a78bfa" stroke-opacity=".5"/>
          <text x="516" y="275" fill="#a78bfa">communication_op 工具</text>
          <rect x="716" y="254" width="210" height="34" rx="8" fill="rgba(167,139,250,.12)" stroke="#a78bfa" stroke-opacity=".5"/>
          <text x="728" y="275" fill="#a78bfa">PG（parallel_state 拓扑）</text>
          <rect x="40" y="296" width="430" height="34" rx="8" fill="rgba(79,140,255,.10)" stroke="#4f8cff" stroke-opacity=".35"/>
          <text x="52" y="317" fill="#8ea0c2">EventOverlap / current_stream_wait · limit_num_sms 通信-计算 SM 让渡</text>
          <rect x="482" y="296" width="444" height="34" rx="8" fill="rgba(79,140,255,.10)" stroke="#4f8cff" stroke-opacity=".35"/>
          <text x="494" y="317" fill="#8ea0c2">NCCLMemoryStatsLogger（communicator 显存观测）· DecodePerfCache</text>
        </g>

        <g stroke="#4f8cff" stroke-width="1.6">
          <line x1="230" y1="340" x2="230" y2="382" class="flowline" marker-end="url(#arr)"/>
          <line x1="480" y1="340" x2="480" y2="382" class="flowline" marker-end="url(#arr)"/>
          <line x1="730" y1="340" x2="730" y2="382" class="flowline" marker-end="url(#arr)"/>
        </g>

        <!-- Layer 3 通信库层 -->
        <rect x="20" y="386" width="920" height="150" rx="14" fill="#101b33" stroke="#22d3ee" stroke-opacity=".55"/>
        <text x="40" y="412" fill="#fff" font-size="15" font-weight="700">③ 通信库层（谁发报文）</text>
        <g font-size="11.5">
          <rect x="40" y="428" width="262" height="42" rx="8" fill="rgba(34,211,238,.14)" stroke="#22d3ee"/>
          <text x="52" y="447" fill="#22d3ee" font-weight="700">DeepEP-V2（vendor/DeepEP）</text>
          <text x="52" y="463" fill="#8ea0c2">EPBuffer · EngramBuffer · BucketBuffer</text>
          <rect x="314" y="428" width="190" height="42" rx="8" fill="rgba(251,191,36,.12)" stroke="#fbbf24" stroke-opacity=".6"/>
          <text x="326" y="447" fill="#fbbf24" font-weight="700">NCCL / HCCL</text>
          <text x="326" y="463" fill="#8ea0c2">torch.distributed 设备组后端</text>
          <rect x="516" y="428" width="140" height="42" rx="8" fill="rgba(79,140,255,.12)" stroke="#4f8cff" stroke-opacity=".6"/>
          <text x="528" y="447" fill="#4f8cff" font-weight="700">gloo</text>
          <text x="528" y="463" fill="#8ea0c2">CPU 集合通信（TCP）</text>
          <rect x="668" y="428" width="258" height="42" rx="8" fill="rgba(52,211,153,.12)" stroke="#34d399" stroke-opacity=".6"/>
          <text x="680" y="447" fill="#34d399" font-weight="700">DeepGEMM SymmBuffer</text>
          <text x="680" y="463" fill="#8ea0c2">NVLink 对称内存零拷贝（含 Ascend）</text>
          <rect x="40" y="480" width="300" height="42" rx="8" fill="rgba(167,139,250,.12)" stroke="#a78bfa" stroke-opacity=".6"/>
          <text x="52" y="499" fill="#a78bfa" font-weight="700">torch symm_mem（IPC 镜像）</text>
          <text x="52" y="515" fill="#8ea0c2">EPLB 单机专家权重搬运</text>
          <rect x="352" y="480" width="300" height="42" rx="8" fill="rgba(79,140,255,.12)" stroke="#4f8cff" stroke-opacity=".6"/>
          <text x="364" y="499" fill="#4f8cff" font-weight="700">shm + ZeroMQ（MessageQueue）</text>
          <text x="364" y="515" fill="#8ea0c2">CP 组 python 对象广播（不经网络栈）</text>
          <rect x="664" y="480" width="262" height="42" rx="8" fill="rgba(251,191,36,.08)" stroke="#fbbf24" stroke-opacity=".35"/>
          <text x="676" y="499" fill="#fbbf24">DEEPINFER_NCCL_NUM_SMS=32</text>
          <text x="676" y="515" fill="#8ea0c2">DEEPINFER_USERBUFFER_COMM_SMS 自动推导</text>
        </g>

        <g stroke="#22d3ee" stroke-width="1.6">
          <line x1="230" y1="536" x2="230" y2="578" class="flowline" marker-end="url(#arrC)"/>
          <line x1="480" y1="536" x2="480" y2="578" class="flowline" marker-end="url(#arrC)"/>
          <line x1="730" y1="536" x2="730" y2="578" class="flowline" marker-end="url(#arrC)"/>
        </g>

        <!-- Layer 4 链路层 -->
        <rect x="20" y="582" width="920" height="98" rx="14" fill="#0d1526" stroke="#34d399" stroke-opacity=".45"/>
        <text x="40" y="608" fill="#fff" font-size="15" font-weight="700">④ 链路层（走哪条线）</text>
        <g font-size="11.5">
          <rect x="40" y="624" width="200" height="40" rx="8" fill="rgba(52,211,153,.10)" stroke="#34d399" stroke-opacity=".5"/>
          <text x="52" y="641" fill="#34d399">NVLink / NVSwitch</text>
          <text x="52" y="657" fill="#8ea0c2">域内 kernel 直写（P2P）</text>
          <rect x="252" y="624" width="250" height="40" rx="8" fill="rgba(251,191,36,.10)" stroke="#fbbf24" stroke-opacity=".5"/>
          <text x="264" y="641" fill="#fbbf24">RoCEv2 / IB RDMA（QP）</text>
          <text x="264" y="657" fill="#8ea0c2">跨域 one-sided · sl3=EP / sl2=KV</text>
          <rect x="514" y="624" width="200" height="40" rx="8" fill="rgba(79,140,255,.10)" stroke="#4f8cff" stroke-opacity=".5"/>
          <text x="526" y="641" fill="#4f8cff">TCP / PCIe（gloo）</text>
          <text x="526" y="657" fill="#8ea0c2">CPU 控制面报文</text>
          <rect x="726" y="624" width="200" height="40" rx="8" fill="rgba(167,139,250,.10)" stroke="#a78bfa" stroke-opacity=".5"/>
          <text x="738" y="641" fill="#a78bfa">POSIX shm + ZMQ TCP</text>
          <text x="738" y="657" fill="#8ea0c2">节点内零拷贝 · 跨机回退 TCP</text>
        </g>

        <!-- 移动数据包 -->
        <circle r="4" fill="#22d3ee" class="barrow">
          <animateMotion dur="3.2s" repeatCount="indefinite" path="M110,160 L110,210 L110,386 L110,582 L110,640"/>
        </circle>
        <circle r="4" fill="#fbbf24" class="barrow">
          <animateMotion dur="3.8s" repeatCount="indefinite" path="M850,160 L850,386 L850,582 L850,640"/>
        </circle>
        <circle r="4" fill="#a78bfa" class="barrow">
          <animateMotion dur="4.4s" repeatCount="indefinite" path="M500,160 L500,386 L500,536"/>
        </circle>
      </svg>
      <div class="cap">图 1-1 · DeepInfer 四层通信栈：应用行为 → 框架抽象 → 通信库 → 物理链路。青色数据包代表 DeepEP 数据面，橙色代表 NCCL/gloo 控制面，紫色代表 shm 对象广播。</div>
    </div>

    <div class="grid c3">
      <div class="card reveal">
        <h3><span class="ico">🔥</span>重数据面：三巨头</h3>
        <p>MoE dispatch/combine（<code>EPBuffer</code>）、Engram 稀疏 fetch（<code>EngramBuffer</code>，RDMA QP）、CP all-gather（<code>BucketBuffer</code>）全部由 <b>DeepEP-V2</b> 承担；NVLink 域内的 MoE 更进一步升级为 <b>DeepGEMM mega-MoE + SymmBuffer</b> 对称内存零拷贝路径，连 DeepEP 都省了。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🎛</span>NCCL/HCCL 的新角色</h3>
        <p>设备组后端退居<b>控制面与轻量数据面</b>：CP 元数据张量 broadcast、EPLB 专家计数 all-reduce / 权重 P2P 迁移、引擎步进同步（8 字节）、KV 块数协商与 communicator 预热。SM 数被限制为 <code>DEEPINFER_NCCL_NUM_SMS=32</code>（platform.py:81-82）。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🧠</span>控制面零占 GPU</h3>
        <p>默认 world 进程组直接用 <b>gloo</b> 初始化（worker/base.py:334-340），另有 cpu_dp / cpu_cp / cpu_ep_in_dp 三条专用 gloo 组；CP 组的 python 对象广播（slave RPC、InputMetadata 非 tensor 字段）走 <b>shm 环形缓冲 + ZeroMQ</b>，连网络协议栈都不碰。</p>
      </div>
    </div>
  </section>

  <!-- ================= 2. 进程组拓扑 ================= -->
  <section id="sec2">
    <h2 class="sec"><span class="num">2</span>进程组拓扑：一切通信的坐标系</h2>
    <p class="lede"><code>parallel_utils/parallel_state.py</code> 中的 <code>ParallelProcessGroup</code>（单例 <code>PG</code>）一次性建出 9 条设备组（NCCL/HCCL）+ 3 条 gloo 组 + 1 条 shm 消息队列。所有通信行为都挂在这些组上，先看懂组再看通信。</p>

    <div class="filepath">deepinfer/model_executor/parallel_utils/parallel_state.py</div>
    <pre class="code"><span class="c"># create_process_groups()：dp/cp_size 决定世界切分（parallel_state.py:70-126）</span>
backend <span class="k">=</span> <span class="n">PLATFORM</span>.distributed_backend            <span class="c"># GPU→"nccl"  NPU→"hccl"（platform.py:58/89）</span>
options <span class="k">=</span> <span class="n">PLATFORM</span>.get_distributed_options()     <span class="c"># NCCL: max/min_ctas=DEEPINFER_NCCL_NUM_SMS</span>
self.world    <span class="k">=</span> <span class="f">_split_group</span>([ranks], backend, options)          <span class="c"># :86 全体</span>
self.local    <span class="k">=</span> <span class="f">_split_group</span>(每 rank 单独一组, backend, options)  <span class="c"># :89 单卡组</span>
self.dp       <span class="k">=</span> <span class="f">_split_group</span>(dp_ranks, backend, options)        <span class="c"># :93 数据并行（同请求不同副本）</span>
self.cpu_dp_group  <span class="k">=</span> <span class="f">_split_group</span>(dp_ranks, <span class="s">"gloo"</span>)          <span class="c"># :94 CPU 副本（调度投票）</span>
self.cp            <span class="k">=</span> <span class="f">_split_group</span>(cp_ranks, backend, options)   <span class="c"># :98 上下文并行（同请求分片）</span>
self.cpu_cp_group  <span class="k">=</span> <span class="f">_split_group</span>(cp_ranks, <span class="s">"gloo"</span>)          <span class="c"># :99 MQ 句柄交换</span>
self.ep       <span class="k">=</span> ... rearrange(<span class="s">"(edp ep) -> edp ep"</span>)              <span class="c"># :102-106 专家并行</span>
self.enp      <span class="k">=</span> ... rearrange(<span class="s">"(replica enp) -> replica enp"</span>)      <span class="c"># :108-110 Engram 表并行</span>
self.ep_in_dp <span class="k">=</span> ... (ep_size==1 时退化为 local)                    <span class="c"># :113-117</span>
self.cpu_ep_in_dp  <span class="k">=</span> <span class="f">_split_group</span>(ep_in_dp_ranks, <span class="s">"gloo"</span>)   <span class="c"># :118</span>
<span class="k">if</span> cp_size <span class="k">&gt;</span> <span class="n">1</span>:                                                        <span class="c"># :123-124 CP 组 shm 广播队列</span>
    self.mq <span class="k">=</span> MessageQueue.<span class="f">create_from_process_group</span>(self.cpu_cp_group, <span class="n">1</span><span class="k">&lt;&lt;</span><span class="n">20</span>, <span class="n">10</span>)</pre>

    <div class="note"><b>关键设计：gloo 是默认，NCCL/HCCL 是"按需子组"。</b>进程组初始化用 <code>dist.init_process_group(backend="gloo")</code>（worker/base.py:334-340，超时 <code>DEEPINFER_GLOO_TIMEOUT</code> 默认 14400 秒，environ.py:117），随后 <code>init_device_groups()</code>（parallel_state.py:173-187）对每条 nccl/hccl 子组执行一次 <code>dist.all_reduce(torch.zeros(1).cuda())</code> 强制 eager 建立 communicator——连单 rank 组也不能跳过，因为 Engram 的 deep_ep 经 <code>backend._comm_ptr()</code> 复用这里建出的 comm，空指针会直接段错误（注释见 parallel_state.py:174-177）。</div>

    <table class="tbl">
      <tr><th>进程组</th><th>后端</th><th>成员含义</th><th>典型用途（后续章节逐一展开）</th><th>代码位置</th></tr>
      <tr><td><code>PG.world</code></td><td><span class="badge nccl">NCCL/HCCL</span></td><td>全部 rank</td><td>KV 块数 all-reduce（SUM）、EPLB（ep_size==world 时同组）</td><td>parallel_state.py:86</td></tr>
      <tr><td><code>PG.local</code></td><td><span class="badge nccl">NCCL/HCCL</span></td><td>单 rank</td><td>ep_size==1 时的 ep_in_dp 退化目标</td><td>parallel_state.py:89</td></tr>
      <tr><td><code>PG.dp</code> / <code>cpu_dp_group</code></td><td><span class="badge nccl">NCCL/HCCL</span> + <span class="badge">gloo</span></td><td>同一请求序列的不同副本</td><td>引擎步进同步 all-reduce(MAX)；C++ 调度器 prefill 投票；DP 调度协调</td><td>parallel_state.py:93-94</td></tr>
      <tr><td><code>PG.cp</code> / <code>cpu_cp_group</code></td><td><span class="badge nccl">NCCL/HCCL</span> + <span class="badge">gloo</span></td><td>同一请求序列的 token 分片</td><td>DeepEP BucketBuffer all-gather；张量 broadcast；对象 shm 广播（mq）</td><td>parallel_state.py:98-99, 123-124</td></tr>
      <tr><td><code>PG.ep</code></td><td><span class="badge nccl">NCCL/HCCL</span>（DeepEP 自建通道）</td><td>全体专家所在 rank</td><td>MoE dispatch/combine、EPLB 计数 all-reduce 与权重迁移、decode perf 同步</td><td>parallel_state.py:102-106</td></tr>
      <tr><td><code>PG.enp</code></td><td><span class="badge nccl">NCCL/HCCL</span>（DeepEP 自建通道）</td><td>Engram n-gram 表分片</td><td>EngramBuffer write/fetch（RDMA QP）、sf all-gather_into_tensor</td><td>parallel_state.py:108-110</td></tr>
      <tr><td><code>PG.ep_in_dp</code> / <code>cpu_ep_in_dp</code></td><td><span class="badge nccl">NCCL/HCCL</span> + <span class="badge">gloo</span></td><td>DP 副本内的 EP 子组</td><td>多副本 EP 部署下的局部通信域</td><td>parallel_state.py:113-118</td></tr>
      <tr><td><code>PG.mq</code></td><td><span class="badge deepep">shm + ZeroMQ</span></td><td>CP 组（1 写多读）</td><td>cp_broadcast_object：slave RPC 方法调用、InputMetadata 非 tensor 字段</td><td>parallel_state.py:17-23, 123-124</td></tr>
    </table>
  </section>

  <!-- ================= 3. 总矩阵 ================= -->
  <section id="sec3">
    <h2 class="sec"><span class="num">3</span>跨卡通信行为总矩阵（核心交付）</h2>
    <p class="lede">对 <code>deepinfer/</code> 全目录 <code>dist.*</code>、<code>deep_ep</code>、<code>symm_mem</code>、<code>MessageQueue</code> 调用点的穷尽 grep 后逐一人工核实，共 <b>22 类</b>跨卡（或显式跨进程）通信行为。按数据量从重到轻排列。</p>

    <table class="tbl">
      <tr>
        <th style="width:4%">#</th><th style="width:14%">通信行为</th><th style="width:11%">触发时机</th><th style="width:6%">进程组</th>
        <th style="width:15%">API / 集合操作</th><th style="width:11%">底层通信库</th><th style="width:10%">链路</th><th style="width:16%">代码位置</th><th style="width:13%">数据量级</th>
      </tr>
      <tr><td>1</td><td><b>MoE token dispatch</b>（token 按路由发往专家所在卡）</td><td>每 forward × 每 MoE 层</td><td>ep</td><td><code>EPBuffer.dispatch(...)</code></td><td><span class="badge deepep">DeepEP-V2</span></td><td>NVLink 域内自研内核 / 跨域 RDMA（不经 NCCL）</td><td>mlp.py:469-490；buffer 分配 userbuffer.py:63-95</td><td>每 token topk×hidden×(1~2)B；GB/s 级</td></tr>
      <tr><td>2</td><td><b>MoE token combine</b>（专家输出加权归回原卡，融合 shared expert bias）</td><td>同上</td><td>ep</td><td><code>EPBuffer.combine(x, handle, bias=shared)</code></td><td><span class="badge deepep">DeepEP-V2</span></td><td>同上</td><td>mlp.py:493-511（"high-throughput chunked combine"）</td><td>与 dispatch 同量级</td></tr>
      <tr><td>3</td><td><b>mega-MoE 对称内存路径</b>（NVLink 域内替代 dispatch/combine）</td><td>use_mega_moe 命中时每 forward</td><td>ep</td><td><code>deep_gemm.fp8_fp4_mega_moe / bf16_mega_moe</code> + <code>SymmBuffer</code></td><td><span class="badge merged">DeepGEMM SymmBuffer</span></td><td>NVLink 对称内存，GEMM 直读对端（零报文）</td><td>mlp.py:184-188, 528-563；userbuffer.py:183-225</td><td>无显式报文；gate/topk 写入共享 buffer</td></tr>
      <tr><td>4</td><td><b>Engram n-gram 嵌入 fetch</b>（按 hash 跨卡稀疏拉取表项）</td><td>每 forward（Engram 层前）</td><td>enp</td><td><code>EngramBuffer.fetch(hashes)</code></td><td><span class="badge deepep">DeepEP-V2（RDMA QP）</span></td><td>RDMA one-sided read；NVLink 域内直读</td><td>engram.py:214-219；deepseek.py:177-188</td><td>每 token num_entries_per_token 行 × hidden，稀疏 KB~MB</td></tr>
      <tr><td>5</td><td><b>Engram 表初始化写入 + scale factor 收集</b></td><td>模型加载后一次</td><td>enp</td><td><code>EngramBuffer.write(weights, sfs)</code> + <code>dist.all_gather_into_tensor</code></td><td><span class="badge deepep">DeepEP</span> + <span class="badge nccl">NCCL/HCCL</span></td><td>RDMA 注册内存写入；sf 走 NCCL</td><td>engram.py:96-101（sf）、195-212（write）</td><td>表本体 GB 级一次性；sf 为 enp×本片段</td></tr>
      <tr><td>6</td><td><b>CP all-gather（注意力 KV / 压缩器输入聚合）</b></td><td>仅 prefill × 每注意力层多轮</td><td>cp</td><td><code>BucketBuffer.all_gather</code>（session 内聚合）</td><td><span class="badge deepep">DeepEP-V2</span></td><td>NVLink / RDMA（DeepEP 选路）</td><td>cp.py:42-51；attn.py:61, 411, 450, 706, 782-785, 943</td><td>max_tokens×cp_size×(投影宽×2B)/session</td></tr>
      <tr><td>7</td><td><b>EPLB 专家权重 P2P 迁移</b></td><td>每 REARRANGEMENT_STEP_INTERVAL 步（跨机）</td><td>ep</td><td><code>dist.batch_isend_irecv(P2POp(isend/irecv))</code></td><td><span class="badge nccl">NCCL / HCCL P2P</span></td><td>NVLink + RDMA</td><td>shuffle.py:94-148（:123 isend、:132 irecv、:137 batch）</td><td>每层整组专家权重，GB 级低频</td></tr>
      <tr><td>8</td><td><b>EPLB 单机 IPC 镜像 shuffle</b></td><td>同上（NVLink 域内 GPU）</td><td>ep</td><td><code>symm_mem.rendezvous</code> IPC 直读 + <code>ep.barrier()</code></td><td><span class="badge open">torch symm_mem</span></td><td>NVLink / IPC</td><td>eplb/__init__.py:195-220；shuffle.py:178-219</td><td>同上</td></tr>
      <tr><td>9</td><td><b>EPLB 专家 token 计数 all-reduce</b></td><td>rearrange 触发时</td><td>ep</td><td><code>dist.all_reduce(logical_expert_token_counts)</code></td><td><span class="badge nccl">NCCL/HCCL</span></td><td>NVLink/RDMA</td><td>eplb/__init__.py:249-254</td><td>[window,layers,logical] int，KB 级</td></tr>
      <tr><td>10</td><td><b>EPLB 负载统计 all-gather</b></td><td>每 MOE_LB_STAT_INTERVAL=128 步</td><td>ep</td><td><code>dist.all_gather_into_tensor(gathered_tokens, ...)</code></td><td><span class="badge nccl">NCCL/HCCL</span></td><td>NVLink/RDMA</td><td>eplb/__init__.py:181-188</td><td>[ep,interval,layers] int64，KB 级</td></tr>
      <tr><td>11</td><td><b>CP 元数据张量 broadcast</b></td><td>每 step（CP&gt;1）</td><td>cp</td><td><code>dist.broadcast</code>（cuda 张量逐个）</td><td><span class="badge nccl">NCCL/HCCL</span></td><td>NVLink/RDMA</td><td>communication_op.py:36-43；model_runner.py:212, 259</td><td>InputMetadata 展平张量，MB 级</td></tr>
      <tr><td>12</td><td><b>CP 对象广播（双通道另一半）</b></td><td>每 step / 每次方法调用</td><td>cp</td><td><code>MessageQueue.enqueue / dequeue</code>（pickle + shm 环形缓冲）</td><td><span class="badge deepep">shm + ZeroMQ</span></td><td>POSIX shm；跨机 reader 走 ZMQ TCP</td><td>parallel_state.py:17-23；shm_broadcast.py:389-422</td><td>≤1MB/chunk ×10 chunk</td></tr>
      <tr><td>13</td><td><b>slave worker RPC</b>（driver → follower 方法派发）</td><td>引擎每 step</td><td>cp</td><td><code>cp_broadcast_object((method, kwargs))</code></td><td><span class="badge deepep">shm + ZeroMQ</span></td><td>shm（CP 同机假设）</td><td>worker/base.py:129-133, 296-302</td><td>方法名+参数，B 级</td></tr>
      <tr><td>14</td><td><b>引擎步进同步</b>（是否有未完成请求）</td><td>每 generate step</td><td>dp</td><td><code>dist.all_reduce(unfinished, ReduceOp.MAX)</code></td><td><span class="badge nccl">NCCL 或 gloo</span>（zero-overhead 时 CPU/gloo）</td><td>NVLink 或 TCP</td><td>llm_engine.py:665-679</td><td>1×int64 = 8B</td></tr>
      <tr><td>15</td><td><b>C++ 调度器 DP 投票</b>（prefill ANY/ALL 决策 + 二次确认）</td><td>decode_step 到达决策点</td><td>dp</td><td><code>c10d allreduce（ReduceOp::MIN）</code></td><td><span class="badge nccl">gloo 或 NCCL</span></td><td>TCP 或 NVLink</td><td>csrc/engine/scheduler.hpp:170-182, 313-332</td><td>1×int32 = 4B</td></tr>
      <tr><td>16</td><td><b>KV 块数协商</b></td><td>启动 profiling 一次</td><td>world</td><td><code>dist.all_reduce(num_gpu_blocks, ReduceOp.SUM)</code></td><td><span class="badge nccl">NCCL/HCCL</span></td><td>NVLink/RDMA</td><td>worker/base.py:264-266</td><td>1×int64</td></tr>
      <tr><td>17</td><td><b>decode perf 曲线测量同步</b></td><td>warmup（CUDA graph 逐 bs 测量）</td><td>ep</td><td><code>dist.all_reduce(zeros)</code> ×2 + <code>ReduceOp.SUM</code>(耗时)</td><td><span class="badge nccl">NCCL/HCCL</span></td><td>NVLink/RDMA</td><td>model_runner.py:595-621</td><td>4B/次</td></tr>
      <tr><td>18</td><td><b>decode perf 缓存分发</b></td><td>warmup 读缓存</td><td>ep</td><td><code>dist.broadcast_object_list([results])</code></td><td><span class="badge nccl">NCCL/HCCL</span>（对象序列化）</td><td>NVLink/RDMA</td><td>decode_perf_cache.py:131-144</td><td>结果列表，KB 级</td></tr>
      <tr><td>19</td><td><b>NCCL/HCCL communicator 预热</b></td><td>进程组创建后一次</td><td>全部设备组</td><td><code>dist.all_reduce(torch.zeros(1).cuda())</code></td><td><span class="badge nccl">NCCL/HCCL</span></td><td>NVLink/RDMA</td><td>parallel_state.py:173-187</td><td>4B × 组数</td></tr>
      <tr><td>20</td><td><b>MessageQueue 句柄交换</b></td><td>MQ 创建一次</td><td>cpu_cp（gloo）</td><td><code>dist.broadcast_object_list([handle])</code></td><td><span class="badge">gloo</span></td><td>TCP</td><td>shm_broadcast.py:431-460（:454, :457）</td><td>shm 段名等，B 级</td></tr>
      <tr><td>21</td><td><b>生命周期 barrier</b></td><td>引擎 stop / 退出</td><td>默认 world 组</td><td><code>dist.barrier()</code> ×2（默认组为 gloo）</td><td><span class="badge">gloo</span></td><td>TCP</td><td>worker/base.py:135-148</td><td>0B</td></tr>
      <tr><td>22</td><td><b>采样 / 词表投影</b></td><td>每 step</td><td><b>无</b></td><td>本地 <code>bf16_gemm_nt</code> + 采样内核；head 为 ReplicatedLinear 全词表</td><td>—（无集合通信）</td><td>—</td><td>sampler.py:142；sampler_utils.py:20-28, 63；heads.py:22</td><td>—</td></tr>
    </table>

    <div class="note warn"><b>权重加载同样零通信</b>：每个 rank 独立用 <code>safetensors.safe_open</code> 从磁盘读自己需要的分片（hugging_face/loading.py:48-49；model_loader.py:136-153），既没有 NCCL broadcast 也没有 shm 分发——多副本部署的带宽成本换成了磁盘读放大。初始化期唯一的集合通信是 #5（Engram sf all-gather）与 #19（communicator 预热）。</div>
  </section>

  <!-- ================= 4. MoE dispatch/combine ================= -->
  <section id="sec4">
    <h2 class="sec"><span class="num">4</span>数据面 A：MoE dispatch / combine（DeepEP-V2 EPBuffer）</h2>
    <p class="lede">MoE 层是推理跨卡流量的绝对大头。DeepSeek 式训练里 all-reduce 串起 TP 组；DeepInfer 推理里权重复制（attention/共享专家/词表）+ EP 分片，token 流由 <code>EPBuffer.dispatch</code>/<code>combine</code> 完成——两者在通信流上以 <code>EventHandle</code>/<code>EventOverlap</code> 与计算流重叠。</p>

    <div class="figure">
      <svg viewBox="0 0 960 560" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="m2c" 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="m2o" 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>
          <marker id="m2g" 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>
        <!-- NVLink 域框 -->
        <rect x="30" y="60" width="430" height="330" rx="16" fill="rgba(34,211,238,.04)" stroke="#22d3ee" stroke-dasharray="6 5" stroke-opacity=".55"/>
        <text x="48" y="86" fill="#22d3ee" font-size="12.5" font-weight="700">NVLink 域（Node A）· is_within_nvl_domain == True</text>
        <rect x="500" y="60" width="430" height="330" rx="16" fill="rgba(251,191,36,.04)" stroke="#fbbf24" stroke-dasharray="6 5" stroke-opacity=".45"/>
        <text x="518" y="86" fill="#fbbf24" font-size="12.5" font-weight="700">远端 Node B · 跨域走 RDMA（RoCEv2 / IB QP）</text>

        <!-- GPU 0 (source) -->
        <g>
          <rect x="60" y="110" width="170" height="120" rx="10" class="node-gpu pulse"/>
          <text x="80" y="134" class="node-gpu-title">GPU 0（EP rank 0）</text>
          <g font-size="11" fill="#8ea0c2">
            <rect x="76" y="146" width="26" height="16" rx="4" fill="rgba(34,211,238,.25)"/><text x="82" y="158" fill="#22d3ee">t0</text>
            <rect x="108" y="146" width="26" height="16" rx="4" fill="rgba(34,211,238,.25)"/><text x="114" y="158" fill="#22d3ee">t1</text>
            <rect x="140" y="146" width="26" height="16" rx="4" fill="rgba(34,211,238,.25)"/><text x="146" y="158" fill="#22d3ee">t2</text>
            <rect x="76" y="170" width="26" height="16" rx="4" fill="rgba(34,211,238,.25)"/><text x="82" y="182" fill="#22d3ee">t3</text>
            <rect x="108" y="170" width="26" height="16" rx="4" fill="rgba(34,211,238,.25)"/><text x="114" y="182" fill="#22d3ee">t4</text>
            <rect x="140" y="170" width="26" height="16" rx="4" fill="rgba(34,211,238,.25)"/><text x="146" y="182" fill="#22d3ee">t5</text>
          </g>
          <text x="76" y="210" fill="#8ea0c2" font-size="10.5">gate → topk_idx / topk_weights</text>
          <text x="76" y="226" fill="#8ea0c2" font-size="10.5">fp8: (x, x_sf) 成对 dispatch</text>
        </g>

        <!-- GPU 1 (node A) -->
        <g>
          <rect x="270" y="110" width="170" height="120" rx="10" class="node-gpu"/>
          <text x="290" y="134" class="node-gpu-title">GPU 1（EP rank 1）</text>
          <g font-size="10" fill="#8ea0c2">
            <rect x="286" y="146" width="60" height="22" rx="5" fill="rgba(79,140,255,.18)" stroke="#4f8cff" stroke-opacity=".5"/><text x="294" y="161">E0 E1</text>
            <rect x="352" y="146" width="60" height="22" rx="5" fill="rgba(79,140,255,.18)" stroke="#4f8cff" stroke-opacity=".5"/><text x="360" y="161">E2</text>
            <rect x="286" y="176" width="126" height="22" rx="5" fill="rgba(79,140,255,.10)" stroke="#4f8cff" stroke-opacity=".3"/><text x="294" y="191">grouped GEMM (psum 布局)</text>
          </g>
          <text x="286" y="218" fill="#8ea0c2" font-size="10.5">recv counts → expert_count</text>
        </g>

        <!-- GPU 2/3 (node B) -->
        <g>
          <rect x="540" y="110" width="170" height="120" rx="10" class="node-gpu"/>
          <text x="560" y="134" class="node-gpu-title">GPU 2（EP rank 2）</text>
          <rect x="556" y="150" width="140" height="22" rx="5" fill="rgba(79,140,255,.10)" stroke="#4f8cff" stroke-opacity=".3"/><text x="564" y="165" fill="#8ea0c2">experts E3 E4 …</text>
          <rect x="760" y="110" width="150" height="120" rx="10" class="node-gpu"/>
          <text x="780" y="134" class="node-gpu-title">GPU 3（rank 3）</text>
          <rect x="776" y="150" width="120" height="22" rx="5" fill="rgba(79,140,255,.10)" stroke="#4f8cff" stroke-opacity=".3"/><text x="784" y="165" fill="#8ea0c2">experts …</text>
        </g>

        <!-- dispatch arrows -->
        <path id="dA1" d="M215,180 C245,180 250,180 268,180" fill="none" stroke="#22d3ee" stroke-width="2" class="flowline" marker-end="url(#m2c)"/>
        <path id="dA2" d="M205,230 C400,300 520,220 538,180" fill="none" stroke="#fbbf24" stroke-width="2" class="flowline" marker-end="url(#m2o)"/>
        <text x="360" y="258" fill="#fbbf24" font-size="11">跨域 dispatch：RDMA（IBGDA / QP，sl3）</text>
        <text x="196" y="172" fill="#22d3ee" font-size="11" text-anchor="end">域内 dispatch：NVLink 直写</text>

        <!-- moving tokens -->
        <circle r="5" fill="#22d3ee" class="barrow"><animateMotion dur="2s" repeatCount="indefinite" path="M215,180 L268,180"/></circle>
        <circle r="5" fill="#fbbf24" class="barrow"><animateMotion dur="3.4s" repeatCount="indefinite" path="M205,230 C400,300 520,220 538,180"/></circle>
        <circle r="4" fill="#22d3ee" class="barrow"><animateMotion dur="2.6s" begin="0.5s" repeatCount="indefinite" path="M145,200 L145,238 L390,238 L390,232"/></circle>

        <!-- combine arrows -->
        <path d="M268,290 C250,290 245,290 215,290" fill="none" stroke="#34d399" stroke-width="2" class="flowline" marker-end="url(#m2g)"/>
        <path d="M538,240 C520,290 300,330 215,300" fill="none" stroke="#34d399" stroke-width="2" stroke-dasharray="7 7" class="flowline" marker-end="url(#m2g)"/>
        <circle r="5" fill="#34d399" class="barrow"><animateMotion dur="2.2s" repeatCount="indefinite" path="M268,290 L215,290"/></circle>
        <circle r="5" fill="#34d399" class="barrow"><animateMotion dur="3.6s" repeatCount="indefinite" path="M538,240 C520,290 300,330 215,300"/></circle>
        <text x="286" y="292" fill="#34d399" font-size="11">combine：topk 加权归约回原卡，bias=shared expert 输出一次融合</text>

        <!-- bottom annotation -->
        <g font-size="11.5">
          <rect x="40" y="420" width="880" height="118" rx="10" fill="#0d1526" stroke="#263352"/>
          <text x="60" y="446" fill="#dbe4f5" font-weight="700">关键工程细节（均已在代码中验证）：</text>
          <text x="60" y="470" fill="#8ea0c2">· async_with_compute_stream=True + previous_event：dispatch/combine 与计算流事件重叠（mlp.py:478-479, 506-507）</text>
          <text x="60" y="492" fill="#8ea0c2">· DEEPINFER_USERBUFFER_COMM_SMS 限制通信 SM；compute 侧 min(32, SM/4) 保底；combine 前 limit_num_sms 再让渡（userbuffer.py:39-51, 86-90；mlp.py:602）</text>
          <text x="60" y="514" fill="#8ea0c2">· cumulative_local_expert_recv_stats 直写 EPLB expert_count（mlp.py:474）→ 通信内核顺带完成负载统计</text>
          <text x="60" y="534" fill="#8ea0c2">· allow_hybrid_mode=True：NVLink 域内自研内核、跨域 RDMA，同一 buffer 自动混用（userbuffer.py:78）</text>
        </g>
      </svg>
      <div class="cap">图 4-1 · MoE dispatch/combine：token 按 topk 路由流向各卡专家。青色 = NVLink 域内自研内核直写；橙色 = 跨机 RDMA；绿色 = combine 加权归回（融合 shared expert bias）。全程不经 NCCL。</div>
    </div>

    <div class="filepath">deepinfer/model_executor/models/v4_modules/mlp.py:461-511</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 <span class="k">=</span> self.ep_buffer.<span class="f">dispatch</span>(
        x<span class="k">=</span>hidden_states,
        num_sms<span class="k">=</span>envs.DEEPINFER_USERBUFFER_COMM_SMS,               <span class="c"># :471 通信 SM 配额</span>
        topk_idx<span class="k">=</span>topk_idx, topk_weights<span class="k">=</span>topk_weights,
        cumulative_local_expert_recv_stats<span class="k">=</span>self._eplb_layer().expert_count,  <span class="c"># :474 → EPLB</span>
        num_experts<span class="k">=</span>self.num_physical_experts,
        num_max_tokens_per_rank<span class="k">=</span>max_num_prefilling_tokens <span class="k">if</span> is_prompt <span class="k">else</span> max_num_decoding_tokens,  <span class="c"># :476</span>
        expert_alignment<span class="k">=</span>deep_gemm.<span class="f">get_mk_alignment_for_contiguous_layout</span>(),  <span class="c"># :477 与 grouped GEMM 布局对齐</span>
        previous_event<span class="k">=</span>dispatch_pre_evt, async_with_compute_stream<span class="k">=</span><span class="n">True</span>,     <span class="c"># :478-479</span>
        allocate_on_comm_stream<span class="k">=</span>dispatch_pre_evt <span class="k">is not</span> <span class="n">None</span>,              <span class="c"># :480 在通信流上分配</span>
        do_cpu_sync<span class="k">=</span>is_prompt <span class="k">and</span> YOCO_TRUNCATION_MODE <span class="k">!=</span> <span class="s">"compact"</span>,          <span class="c"># :485 CPU 需要知道 recv 形状</span>
        do_expand<span class="k">=</span><span class="n">True</span>, use_tma_aligned_col_major_sf<span class="k">=</span><span class="n">True</span>, defer_epilogue<span class="k">=</span><span class="n">True</span>)  <span class="c"># :486-488</span>
    <span class="k">return</span> event_overlap   <span class="c"># .current_stream_wait() → (moe_in_hidden, topk_idx, topk_weights, EPHandle)</span>

<span class="k">def</span> <span class="f">combine</span>(self, hidden_states, shared_hidden_states, handle, combine_pre_evt):
    <span class="c"># "Launch high-throughput chunked combine."（mlp.py:500）</span>
    event_overlap <span class="k">=</span> self.ep_buffer.<span class="f">combine</span>(x<span class="k">=</span>hidden_states, handle<span class="k">=</span>handle,
        num_sms<span class="k">=</span>envs.DEEPINFER_USERBUFFER_COMM_SMS, bias<span class="k">=</span>shared_hidden_states,   <span class="c"># :504-505 共享专家 bias 直接在通信内核中相加</span>
        previous_event<span class="k">=</span>combine_pre_evt, async_with_compute_stream<span class="k">=</span><span class="n">True</span>, defer_epilogue<span class="k">=</span><span class="n">True</span>)</pre>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📐</span>EPBuffer 分配参数</h3>
        <p><code>userbuffer.allocate_ep()</code>（userbuffer.py:63-95）传入 <code>num_max_tokens_per_rank</code>、<code>hidden</code>、<code>num_topk</code>、<code>use_fp8_dispatch=use_fp8_act</code>（fp8 激活时 token 以 fp8+sf 跨卡，带宽减半）；<code>allow_hybrid_mode=True</code>（:78）；<code>allow_multiple_reduction</code> 在批次不变性 + EPLB 开启时关闭以保证确定性（:79，environ.py 联动）。buffer 大小日志直接打印 <code>_gib(self.ep.num_bytes)</code>。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧮</span>SM 配额自动推导</h3>
        <p>若 <code>DEEPINFER_USERBUFFER_COMM_SMS==0</code>（未设置，environ.py:116）：理论值 <code>EPBuffer.get_theoretical_num_sms(num_experts, num_topk)</code> 与 <code>设备 SM − min(32, SM/4)</code> 取较小者（userbuffer.py:86-90）——通信内核与计算内核在同一颗 GPU 上抢 SM，配额显式化。combine 前共享专家计算包在 <code>limit_num_sms(...)</code> 里（mlp.py:602），为 combine 让出通信 SM。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🔀</span>NVLink 域内：mega-MoE 捷径</h3>
        <p><code>use_mega_moe = (is_gpu or fp8xfp4) and is_within_nvl_domain(EP 组)</code>（mlp.py:184-188）时<b>完全不走 dispatch/combine</b>：gate 输出直接写入 <code>SymmBuffer.topk_idx/topk_weights</code>，norm+fp8 cast 落入 <code>sym_buffer.x/x_sf</code>（mlp.py:540-546、274-301），随后 <code>deep_gemm.fp8_fp4_mega_moe / bf16_mega_moe</code> 在对称内存上直接 GEMM（mlp.py:549-559）。详见第 9 节 SymmBuffer。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">📊</span>数据量估算</h3>
        <p>prefill 单层 dispatch ≈ <code>max_num_prefilling_tokens × topk × hidden × 1B(fp8)/2B(bf16)</code>；decode 按 <code>max_num_decoding_tokens</code>（mlp.py:476）。以 hidden≈7k、topk≈8 计，万 token prefill 单层即数百 MB 跨卡流量——这正是必须用 DeepEP 而非 NCCL all-to-all 的原因。</p>
      </div>
    </div>
  </section>

  <!-- ================= 5. Engram ================= -->
  <section id="sec5">
    <h2 class="sec"><span class="num">5</span>数据面 B：Engram 稀疏交换（EngramBuffer，RDMA QP）</h2>
    <p class="lede">Engram（n-gram 稀疏注意力元数据）是 V4.1-Flash 的独有通信形态：每张卡持有 n-gram 嵌入表的 <b>hash 分片</b>，forward 时按 token 的 n-gram hash <b>one-sided RDMA 读</b>对端表项——不是集合通信，而是稀疏随机访问。</p>

    <div class="figure">
      <svg viewBox="0 0 960 470" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="m5p" 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>
        <!-- ranks -->
        <g>
          <rect x="40" y="70" width="230" height="150" rx="10" class="node-gpu pulse"/>
          <text x="60" y="94" class="node-gpu-title">Rank 0（enp rank 0）</text>
          <text x="60" y="116" fill="#8ea0c2" font-size="11">engram_hash(ngram_token_ids) → h0 h1 h2</text>
          <rect x="60" y="130" width="80" height="20" rx="4" fill="rgba(167,139,250,.25)"/><text x="68" y="144" fill="#a78bfa" font-size="10.5">hash h0</text>
          <rect x="150" y="130" width="80" height="20" rx="4" fill="rgba(167,139,250,.25)"/><text x="158" y="144" fill="#a78bfa" font-size="10.5">hash h1</text>
          <text x="60" y="180" fill="#8ea0c2" font-size="10.5">fetch → hooks（延迟等待）</text>
          <text x="60" y="198" fill="#8ea0c2" font-size="10.5">hook() 在 Engram.forward 内消费</text>
        </g>
        <g>
          <rect x="380" y="60" width="200" height="90" rx="10" class="node-gpu"/>
          <text x="400" y="84" class="node-gpu-title">Rank 1 · 表分片 #1</text>
          <g font-size="10" fill="#8ea0c2">
            <rect x="400" y="96" width="46" height="14" rx="3" fill="rgba(34,211,238,.18)"/><text x="408" y="107">k=v</text>
            <rect x="452" y="96" width="46" height="14" rx="3" fill="rgba(34,211,238,.18)"/><text x="460" y="107">k=v</text>
            <rect x="504" y="96" width="46" height="14" rx="3" fill="rgba(34,211,238,.18)"/><text x="512" y="107">…</text>
          </g>
          <text x="400" y="138" fill="#8ea0c2" font-size="10.5">EngramBuffer 存储（GPU 或 CPU RDMA）</text>
        </g>
        <g>
          <rect x="640" y="60" width="200" height="90" rx="10" class="node-gpu"/>
          <text x="660" y="84" class="node-gpu-title">Rank 2 · 表分片 #2</text>
          <g font-size="10" fill="#8ea0c2">
            <rect x="660" y="96" width="46" height="14" rx="3" fill="rgba(34,211,238,.18)"/><text x="668" y="107">k=v</text>
            <rect x="712" y="96" width="46" height="14" rx="3" fill="rgba(34,211,238,.18)"/><text x="720" y="107">k=v</text>
            <rect x="764" y="96" width="46" height="14" rx="3" fill="rgba(34,211,238,.18)"/><text x="772" y="107">…</text>
          </g>
        </g>

        <!-- RDMA read arrows -->
        <path d="M262,140 C310,130 330,120 378,115" fill="none" stroke="#a78bfa" stroke-width="2" class="flowline" marker-end="url(#m5p)"/>
        <path d="M262,155 C420,200 560,160 638,120" fill="none" stroke="#a78bfa" stroke-width="2" class="flowline" marker-end="url(#m5p)"/>
        <circle r="4.5" fill="#a78bfa" class="barrow"><animateMotion dur="2.2s" repeatCount="indefinite" path="M262,140 C310,130 330,120 378,115"/></circle>
        <circle r="4.5" fill="#a78bfa" class="barrow"><animateMotion dur="3.2s" repeatCount="indefinite" path="M262,155 C420,200 560,160 638,120"/></circle>
        <!-- return rows -->
        <path d="M378,150 C330,165 310,160 264,160" fill="none" stroke="#34d399" stroke-width="1.6" stroke-dasharray="5 5" class="flowline" marker-end="url(#m2g)"/>
        <text x="300" y="185" fill="#34d399" font-size="10.5" transform="rotate(8 300 185)">嵌入行(one-sided read 返回)</text>

        <!-- QP config box -->
        <g font-size="11.5">
          <rect x="40" y="270" width="880" height="170" rx="10" fill="#0d1526" stroke="#263352"/>
          <text x="60" y="296" fill="#dbe4f5" font-weight="700">EngramBuffer 通道配置（userbuffer.py:127-181）：</text>
          <text x="60" y="320" fill="#8ea0c2">· num_qps / qp_depth / restrict_rd_atomic = EngramBuffer.get_theoretical_config(组大小, 层数, tokens, entries)（:149-154）</text>
          <text x="60" y="342" fill="#8ea0c2">· use_cpu_rdma_storage = not DEEPINFER_ENGRAM_FORCE_GPU_STORAGE（:148）——大表可放 CPU 注册内存，节省显存；昇腾默认强制 GPU（environ.py:154）</text>
          <text x="60" y="364" fill="#8ea0c2">· 服务级别："EP 通信走 nvlink，此处 Engram sl 保持默认 sl3（sl2 留给 kv cache 流量隔离）"（:155 注释）→ RoCE QoS 双队列隔离 MoE 与 KV 流量</text>
          <text x="60" y="386" fill="#8ea0c2">· allow_hybrid_mode=True（:162）：NVLink 域内直读、跨域 RDMA QP</text>
          <text x="60" y="408" fill="#8ea0c2">· 初始化：本卡分片 weight 经 EngramBuffer.write() 灌入注册存储后立即释放（engram.py:208-212），此后表只活在通信 buffer 里</text>
          <text x="60" y="430" fill="#fbbf24">· 例外：scale factor 收集走 dist.all_gather_into_tensor（NCCL/HCCL，engram.py:96-101）——初始化期一次性混用两种库</text>
        </g>
      </svg>
      <div class="cap">图 5-1 · Engram 交换：hash 计算（本地）→ one-sided RDMA 读各 rank 表分片 → hook 在层内延迟消费。sl3/sl2 双服务级别隔离 EP 与 KV cache 流量。</div>
    </div>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">🧬</span>每步都发生什么</h3>
        <p>模型 forward 入口先 <code>tile_kernels.engram.engram_hash(ngram_token_ids, ...)</code> 算 hash（deepseek.py:180-186），随后 <code>self.engram_runtime.fetch(hashes)</code>（deepseek.py:188）触发跨卡稀疏读并返回每层一个延迟 hook；<code>Engram.forward</code> 里 <code>embed_hook()</code> 才真正等待数据（engram.py:149）。通信与投影计算天然重叠。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">💾</span>sf 收集为何走 NCCL</h3>
        <p><code>NgramEmbedding.gather_sf()</code>（engram.py:96-101）把本卡 FP8 表的 ue8m0 scale factor 打包后 <code>dist.all_gather_into_tensor(sf, local_sf, group=self.engram_group)</code>——这是一次<b>稠密、全量、一次性</b>的小张量收集，正是 NCCL 擅长的形态；而 write 大表本体走 DeepEP 注册内存直写（engram.py:210）。两种库各取所长。</p>
      </div>
    </div>
  </section>

  <!-- ================= 6. CP ================= -->
  <section id="sec6">
    <h2 class="sec"><span class="num">6</span>数据面 C：CP all-gather（DeepEP BucketBuffer 会话式聚合）</h2>
    <p class="lede">上下文并行（CP）把同一请求的 token 分片到多卡，prefill 时注意力需要看到全序列 KV——这就需要 all-gather。DeepInfer 没有用 <code>dist.all_gather_into_tensor</code>（NCCL），而是用 DeepEP 的 <code>BucketBuffer</code>：<b>一次 session 内聚合多次 all-gather</b>，等待时沿 token 维零拷贝拼接。</p>

    <div class="figure">
      <svg viewBox="0 0 960 500" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="m6" 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>
        <!-- CP ranks -->
        <g>
          <rect x="40" y="50" width="180" height="70" rx="10" class="node-gpu"/>
          <text x="60" y="74" class="node-gpu-title">CP rank 0</text>
          <g font-size="10">
            <rect x="60" y="86" width="30" height="14" rx="3" fill="#4f8cff"/><rect x="94" y="86" width="30" height="14" rx="3" fill="#4f8cff"/><rect x="128" y="86" width="30" height="14" rx="3" fill="#4f8cff"/>
          </g>
          <text x="60" y="112" fill="#8ea0c2" font-size="10.5">token 分片 / KV shard</text>
        </g>
        <g>
          <rect x="40" y="150" width="180" height="70" rx="10" class="node-gpu"/>
          <text x="60" y="174" class="node-gpu-title">CP rank 1</text>
          <g font-size="10">
            <rect x="60" y="186" width="30" height="14" rx="3" fill="#34d399"/><rect x="94" y="186" width="30" height="14" rx="3" fill="#34d399"/><rect x="128" y="186" width="30" height="14" rx="3" fill="#34d399"/>
          </g>
        </g>
        <g>
          <rect x="40" y="250" width="180" height="70" rx="10" class="node-gpu"/>
          <text x="60" y="274" class="node-gpu-title">CP rank 2</text>
          <g font-size="10">
            <rect x="60" y="286" width="30" height="14" rx="3" fill="#a78bfa"/><rect x="94" y="286" width="30" height="14" rx="3" fill="#a78bfa"/><rect x="128" y="286" width="30" height="14" rx="3" fill="#a78bfa"/>
          </g>
        </g>
        <g>
          <rect x="40" y="350" width="180" height="70" rx="10" class="node-gpu"/>
          <text x="60" y="374" class="node-gpu-title">CP rank 3</text>
          <g font-size="10">
            <rect x="60" y="386" width="30" height="14" rx="3" fill="#fbbf24"/><rect x="94" y="386" width="30" height="14" rx="3" fill="#fbbf24"/><rect x="128" y="386" width="30" height="14" rx="3" fill="#fbbf24"/>
          </g>
        </g>

        <!-- session buffer -->
        <rect x="330" y="60" width="590" height="360" rx="14" fill="#101b33" stroke="#a78bfa" stroke-opacity=".55"/>
        <text x="352" y="90" fill="#fff" font-size="14" font-weight="700">CPManager 会话（userbuffer.cp_session()，attn.py:782）</text>
        <text x="352" y="112" fill="#8ea0c2" font-size="11">BucketBuffer：num_bytes = max_tokens × max_ag_bytes_per_token × cp_size + RDMA 对齐（userbuffer.py:107-110）</text>
        <!-- gathered region -->
        <g font-size="10">
          <rect x="380" y="130" width="330" height="26" rx="4" fill="#4f8cff" fill-opacity=".7"/><text x="388" y="147" fill="#0b1020" font-weight="700">rank0 shard</text>
          <rect x="380" y="162" width="330" height="26" rx="4" fill="#34d399" fill-opacity=".7"/><text x="388" y="179" fill="#0b1020" font-weight="700">rank1 shard</text>
          <rect x="380" y="194" width="330" height="26" rx="4" fill="#a78bfa" fill-opacity=".7"/><text x="388" y="211" fill="#0b1020" font-weight="700">rank2 shard</text>
          <rect x="380" y="226" width="330" height="26" rx="4" fill="#fbbf24" fill-opacity=".7"/><text x="388" y="243" fill="#0b1020" font-weight="700">rank3 shard</text>
        </g>
        <text x="380" y="280" fill="#22d3ee" font-size="12">wait() → view(cp_size, *shape).flatten(0,1) 沿 token 维拼接（cp.py:51）</text>
        <text x="380" y="304" fill="#8ea0c2" font-size="11">get_inplace_tensor()：先把本 rank 分片写进聚合区，投影内核直接输出到通信 buffer（cp.py:36-41）</text>
        <text x="380" y="326" fill="#8ea0c2" font-size="11">同一 session 内多次 all_gather 复用存储；session 结束整块回收（cp.py:26-34）</text>
        <text x="380" y="352" fill="#fbbf24" font-size="11">触发点（均 prefill）：projected_kv / kv_swa / main_k / yoco full KV（attn.py:61, 411, 450, 785, 943）</text>
        <text x="380" y="376" fill="#fbbf24" font-size="11">decode 不走 CP：use_cp = is_prompt and cp_size&gt;1（attn.py:766）</text>
        <text x="380" y="400" fill="#8ea0c2" font-size="11">数据量上限：每层 get_max_ag_bytes_per_token()（attn.py:375-385，hidden×2 或投影宽）</text>

        <!-- arrows -->
        <path d="M220,85 C280,85 300,120 376,143" fill="none" stroke="#4f8cff" stroke-width="2" class="flowline" marker-end="url(#m6)"/>
        <path d="M220,185 C280,185 300,180 376,175" fill="none" stroke="#34d399" stroke-width="2" class="flowline" marker-end="url(#m6)"/>
        <path d="M220,285 C280,285 300,250 376,207" fill="none" stroke="#a78bfa" stroke-width="2" class="flowline" marker-end="url(#m6)"/>
        <path d="M220,385 C290,385 300,300 376,239" fill="none" stroke="#fbbf24" stroke-width="2" class="flowline" marker-end="url(#m6)"/>
        <circle r="4" fill="#4f8cff" class="barrow"><animateMotion dur="2.4s" repeatCount="indefinite" path="M220,85 C280,85 300,120 376,143"/></circle>
        <circle r="4" fill="#fbbf24" class="barrow"><animateMotion dur="3s" repeatCount="indefinite" path="M220,385 C290,385 300,300 376,239"/></circle>
      </svg>
      <div class="cap">图 6-1 · CP all-gather 会话式聚合：各 rank 分片进入 BucketBuffer 会话区，wait 后沿 token 维零拷贝拼接。一个 prefill step 内多层多次 gather 共享同一 session。</div>
    </div>

    <div class="filepath">deepinfer/model_executor/parallel_utils/cp.py:42-51 + communication_op.py</div>
    <pre class="code"><span class="k">def</span> <span class="f">all_gather</span>(self, x):                              <span class="c"># DeepEP 路径</span>
    handle <span class="k">=</span> self._buffer.<span class="f">all_gather</span>(x)                <span class="c"># BucketBuffer（deep_ep），NVLink/RDMA</span>
    <span class="k">return</span> <span class="k">lambda</span>: handle.<span class="f">wait</span>().<span class="f">view</span>((self._size, *x.shape)).<span class="f">flatten</span>(<span class="n">0</span>, <span class="n">1</span>)

<span class="k">def</span> <span class="f">cp_broadcast</span>(input_, src<span class="k">=</span><span class="n">0</span>):                      <span class="c"># NCCL 路径（communication_op.py:28-33）</span>
    dist.<span class="f">broadcast</span>(input_, src<span class="k">=</span>dist.<span class="f">get_global_rank</span>(cp_group, src), group<span class="k">=</span>cp_group)

<span class="k">def</span> <span class="f">broadcast_tensor_dict</span>(tensor_dict, src<span class="k">=</span><span class="n">0</span>):            <span class="c"># 双通道（communication_op.py:51-82）</span>
    <span class="c"># cuda 张量：metadata（dtype/size）经 shm MQ 广播，本体经 cp_broadcast_multi_tensor → dist.broadcast（NCCL）</span>
    <span class="c"># 其余 python 对象：直接随 metadata 走 cp_broadcast_object → MessageQueue（shm，parallel_state.py:17-23）</span></pre>

    <div class="note"><b>谁走 DeepEP、谁走 NCCL？</b>规则非常清晰：<b>大张量聚合</b>（KV/投影输出，MB~GB）走 DeepEP <code>BucketBuffer</code>——可控 SM、会话复用、零拷贝拼接；<b>小张量广播</b>（InputMetadata 展平的 cu_seqlens / slot_mapping 等，KB~MB）走 NCCL <code>dist.broadcast</code>；<b>python 对象</b>（方法调用、采样参数元信息）走 shm <code>MessageQueue</code>。同一个 <code>broadcast_tensor_dict</code> 一次调用就把三套库全部用上（communication_op.py:51-82）。</div>
  </section>

  <!-- ================= 7. EPLB ================= -->
  <section id="sec7">
    <h2 class="sec"><span class="num">7</span>数据面 D：EPLB 专家重排（NCCL P2P + symm_mem IPC 双路径）</h2>
    <p class="lede">EPLB 周期性把"热"专家搬到负载低的卡上。一次重排 = 一次 <b>NCCL all-reduce</b>（全局专家计数）+ 纯本地重排决策（rebalance_experts_global）+ <b>权重迁移</b>（跨机走 NCCL batched P2P；NVLink 域内走 symm_mem IPC 镜像直读）。</p>

    <div class="figure">
      <svg viewBox="0 0 960 560" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="m7g" 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="m7v" 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>
        <!-- phase 1 -->
        <rect x="20" y="14" width="920" height="130" rx="12" fill="#0d1526" stroke="#263352"/>
        <text x="40" y="40" fill="#fff" font-size="13.5" font-weight="700">Phase 1 · 计数聚合（NCCL，eplb/__init__.py:249-254）</text>
        <g font-size="10.5">
          <rect x="60" y="56" width="150" height="40" rx="8" class="node-gpu"/><text x="72" y="80" fill="#dbe4f5">rank0 计数窗口</text>
          <rect x="260" y="56" width="150" height="40" rx="8" class="node-gpu"/><text x="272" y="80" fill="#dbe4f5">rank1 计数窗口</text>
          <rect x="460" y="56" width="150" height="40" rx="8" class="node-gpu"/><text x="272" y="80" fill="#dbe4f5" opacity="0">.</text><text x="472" y="80" fill="#dbe4f5">rank2 计数窗口</text>
          <rect x="660" y="56" width="150" height="40" rx="8" class="node-gpu"/><text x="672" y="80" fill="#dbe4f5">rank3 计数窗口</text>
        </g>
        <path d="M130,100 L130,124" stroke="#fbbf24" stroke-width="2" class="flowline" marker-end="url(#m2o)"/>
        <path d="M335,100 L335,124" stroke="#fbbf24" stroke-width="2" class="flowline" marker-end="url(#m2o)"/>
        <path d="M535,100 L535,124" stroke="#fbbf24" stroke-width="2" class="flowline" marker-end="url(#m2o)"/>
        <path d="M735,100 L735,124" stroke="#fbbf24" stroke-width="2" class="flowline" marker-end="url(#m2o)"/>
        <text x="400" y="122" fill="#fbbf24" font-size="11.5" text-anchor="middle">dist.all_reduce(scatter_add 后的 logical 计数) → 全员一致的全局负载视图</text>

        <!-- phase 2 -->
        <rect x="20" y="158" width="920" height="120" rx="12" fill="#0d1526" stroke="#263352"/>
        <text x="40" y="184" fill="#fff" font-size="13.5" font-weight="700">Phase 2 · 新布局计算（本地，无通信，policy.py:rebalance_experts_global）</text>
        <g font-size="10.5">
          <rect x="60" y="200" width="840" height="56" rx="8" fill="rgba(79,140,255,.08)" stroke="#4f8cff" stroke-opacity=".3"/>
          <text x="80" y="222" fill="#8ea0c2">old physical→logical 映射与 rebalance_experts_global(logical 计数, num_physical, num_local) →</text>
          <text x="80" y="242" fill="#8ea0c2">next_physical_to_logical / next_logical_to_physical / next_logical_count，各 rank 计算结果完全一致</text>
        </g>

        <!-- phase 3: weight migration -->
        <rect x="20" y="292" width="920" height="258" rx="12" fill="#0d1526" stroke="#263352"/>
        <text x="40" y="318" fill="#fff" font-size="13.5" font-weight="700">Phase 3 · 专家权重迁移（两种库二选一，eplb/__init__.py:261-275）</text>
        <g>
          <rect x="40" y="332" width="440" height="130" rx="10" fill="rgba(52,211,153,.05)" stroke="#34d399" stroke-opacity=".5"/>
          <text x="56" y="354" fill="#34d399" font-size="12" font-weight="700">跨机：expert_model_parallel_shuffle_inplace（NCCL P2P）</text>
          <g font-size="10">
            <rect x="60" y="366" width="70" height="30" rx="6" class="node-gpu"/><text x="70" y="384">rank0</text>
            <rect x="160" y="366" width="70" height="30" rx="6" class="node-gpu"/><text x="170" y="384">rank1</text>
            <rect x="260" y="366" width="70" height="30" rx="6" class="node-gpu"/><text x="270" y="384">rank2</text>
            <rect x="360" y="366" width="70" height="30" rx="6" class="node-gpu"/><text x="370" y="384">rank3</text>
          </g>
          <path d="M95,398 C120,430 140,430 162,398" fill="none" stroke="#34d399" stroke-width="2" class="flowline" marker-end="url(#m7g)"/>
          <path d="M330,364 C310,350 290,350 270,364" fill="none" stroke="#34d399" stroke-width="2" class="flowline" marker-end="url(#m7g)"/>
          <circle r="4.5" fill="#34d399" class="barrow"><animateMotion dur="2.2s" repeatCount="indefinite" path="M95,398 C120,430 140,430 162,398"/></circle>
          <circle r="4.5" fill="#34d399" class="barrow"><animateMotion dur="2.8s" repeatCount="indefinite" path="M330,364 C310,350 290,350 270,364"/></circle>
          <text x="56" y="448" fill="#8ea0c2" font-size="10.5">dist.batch_isend_irecv(P2POp(isend/irecv))（shuffle.py:123,132,137）</text>
          <text x="56" y="462" fill="#8ea0c2" font-size="10.5">按对端 rank 差 mod REARRANGE_P2P_GROUPS 分桶批量收发</text>
        </g>
        <g>
          <rect x="500" y="332" width="440" height="130" rx="10" fill="rgba(167,139,250,.05)" stroke="#a78bfa" stroke-opacity=".5"/>
          <text x="516" y="354" fill="#a78bfa" font-size="12" font-weight="700">单机：intranode（torch symm_mem IPC 镜像直读）</text>
          <g font-size="10">
            <rect x="530" y="366" width="60" height="30" rx="6" class="node-gpu"/><text x="542" y="384">r0</text>
            <rect x="630" y="366" width="60" height="30" rx="6" class="node-gpu"/><text x="642" y="384">r1</text>
            <rect x="730" y="366" width="60" height="30" rx="6" class="node-gpu"/><text x="742" y="384">r2</text>
          </g>
          <path d="M560,364 C600,340 660,340 692,364" fill="none" stroke="#a78bfa" stroke-width="2" stroke-dasharray="5 4" class="flowline" marker-end="url(#m7v)"/>
          <circle r="4.5" fill="#a78bfa" class="barrow"><animateMotion dur="2s" repeatCount="indefinite" path="M560,364 C600,340 660,340 692,364"/></circle>
          <text x="516" y="424" fill="#8ea0c2" font-size="10.5">权重镜像进 symm_mem buffer（ rendezvous + get_buffer，</text>
          <text x="516" y="440" fill="#8ea0c2" font-size="10.5">eplb/__init__.py:206-220），对端 weight[dst].copy_(peer[src_slot])</text>
          <text x="516" y="456" fill="#8ea0c2" font-size="10.5">直接读对端显存（shuffle.py:209-210）；ep.barrier()×2 保护层间复用</text>
        </g>
        <text x="40" y="486" fill="#fbbf24" font-size="11">条件：_intranode_shuffle = is_within_nvl_domain(ep) and PLATFORM.is_gpu（eplb/__init__.py:200）——NPU 暂不支持 symm_mem（:199 TODO）</text>
        <text x="40" y="506" fill="#8ea0c2" font-size="11">LB 统计另有 all_gather_into_tensor 每 128 步收集每 rank token 数（eplb/__init__.py:181-188）→ moe_load_balance_ratio(avg,max) 上报</text>
        <text x="40" y="526" fill="#8ea0c2" font-size="11">首个重排提前到 1/4 周期纠正冷启动失衡（eplb/__init__.py:121-123）；expert_count 每步清零、由 dispatch 内核累计（eplb/__init__.py:138）</text>
      </svg>
      <div class="cap">图 7-1 · EPLB 重排三阶段：NCCL all-reduce 聚合计数（上）→ 本地一致决策（中）→ 权重迁移（下：绿色 NCCL P2P / 紫色 symm_mem IPC 直读）。</div>
    </div>

    <div class="filepath">deepinfer/model_executor/eplb/shuffle.py:94-148（跨机 P2P）</div>
    <pre class="code"><span class="c"># 按 (ep_rank - dst) % REARRANGE_P2P_GROUPS 分桶（shuffle.py:114），逐桶批量收发避免 deadlock</span>
p2p_buckets[(ep_rank <span class="k">-</span> dst) <span class="k">%</span> 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>
p2p_buckets[(src_rank <span class="k">-</span> ep_rank) <span class="k">%</span> 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">for</span> req <span class="k">in</span> dist.<span class="f">batch_isend_irecv</span>(ops):   <span class="c"># :137 torch.distributed 的 NCCL 后端原生支持 batch P2P</span>
        req.<span class="f">wait</span>()</pre>
  </section>

  <!-- ================= 8. 控制面 ================= -->
  <section id="sec8">
    <h2 class="sec"><span class="num">8</span>控制面与元数据通信：把 NCCL 留给"小事"</h2>
    <p class="lede">每 step 的固定开销通信全部是字节级/KB 级：引擎步进同步、C++ 调度器投票、CP 元数据广播、slave RPC。DeepInfer 的做法是能用 gloo/shm 就不占 GPU 通信资源。</p>

    <table class="tbl">
      <tr><th>行为</th><th>操作与后端</th><th>细节</th><th>代码位置</th></tr>
      <tr>
        <td><b>引擎步进同步</b></td>
        <td><code>dist.all_reduce(unfinished, ReduceOp.MAX)</code>；zero-overhead 时走 <code>cpu_dp_group</code>（gloo, CPU tensor），否则 dp 组（NCCL, CUDA tensor）</td>
        <td>每步询问"所有 DP 副本是否还有活干"——DP 副本必须同步停止；1 个 int64。</td>
        <td>llm_engine.py:665-679</td>
      </tr>
      <tr>
        <td><b>C++ 调度器投票</b></td>
        <td><code>c10d::ProcessGroup::allreduce</code>（<code>ReduceOp::MIN</code>），int32/float32</td>
        <td>prefill ANY/ALL 决策 + 二次确认 any_scheduled，防"全员空 prompt step 死循环"；<code>use_cpu_dp_group = backend=="gloo"</code> 决定 CPU/CUDA 张量。Python 侧调度器构造时按 ZERO_OVERHEAD 传 gloo 或 NCCL 组。</td>
        <td>csrc/engine/scheduler.hpp:170-182, 313-332, 109；llm_engine.py:313</td>
      </tr>
      <tr>
        <td><b>CP InputMetadata 广播</b></td>
        <td><code>broadcast_tensor_dict</code>：cuda 张量 → <code>dist.broadcast</code>（NCCL）；非张量 → <code>cp_broadcast_object</code> → shm MQ</td>
        <td>driver 组包 <code>to_flatten_dict()</code>，follower <code>from_flatten_dict</code> 还原；CUDA graph 路径只传少量标量。</td>
        <td>communication_op.py:51-82；model_runner.py:200-230</td>
      </tr>
      <tr>
        <td><b>采样参数元信息广播</b></td>
        <td>同上（selected_token_indices 等 cuda 张量走 NCCL）</td>
        <td>driver 在 prepare_sampler_inputs 后广播，follower 校验 is_prompt 一致。</td>
        <td>model_runner.py:250-262</td>
      </tr>
      <tr>
        <td><b>slave worker RPC</b></td>
        <td><code>cp_broadcast_object((method, kwargs))</code> → MessageQueue（shm）</td>
        <td>非 driver 的 CP follower 进程死循环 dequeue 并反射调用（start_slave_worker_loop）。</td>
        <td>worker/base.py:129-133, 296-302</td>
      </tr>
      <tr>
        <td><b>KV 块数协商</b></td>
        <td><code>dist.all_reduce(num_gpu_blocks, ReduceOp.SUM, PG.world_group())</code></td>
        <td>各 rank profiling 后求和再除以 world size（//2*2 保证偶数），全员统一 KV 容量。</td>
        <td>worker/base.py:264-266</td>
      </tr>
      <tr>
        <td><b>decode perf 测量</b></td>
        <td>EP 组上 <code>all_reduce(zeros)</code> 作跨 rank 同步点 + <code>ReduceOp.SUM</code> 平均耗时；结果 <code>broadcast_object_list</code> 分发（rank0 读缓存后广播）</td>
        <td>选 EP 组是刻意的：decode 时长由最慢的 EP 通信决定。</td>
        <td>model_runner.py:595-631；decode_perf_cache.py:131-144</td>
      </tr>
      <tr>
        <td><b>生命周期 barrier</b></td>
        <td><code>dist.barrier()</code> ×2（默认 world 组 = gloo）</td>
        <td>stop 顺序：barrier → userbuffer.close()（销毁 DeepEP/symm buffer）→ barrier → destroy_cuda_graphs → 清理 shm → destroy_process_group。注释明确说明 NCCL-in-CUDA-graph 销毁挂起问题（pytorch#115388），故 barrier 用 gloo。</td>
        <td>worker/base.py:135-148</td>
      </tr>
    </table>

    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📬</span>MessageQueue：不占网络的广播</h3>
        <p><code>ShmRingBuffer</code>（shm_broadcast.py:33-150）是单写多读的 POSIX 共享内存环形缓冲：每 chunk 1MB（<code>1&lt;&lt;20</code>）、10 个 chunk（parallel_state.py:124），元数据区用 written/reader 标志位无锁同步。超大对象溢出到 <b>ZeroMQ</b>（XPUB/SUB，enqueue :389-404）；跨节点 reader 也走 ZMQ TCP（create_from_handle :250-284）。CP 组按"不跨节点"假设创建（:442 注释）。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧾</span>NCCL 显存观测</h3>
        <p><code>NCCLMemoryStatsLogger</code>（nccl_memory.py:13-100）每 1000 步（<code>DEEPINFER_NCCL_MEMORY_SAMPLE_INTERVAL_STEPS</code>）枚举 <code>c10d._world.pg_map</code> 中所有已初始化 NCCL communicator，经 <code>backend._comm_ptr()</code> 过滤空 comm，读 <code>memory_stats()["total"]</code> 打印每个组（dp/cp/ep/…别名标注）的 NCCL 内部缓冲占用——推理框架里少见的 NCCL 显存可观测性设施（llm_engine.py:955 挂钩）。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🎲</span>采样确实无通信</h3>
        <p>grep 到的 sampler "nccl" 只是一句注释（sampler.py:378）："CP rank 0 采样主路径 raise 会连坐所有请求 + <b>NCCL barrier 超时</b>"。词表不切分：<code>GPTHead</code> 是全词表 <code>ReplicatedLinear</code>（heads.py:22），logits 由本地 <code>bf16_gemm_nt</code> 算出（sampler_utils.py:20-28）；<code>VocabParallelEmbedding.forward</code> 的 <code>gather</code> 是 tilelang 本地行 gather（tilelang_ops/gather.py，越界补零），prompt logprobs 仅 CP rank 0 物化结果（sampler_utils.py:63, 95）；SO 结构化输出 mask 也只在 CP rank 0 计算（sampler.py:314）。</p>
      </div>
      <div class="card reveal d3">
        <h3><span class="ico">📚</span>权重加载零通信</h3>
        <p>各 rank 独立 <code>safe_open</code> 读盘（loading.py:48-49）、独立校验覆盖与形状（loading.py:86-121），加载后 <code>get_model</code> 断言参数在 cuda（model_loader.py:76-80）。对比 vLLM 早期的 broadcast 权重分发，DeepInfer 选择了"磁盘读放大换零通信"——对多副本 EP/DP 部署尤其划算。</p>
      </div>
    </div>
  </section>

  <!-- ================= 9. 通信库横评 ================= -->
  <section id="sec9">
    <h2 class="sec"><span class="num">9</span>底层通信库横评</h2>
    <p class="lede">六个通信库在 DeepInfer 中各司其职，选择逻辑可以一句话总结：<b>大张量走 DeepEP/SymmBuffer，小张量走 NCCL/HCCL，CPU 控制流走 gloo，python 对象走 shm。</b></p>

    <table class="tbl">
      <tr><th style="width:13%">通信库</th><th style="width:17%">载体 API</th><th style="width:17%">通信模式</th><th style="width:12%">链路</th><th style="width:23%">在 DeepInfer 中的角色</th><th style="width:18%">选择逻辑 / 谁决定</th></tr>
      <tr>
        <td><b>DeepEP-V2</b><br><span class="badge deepep">数据面主力</span></td>
        <td><code>EPBuffer.dispatch/combine</code>、<code>EngramBuffer.fetch/write</code>、<code>BucketBuffer.all_gather</code></td>
        <td>MoE token 路由（all-to-all 变体）、稀疏 one-sided 读、会话式 all-gather</td>
        <td>NVLink 域内自研内核；跨域 RoCE/IB RDMA（QP，sl3）</td>
        <td>MoE dispatch/combine、Engram 表项 fetch、CP KV 聚合——三大重数据面</td>
        <td>userbuffer 显式分配；<code>allow_hybrid_mode=True</code> 让 DeepEP 自动混选域内/跨域路径（userbuffer.py:78, 162）</td>
      </tr>
      <tr>
        <td><b>DeepGEMM SymmBuffer</b><br><span class="badge merged">对称内存</span></td>
        <td><code>deep_gemm.SymmBuffer</code> + <code>fp8_fp4_mega_moe / bf16_mega_moe</code></td>
        <td>无报文：GEMM 经 NVLink 对称内存直读对端 token/写对端输出</td>
        <td>NVLink（IPC/多播），限单通信域</td>
        <td>NVLink 域内 MoE 的"零通信"路径；norm/fp8-cast 直接输出到通信 buffer（fused_norm_cast_kwargs, mlp.py:274-301）</td>
        <td><code>use_mega_moe = (is_gpu or fp8xfp4) and is_within_nvl_domain(ep)</code>（mlp.py:184-188）；首个 spec 拥有底层存储，后续为缓存视图（userbuffer.py:195-197）</td>
      </tr>
      <tr>
        <td><b>NCCL / HCCL</b><br><span class="badge nccl">torch.distributed</span></td>
        <td><code>dist.broadcast / all_reduce / all_gather_into_tensor / batch_isend_irecv(P2POp)</code></td>
        <td>经典集合通信 + 点对点</td>
        <td>NVLink + RDMA（拓扑感知）</td>
        <td>CP 元数据张量广播、EPLB 计数/统计/权重迁移、引擎步进同步、KV 块数、communicator 预热</td>
        <td>一切 <code>dist.*</code> 的默认后端；SM 上限 <code>DEEPINFER_NCCL_NUM_SMS=32</code>（platform.py:81-82）；NPU 自动换 HCCL</td>
      </tr>
      <tr>
        <td><b>gloo</b><br><span class="badge">CPU 组</span></td>
        <td><code>dist.init_process_group("gloo")</code>、gloo 子组、<code>dist.barrier</code>、<code>broadcast_object_list</code></td>
        <td>CPU 集合通信</td>
        <td>TCP（+共享内存优化）</td>
        <td>默认 world 组、cpu_dp（调度投票/引擎同步）、cpu_cp（MQ 句柄交换）、stop barrier</td>
        <td>控制面通信零占 GPU；生命周期操作避开 NCCL 死锁（worker/base.py:135-148 注释）</td>
      </tr>
      <tr>
        <td><b>torch symm_mem</b><br><span class="badge open">IPC 镜像</span></td>
        <td><code>symm_mem.empty → rendezvous → handle.get_buffer</code></td>
        <td>本机各 rank 显存互读（cudaIpc）</td>
        <td>NVLink / IPC</td>
        <td>EPLB 单机专家权重 shuffle：每层镜像刷新 + 直读对端（eplb/__init__.py:206-220）</td>
        <td><code>is_within_nvl_domain(ep) and is_gpu</code>（eplb/__init__.py:200）；NPU 不支持（:199 TODO）</td>
      </tr>
      <tr>
        <td><b>shm + ZeroMQ</b><br><span class="badge deepep">对象广播</span></td>
        <td><code>ShmRingBuffer</code> + ZMQ XPUB/SUB（<code>MessageQueue</code>）</td>
        <td>单写多读环形缓冲；pickle 序列化</td>
        <td>POSIX shm；跨机回退 ZMQ TCP</td>
        <td>CP 组 python 对象广播：slave RPC、InputMetadata 非 tensor 字段、采样元信息</td>
        <td>CP 组创建时自动建（parallel_state.py:123-124）；对象级广播比 gloo broadcast 延迟更低且不占网络</td>
      </tr>
    </table>

    <div class="note good"><b>典型分工示例（一次 prefill step）</b>：driver 经 <b>shm MQ</b> 派发 execute_model → InputMetadata 张量经 <b>NCCL broadcast</b> 补齐 → 注意力 KV 经 <b>DeepEP BucketBuffer</b> 聚合 → MoE token 经 <b>DeepEP dispatch/combine</b>（或 <b>SymmBuffer mega-MoE</b>）路由 → EPLB 计数在下一次 rearrange 时经 <b>NCCL all-reduce</b> 聚合 → 步末"还有活吗"经 <b>gloo/NCCL all-reduce(MAX)</b> 同步。一条推理路径，五种库无缝接力。</div>
  </section>

  <!-- ================= 10. NVLink 域判定 ================= -->
  <section id="sec10">
    <h2 class="sec"><span class="num">10</span>NVLink 域与 RDMA 域判定机制</h2>
    <p class="lede">"这组卡之间能不能走 NVLink 直写"是多个路径选择的分叉点。判定函数只有三行，但它决定了 MoE 用 mega-MoE 还是 dispatch/combine、EPLB 用 IPC 还是 P2P、DeepEP 内核选域内还是跨域。</p>

    <div class="figure">
      <svg viewBox="0 0 960 420" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <marker id="m10" 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>
        <g>
          <rect x="40" y="30" width="380" height="86" rx="12" class="node-gpu pulse"/>
          <text x="60" y="58" fill="#fff" font-size="13.5" font-weight="700">PG.is_within_nvl_domain(group)</text>
          <text x="60" y="80" fill="#8ea0c2" font-size="11">NPU → 恒 True（parallel_state.py:132-133）</text>
          <text x="60" y="98" fill="#8ea0c2" font-size="11">GPU → group.size() ≤ deep_ep.get_physical_domain_size(group)[1]</text>
        </g>
        <path d="M420,73 L480,73" stroke="#4f8cff" stroke-width="2" class="flowline" marker-end="url(#m10)"/>
        <g>
          <rect x="484" y="20" width="220" height="110" rx="12" fill="rgba(34,211,238,.06)" stroke="#22d3ee" stroke-opacity=".6"/>
          <text x="504" y="46" fill="#22d3ee" font-size="12.5" font-weight="700">域内（NVLink）</text>
          <text x="504" y="70" fill="#8ea0c2" font-size="10.5">· mega-MoE + SymmBuffer</text>
          <text x="504" y="88" fill="#8ea0c2" font-size="10.5">· EPLB symm_mem IPC shuffle</text>
          <text x="504" y="106" fill="#8ea0c2" font-size="10.5">· DeepEP 域内内核（低延迟直写）</text>
        </g>
        <g>
          <rect x="724" y="20" width="216" height="110" rx="12" fill="rgba(251,191,36,.05)" stroke="#fbbf24" stroke-opacity=".6"/>
          <text x="744" y="46" fill="#fbbf24" font-size="12.5" font-weight="700">跨域（RDMA）</text>
          <text x="744" y="70" fill="#8ea0c2" font-size="10.5">· EPBuffer dispatch/combine</text>
          <text x="744" y="88" fill="#8ea0c2" font-size="10.5">· EPLB NCCL P2P 迁移</text>
          <text x="744" y="106" fill="#8ea0c2" font-size="10.5">· EngramBuffer QP / BucketBuffer</text>
        </g>

        <g>
          <rect x="40" y="160" width="900" height="240" rx="12" fill="#0d1526" stroke="#263352"/>
          <text x="60" y="188" fill="#fff" font-size="13.5" font-weight="700">hybrid mode：一份 buffer，两条路径</text>
          <text x="60" y="214" fill="#8ea0c2" font-size="11.5">EPBuffer / EngramBuffer 均传 allow_hybrid_mode=True（userbuffer.py:78, 162）：组内同时含域内与跨域成员时，DeepEP 对域内对端走</text>
          <text x="60" y="234" fill="#8ea0c2" font-size="11.5">NVLink 直写、对跨域对端走 RDMA——上层（DeepInfer）完全无感知，只需给足 buffer 尺寸。</text>
          <text x="60" y="266" fill="#a78bfa" font-size="11.5"  font-weight="700">RDMA QP 细节（EngramBuffer，userbuffer.py:148-166）：</text>
          <text x="60" y="288" fill="#8ea0c2" font-size="11.5">· num_qps / qp_depth / restrict_rd_atomic 由 get_theoretical_config 按（组大小、层数、max tokens、entries/token）推导</text>
          <text x="60" y="308" fill="#8ea0c2" font-size="11.5">· use_cpu_rdma_storage：表存 CPU 注册内存走 RDMA，省显存；昇腾默认强制 GPU 存储（environ.py:154）</text>
          <text x="60" y="340" fill="#fbbf24" font-size="11.5" font-weight="700">服务级别（RoCE QoS）双队列：</text>
          <text x="60" y="362" fill="#8ea0c2" font-size="11.5">· sl3：EP / Engram 数据面（userbuffer.py:155 注释："EP 通信走 nvlink，此处 Engram sl 保持默认 sl3"）</text>
          <text x="60" y="382" fill="#8ea0c2" font-size="11.5">· sl2：预留 KV cache 流量隔离——同一张网卡上 MoE 突发不挤占 KV cache 转发带宽</text>
        </g>
      </svg>
      <div class="cap">图 10-1 · NVLink 域判定与 hybrid mode：三行判定函数分出两条数据面；QP 深度/原子性限制与服务级别隔离是跨域路径的工程细节。</div>
    </div>

    <ul class="feat">
      <li><b>判定输入</b>：<code>deep_ep.get_physical_domain_size(group)[1]</code> 返回该组的 NVLink 物理域大小；组大小不超过它 → 域内（parallel_state.py:130-134）。</li>
      <li><b>mega-MoE 的双重门</b>：除了域内，还要求 <code>PLATFORM.is_gpu 或 mma_type=="fp8xfp4"</code>（mlp.py:184-188）——昇腾 950 在 fp8xfp4 量化下同样走 SymmBuffer（DeepGEMM-Ascend），其余量化回退 EPBuffer。</li>
      <li><b>SymmBuffer 的 SM 本地性预热</b>：首个分配前调用 <code>locality_domain.get_balanced_sm_locality_domains()</code>，避免 DeepGEMM 首次使用时同步打断 CUDA graph 捕获（userbuffer.py:215-220）。</li>
      <li><b>buffer 复用与销毁</b>：EPBuffer 二次分配断言尺寸不缩水（userbuffer.py:81-83）；SymmBuffer 相同 spec 共享实例、首个 spec 持有底层存储（:195-225）；模型卸载时 <code>userbuffer.close()</code> 统一 destroy（:227-237）。</li>
    </ul>
  </section>

  <!-- ================= 11. 平台映射 ================= -->
  <section id="sec11">
    <h2 class="sec"><span class="num">11</span>GPU 与 NPU 平台的通信库映射对照</h2>
    <p class="lede">DeepInfer 通过 <code>PLATFORM</code> 单例（platform.py）在 NVIDIA SM100 与昇腾 950 之间切换整套通信栈——Python 层 API 不变，底层库成对替换。</p>

    <table class="tbl">
      <tr><th style="width:20%">维度</th><th style="width:40%">NVIDIA GPU（SM100）</th><th style="width:40%">昇腾 NPU（950）</th></tr>
      <tr><td>torch.distributed 后端</td><td><code>nccl</code>（platform.py:58）</td><td><code>hccl</code>（platform.py:89）</td></tr>
      <tr><td>组选项</td><td><code>ProcessGroupNCCL.Options</code>：<code>max_ctas=min_ctas=DEEPINFER_NCCL_NUM_SMS</code>（默认 32，platform.py:75-83）</td><td><code>ProcessGroupHCCL.Options</code>（platform.py:145-149）</td></tr>
      <tr><td>MoE 数据面</td><td>DeepEP（vendor/DeepEP submodule）；NVLink 域内可升级 mega-MoE</td><td>DeepEP-Ascend（vendor/DeepEP-Ascend submodule）；fp8xfp4 时亦可走 mega-MoE（DeepGEMM-Ascend）</td></tr>
      <tr><td>SymmBuffer 后端</td><td>DeepGEMM（NVLink 对称内存）</td><td>DeepGEMM-Ascend；<code>DEEPINFER_ENGRAM_FORCE_GPU_STORAGE</code> 默认 true（environ.py:154）</td></tr>
      <tr><td>is_within_nvl_domain</td><td>查询 <code>deep_ep.get_physical_domain_size</code></td><td>恒 True——整机视为单一通信域（parallel_state.py:132-133）</td></tr>
      <tr><td>EPLB shuffle</td><td>域内 symm_mem IPC + 跨机 NCCL P2P</td><td>HCCL P2P（batch_isend_irecv）；symm_mem 暂不支持（eplb/__init__.py:199 TODO）</td></tr>
      <tr><td>host 内存 pin</td><td><code>cudaHostRegister/Unregister</code>（platform.py:65-73）</td><td><code>aclrtHostRegisterV2(ACL_HOST_REG_PINNED)</code> / <code>aclrtHostUnregister</code>，经 ctypes 直连 libascendcl（platform.py:195-220）</td></tr>
      <tr><td>通信环境变量</td><td><code>DEEPINFER_NCCL_NUM_SMS=32</code></td><td><code>HCCL_BUFFSIZE=16</code>、<code>HCCL_CONNECT_TIMEOUT=240</code>、<code>HCCL_EXEC_TIMEOUT=200</code>、<code>HCCL_{HOST,NPU}_SOCKET_PORT_RANGE=auto</code>（platform.py:111-115）</td></tr>
      <tr><td>FP8 sf 类型</td><td>int32（4 个 ue8m0 打包，platform.py:63）</td><td>int16（2 个打包，platform.py:138）→ Engram sf 装载路径按 itemsize 自适应（engram.py:173-178）</td></tr>
      <tr><td>NCCL 显存观测</td><td>可用（nccl_memory.py，过滤 backend=="nccl"）</td><td>自动跳过（HCCL 组不匹配过滤器，nccl_memory.py:48-50）</td></tr>
      <tr><td>其他 NPU 适配</td><td>—</td><td><code>transfer_to_npu</code> 全局映射 torch.cuda→torch.npu（platform.py:121）；TASK_QUEUE_ENABLE=0、expandable_segments 等内存策略（platform.py:105-108）；npu_ops/ 目录补齐 deep_select、vit_attn 等算子</td></tr>
    </table>

    <div class="note"><b>昇腾侧的域语义</b>：<code>is_within_nvl_domain</code> 对 NPU 恒返回 True 意味着"跨域 RDMA"概念在单机 950 上不存在——所有 DeepEP-Ascend 通信都按机内高速互联处理；这也让 EPLB 的"跨机 P2P"分支在 NPU 上成为通用路径。</div>
  </section>

  <!-- ================= 12. 总结 ================= -->
  <section id="sec12">
    <h2 class="sec"><span class="num">12</span>关键发现与总结</h2>
    <p class="lede">十个结论，按"反直觉程度"排序。</p>

    <div class="timeline">
      <div class="tl-item reveal">
        <div class="tl-date">发现 01</div>
        <div class="tl-body"><b>训练式 all-reduce 在推理中被彻底消灭。</b>整个 forward 没有一次对 hidden_states 的 all-reduce：attention/共享专家/词表权重全复制（DP 语义），路由专家 EP 分片后 token 由 DeepEP dispatch/combine 搬运（mlp.py:461-511）。TP 及其 all-reduce 在推理架构里消失了。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">发现 02</div>
        <div class="tl-body"><b>NCCL 退居控制面与轻量数据面。</b>全仓 <code>dist.*</code> 调用仅 20 余处，全部是元数据、计数（int）、8 字节同步与低频权重迁移；没有一条持续的大流量路径跑在 NCCL 上。NCCL 还被限制只用 32 个 CTA（platform.py:81-82）。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">发现 03</div>
        <div class="tl-body"><b>NVLink 域内连 DeepEP 都可以省。</b><code>use_mega_moe</code> 命中时 gate 输出、fp8 cast 直接落进 SymmBuffer，GEMM 跨卡直读对端 buffer（mlp.py:528-563）——"通信"退化成内存语义，是跨卡通信的极限优化形态。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">发现 04</div>
        <div class="tl-body"><b>通信内核顺带做了可观测性。</b>dispatch 的 <code>cumulative_local_expert_recv_stats</code> 在收 token 时同步累计 EPLB 的 expert_count（mlp.py:474），负载统计零额外通信。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">发现 05</div>
        <div class="tl-body"><b>计算与通信在同一颗 GPU 上协商 SM。</b><code>DEEPINFER_USERBUFFER_COMM_SMS</code> 自动推导（userbuffer.py:86-90），combine 前 <code>limit_num_sms</code> 把 deep_gemm/tile_kernels 压到剩余 SM 上为通信让路（mlp.py:602）——推理通信的 SM 是"借"来的，不是独占网卡那一套。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">发现 06</div>
        <div class="tl-body"><b>一次广播，三套库。</b><code>broadcast_tensor_dict</code>（communication_op.py:51-82）：cuda 张量 → NCCL；张量元数据 → shm MQ；python 对象 → shm MQ。gloo 只在 MQ 创建时交换 shm 段句柄（shm_broadcast.py:454-457）。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">发现 07</div>
        <div class="tl-body"><b>CP 聚合是"会话"不是"调用"。</b>一个 prefill step 内多次 all-gather 共享 BucketBuffer 会话存储，wait 后零拷贝 view 拼接（cp.py:42-51）——比逐次 NCCL all_gather 少了反复的 buffer 分配与内核启动。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">发现 08</div>
        <div class="tl-body"><b>RoCE 服务级别做了流量隔离设计。</b>EP/Engram 走 sl3，sl2 显式留给 KV cache（userbuffer.py:155）——同网卡上 MoE 突发流量不会饿死对延迟敏感的 KV 转发。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">发现 09</div>
        <div class="tl-body"><b>Engram 是推理独有的"稀疏通信"形态。</b>按 hash 的 one-sided RDMA 读（engram.py:214-219）+ CPU 注册内存可选存储 + QP 深度/原子性按理论模型配置——它不是集合通信，更像一台跨卡分布式 KV 存储；而它的 sf 收集却老老实实走 NCCL all_gather（engram.py:100），两种库在同一初始化流程中混用。</div>
      </div>
      <div class="tl-item reveal">
        <div class="tl-date">发现 10</div>
        <div class="tl-body"><b>控制面通信"下地面"。</b>默认 world 组是 gloo、调度投票可走 CPU、对象广播走 shm+ZMQ、stop barrier 刻意避开 NCCL（worker/base.py:135-148，规避 pytorch#115388 的 CUDA graph 内 NCCL 销毁挂起）——GPU 通信资源被完整让给数据面。</div>
      </div>
    </div>

    <div class="note good" style="margin-top:26px"><b>一句话总结</b>：DeepInfer 的跨卡通信是一张精心分层的网——<b>DeepEP-V2 挑大梁</b>（MoE token 路由、Engram 稀疏读、CP 会话聚合），<b>SymmBuffer 管域内零拷贝</b>，<b>NCCL/HCCL 只做轻活</b>（元数据、计数、低频迁移、8 字节同步），<b>gloo 和 shm 把控制面彻底移出 GPU</b>；域判定三行代码（is_within_nvl_domain）+ hybrid mode + sl2/sl3 服务级别，把 NVLink 与 RDMA 两条物理链路编织成对上层透明的单一通信抽象。</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>NCCL 使用场景全景(代码视角)</title><link>https://hccl.club/docs/inference-engines/sglang/11-nccl-usage/</link><pubDate>Sun, 08 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/sglang/11-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;}
.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:30px;
  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:2px;margin-bottom:12px}
.fwdoc .hero h1{font-size:33px;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 .hero h1 .cursor{display:inline-block;width:10px;height:28px;vertical-align:-3px;margin-left:6px;border-radius:2px;
  background:var(--accent2);animation:curblink 1.1s steps(1) infinite}
.fwdoc .statrow{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px;margin-top:26px}
.fwdoc .statrow .stat{background:rgba(20,29,51,.72);border:1px solid var(--border);border-radius:12px;padding:14px 18px;text-align:center;backdrop-filter:blur(4px)}
.fwdoc .statrow .stat .v{font-size:26px;font-weight:800;color:#fff;font-family:Consolas,monospace}
.fwdoc .statrow .stat .v .u{font-size:13px;color:var(--accent2);margin-left:2px}
.fwdoc .statrow .stat .k{font-size:12px;color:var(--muted);margin-top:2px}
.fwdoc .klabel{font-size:11px;color:#5a6b92;letter-spacing:1px;text-transform:uppercase;margin-bottom:10px}
.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 .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 p{margin:10px 0;color:var(--text);font-size:14.5px}
.fwdoc ul{list-style:disc;padding-left:26px;margin:10px 0}
.fwdoc ol{list-style:decimal;padding-left:26px;margin:10px 0}
.fwdoc li{margin:6px 0}
.fwdoc h3{font-size:18.5px;color:#fff;margin:28px 0 10px}
.fwdoc h3.sub{border-left:3px solid var(--accent);padding-left:12px}
.fwdoc h4{font-size:15.5px;color:#e6ecf9;margin:20px 0 8px}
.fwdoc h5{font-size:14px;color:var(--muted);margin:14px 0 6px}
.fwdoc a{color:var(--accent2)}
.fwdoc a:hover{text-decoration:underline}
.fwdoc hr{border:0;border-top:1px dashed #2a3a5c;margin:26px 0}
.fwdoc strong{color:#fff;font-weight:700}
.fwdoc blockquote{border-left:3px solid var(--accent);padding:6px 16px;margin:14px 0;color:var(--muted)}
.fwdoc code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:.88em}
.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 8px}
.fwdoc .tag{display:inline-block;background:rgba(79,140,255,.12);color:var(--accent2);border-radius:6px;
  padding:2px 9px;font-size:12px;font-weight:600;margin:2px 4px 2px 0}
.fwdoc .muted{color:var(--muted)}
.fwdoc .small{font-size:12.5px}
.fwdoc .two-col{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@media(max-width:800px){.fwdoc .two-col{grid-template-columns:1fr}}
.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 code{background:transparent;padding:0;color:#cfe0f5;font-size:inherit}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border);display:block;overflow-x:auto}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px;white-space:nowrap}
.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 .grid-2{display:grid;gap:16px;grid-template-columns:repeat(auto-fit,minmax(320px,1fr))}
.fwdoc .grid-3{display:grid;gap:16px;grid-template-columns:repeat(auto-fit,minmax(240px,1fr))}
.fwdoc .grid-2 .card,.fwdoc .grid-3 .card{margin:0}
.fwdoc .card-title{font-size:16.5px;color:#fff;font-weight:700;margin:0 0 8px}
.fwdoc .stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:14px;margin:20px 0}
.fwdoc .stat-grid .stat{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:12px;padding:16px 12px;text-align:center}
.fwdoc .stat-value{font-size:27px;font-weight:800;color:#fff}
.fwdoc .stat-label{font-size:12px;color:var(--muted);margin-top:4px}
.fwdoc .callout{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13.5px;margin:16px 0}
.fwdoc .callout p{margin:6px 0}
.fwdoc .callout.c-info{border-left-color:var(--accent)}
.fwdoc .callout.c-tip{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .callout.c-warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .callout.c-danger{border-left-color:var(--bad);background:rgba(248,113,113,.06)}
.fwdoc .callout strong{color:#fff}
.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 .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px;margin:0 5px 4px 0}
.fwdoc .badge.b-blue{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.b-green{background:rgba(52,211,153,.12);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.b-orange{background:rgba(251,146,60,.12);color:#fb923c;border:1px solid rgba(251,146,60,.4)}
.fwdoc .badge.b-red{background:rgba(248,113,113,.12);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.b-gray{background:rgba(142,160,194,.12);color:var(--muted);border:1px solid rgba(142,160,194,.35)}
.fwdoc .badge.b-purple{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .toc{background:rgba(20,29,51,.6);border:1px solid var(--border);border-radius:12px;padding:16px 22px;margin:0 0 30px}
.fwdoc .toc-title{font-size:12.5px;font-weight:700;color:var(--muted);letter-spacing:2px;margin-bottom:8px}
.fwdoc .toc ol,.fwdoc .toc ul{columns:2;column-gap:28px;margin:0;padding-left:20px}
.fwdoc .toc li{margin:4px 0;font-size:13.5px;break-inside:avoid}
.fwdoc .toc a{color:var(--text);text-decoration:none}
.fwdoc .toc a:hover{color:var(--accent2)}
@media(max-width:800px){.fwdoc .toc ol,.fwdoc .toc ul{columns:1}}
.fwdoc .timeline{position:relative;padding-left:28px;margin:20px 0}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .timeline-item{position:relative;margin-bottom:24px}
.fwdoc .timeline-item::before{content:"";position:absolute;left:-24px;top:6px;width:11px;height:11px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.15);animation:fw-tlpulse 2.4s infinite}
@keyframes fw-tlpulse{0%,100%{opacity:.55}50%{opacity:1}}
.fwdoc .timeline-time{font-size:12px;color:var(--accent2);font-weight:700;font-family:Consolas,monospace}
.fwdoc .timeline-body{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:10px;padding:12px 16px;margin-top:6px}
.fwdoc .timeline-body p{margin:6px 0 0;font-size:13.5px}
.fwdoc .timeline-tag{display:inline-block;font-size:11px;font-weight:700;padding:1px 8px;border-radius:4px;
  background:rgba(79,140,255,.14);color:var(--accent2);margin-left:8px;vertical-align:1px}
.fwdoc .flow{display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin:18px 0}
.fwdoc .flow-v{display:flex;flex-direction:column;align-items:flex-start;gap:6px;margin:18px 0}
.fwdoc .flow .node,.fwdoc .flow-v .node{background:#101a2d;border:1.5px solid #3a5a8c;border-radius:9px;
  padding:8px 13px;font-size:13.5px;font-weight:600;color:#e6eefb}
.fwdoc .flow .node small,.fwdoc .flow-v .node small{display:block;font-weight:400;color:var(--muted);font-size:11.5px;margin-top:2px}
.fwdoc .node-accent{border-color:var(--accent) !important;background:rgba(79,140,255,.12) !important;color:#cfe4ff !important}
.fwdoc .arrow{color:#7d9ac4;font-size:19px;font-weight:700;line-height:1}
.fwdoc .arrow-v{color:#7d9ac4;font-size:17px;font-weight:700;padding-left:16px}
.fwdoc .chart{margin:20px 0}
.fwdoc .chart-row{display:grid;grid-template-columns:230px 1fr 70px;gap:10px;align-items:center;margin:8px 0;font-size:13.5px}
.fwdoc .chart-label{text-align:right;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.fwdoc .chart-track{background:rgba(10,16,32,.85);border-radius:6px;height:20px;overflow:hidden}
.fwdoc .chart-bar{height:100%;border-radius:6px 0 0 6px;background:var(--accent);min-width:2px}
.fwdoc .bar-blue{background:var(--accent)}
.fwdoc .bar-green{background:var(--good)}
.fwdoc .bar-orange{background:#fb923c}
.fwdoc .bar-red{background:var(--bad)}
.fwdoc .bar-purple{background:var(--purple)}
.fwdoc .bar-gray{background:#64748b}
.fwdoc .chart-value{font-family:Consolas,monospace;font-size:12px;color:var(--muted)}
.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:.1s}
.fwdoc .reveal.d2{transition-delay:.2s}
.fwdoc .reveal.d3{transition-delay:.3s}
.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 .pgnav a:hover{text-decoration:underline}
.fwdoc .scene{--T:6s;position:relative;background:radial-gradient(1100px 420px at 18% -12%,#16273f 0%,#0d1729 55%,#0a0f1c 100%);
  border:1px solid var(--border);border-radius:var(--radius);padding:20px 22px 18px;min-height:200px;
  color:#d7e3f4;overflow:hidden;margin:20px 0 8px}
.fwdoc .scene .sc-title{position:absolute;top:12px;left:16px;font-size:12.5px;font-weight:700;color:#8fa7c9;letter-spacing:.05em}
.fwdoc .scene .sc-hint{position:absolute;bottom:10px;right:14px;font-size:11px;color:#5d7396}
.fwdoc .scene .row{display:flex;align-items:center;gap:14px;flex-wrap:wrap}
.fwdoc .scene .col{display:flex;flex-direction:column;gap:12px;align-items:flex-start}
.fwdoc .scene .cen{justify-content:center;align-items:center}
.fwdoc .scene .stack{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px}
.fwdoc .scene .trow{display:flex;gap:4px;flex-wrap:wrap;align-items:center}
.fwdoc .scene .abs{position:absolute}
.fwdoc .scene .mt{margin-top:30px}
.fwdoc .scene .lbl{font-size:11.5px;color:#7d92b4;font-weight:600}
.fwdoc .scene .big{font-size:19px;font-weight:800;color:#eaf2ff}
.fwdoc .scene .dim{opacity:.42}
.fwdoc .scene .gpu{background:#101a2d;border:1.5px solid #31507e;border-radius:10px;padding:9px 14px;min-width:78px;
  text-align:center;font-weight:700;font-size:14px;color:#e6eefb}
.fwdoc .scene .gpu small{display:block;font-weight:400;color:#7d92b4;font-size:11.5px;margin-top:2px}
.fwdoc .scene .node{background:#101a2d;border:1.5px solid #3a5a8c;border-radius:10px;padding:8px 13px;text-align:center;
  font-weight:700;font-size:13.5px;color:#e6eefb}
.fwdoc .scene .node small{display:block;font-weight:400;color:#7d92b4;font-size:11.5px;margin-top:2px}
.fwdoc .scene .srv{border:1.5px solid #3b6ea5;border-radius:12px;padding:12px 14px;background:rgba(16,26,45,.78);min-width:170px}
.fwdoc .scene .srv-head{font-weight:800;color:#bfe0ff;font-size:13.5px;margin-bottom:8px}
.fwdoc .scene .zone{border:1.5px dashed #3a5b8f;border-radius:10px;padding:10px 12px}
.fwdoc .scene .bub{width:36px;height:36px;border-radius:50%;background:#16233c;border:1.5px solid #3a5a8c;
  display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#cfe0f7}
.fwdoc .scene .tok{width:16px;height:16px;border-radius:4px;background:#3a4a63;display:inline-block}
.fwdoc .scene .tok.a{background:#3b82f6}
.fwdoc .scene .tok.b{background:#22c55e}
.fwdoc .scene .tok.c{background:#f59e0b}
.fwdoc .scene .tok.d{background:#a78bfa}
.fwdoc .scene .tok.e{background:#f472b6}
.fwdoc .scene .kv{width:22px;height:14px;border-radius:3px;background:#3a4a63;display:inline-block}
.fwdoc .scene .bar{height:14px;border-radius:4px;background:#3b82f6;min-width:70px;transform-origin:left center}
.fwdoc .scene .bar.g{background:#22c55e}
.fwdoc .scene .bar.o{background:#f59e0b}
.fwdoc .scene .bar.r{background:#ef4444}
.fwdoc .scene .wire{height:2px;flex:none;min-width:40px;background:repeating-linear-gradient(90deg,#3f6db3 0 8px,transparent 8px 16px);animation:fw-k-flow .9s linear infinite}
.fwdoc .scene .wire.v{width:2px;min-width:0;height:auto;align-self:stretch;min-height:34px;
  background:repeating-linear-gradient(180deg,#3f6db3 0 8px,transparent 8px 16px);animation:fw-k-flowv .9s linear infinite}
.fwdoc .scene .pkt{position:absolute;width:12px;height:12px;border-radius:50%;background:#38bdf8;box-shadow:0 0 12px rgba(56,189,248,.8)}
.fwdoc .scene .pkt.g{background:#34d399;box-shadow:0 0 12px rgba(52,211,153,.8)}
.fwdoc .scene .pkt.o{background:#fb923c;box-shadow:0 0 12px rgba(251,146,60,.8)}
.fwdoc .scene .pkt.r{background:#f87171;box-shadow:0 0 12px rgba(248,113,113,.8)}
.fwdoc .scene .pkt.v{background:#a78bfa;box-shadow:0 0 12px rgba(167,139,250,.8)}
.fwdoc .scene .mv{animation:fw-k-mv var(--T) linear infinite}
.fwdoc .scene .pop{animation:fw-k-pop var(--T) ease-in-out infinite}
.fwdoc .scene .fadein{animation:fw-k-fadein var(--T) ease-in-out infinite}
.fwdoc .scene .hit{animation:fw-k-on var(--T) ease-in-out infinite}
.fwdoc .scene .hit.o{animation-name:fw-k-on-o}
.fwdoc .scene .hit.r{animation-name:fw-k-on-r}
.fwdoc .scene .hit.b{animation-name:fw-k-on-b}
.fwdoc .scene .ok{animation:fw-k-ok var(--T) ease-in-out infinite}
.fwdoc .scene .no{animation:fw-k-no var(--T) ease-in-out infinite}
.fwdoc .scene .pulse{animation:fw-k-pulse 1.8s ease-in-out infinite}
.fwdoc .scene .glow{animation:fw-k-glow 2.4s ease-in-out infinite}
.fwdoc .scene .grow{animation:fw-k-grow var(--T) ease-in-out infinite;transform-origin:left center}
.fwdoc .scene .alt{animation-direction:alternate}
.fwdoc .scene .svgflow{stroke-dasharray:5 9;animation:fw-k-dash 1.1s linear infinite}
.fwdoc .scene .d1{animation-delay:calc(var(--T)*.04)}
.fwdoc .scene .d2{animation-delay:calc(var(--T)*.08)}
.fwdoc .scene .d3{animation-delay:calc(var(--T)*.12)}
.fwdoc .scene .d4{animation-delay:calc(var(--T)*.16)}
.fwdoc .scene .d5{animation-delay:calc(var(--T)*.20)}
.fwdoc .scene .d6{animation-delay:calc(var(--T)*.24)}
.fwdoc .scene .d7{animation-delay:calc(var(--T)*.28)}
.fwdoc .scene .d8{animation-delay:calc(var(--T)*.32)}
.fwdoc .scene .d9{animation-delay:calc(var(--T)*.36)}
.fwdoc .scene .d10{animation-delay:calc(var(--T)*.40)}
.fwdoc .scene .d11{animation-delay:calc(var(--T)*.44)}
.fwdoc .scene .d12{animation-delay:calc(var(--T)*.48)}
.fwdoc .scene .d13{animation-delay:calc(var(--T)*.52)}
.fwdoc .scene .d14{animation-delay:calc(var(--T)*.56)}
.fwdoc .scene .d15{animation-delay:calc(var(--T)*.60)}
.fwdoc .scene .d16{animation-delay:calc(var(--T)*.64)}
.fwdoc .scene .d17{animation-delay:calc(var(--T)*.68)}
.fwdoc .scene .d18{animation-delay:calc(var(--T)*.72)}
.fwdoc .scene .d19{animation-delay:calc(var(--T)*.76)}
.fwdoc .scene .d20{animation-delay:calc(var(--T)*.80)}
.fwdoc .scene .d21{animation-delay:calc(var(--T)*.84)}
.fwdoc .scene .d22{animation-delay:calc(var(--T)*.88)}
.fwdoc .scene .d23{animation-delay:calc(var(--T)*.92)}
.fwdoc .scene .d24{animation-delay:calc(var(--T)*.96)}
@keyframes fw-k-flow{to{background-position:16px 0}}
@keyframes fw-k-flowv{to{background-position:0 16px}}
@keyframes fw-k-mv{0%{transform:translate(0,0);opacity:0}10%{opacity:1}85%{opacity:1}100%{transform:translate(var(--tx,120px),var(--ty,0));opacity:0}}
@keyframes fw-k-pop{0%,8%{transform:scale(0);opacity:0}20%,82%{transform:scale(1);opacity:1}94%,100%{transform:scale(0);opacity:0}}
@keyframes fw-k-fadein{0%,10%{opacity:0}28%,84%{opacity:1}96%,100%{opacity:0}}
@keyframes fw-k-on{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#22c55e;box-shadow:0 0 12px rgba(34,197,94,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-on-o{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#f59e0b;box-shadow:0 0 12px rgba(245,158,11,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-on-r{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#ef4444;box-shadow:0 0 12px rgba(239,68,68,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-on-b{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#3b82f6;box-shadow:0 0 12px rgba(59,130,246,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-ok{0%,18%{background:#3a4a63;transform:scale(1);box-shadow:none}34%,86%{background:#22c55e;transform:scale(1.22);box-shadow:0 0 12px rgba(34,197,94,.6)}100%{background:#22c55e;transform:scale(1)}}
@keyframes fw-k-no{0%,16%{background:#3a4a63;opacity:1;transform:translateX(0)}30%{background:#ef4444}38%{transform:translateX(-4px)}48%{transform:translateX(4px)}62%{opacity:.22;transform:translateY(7px)}100%{opacity:.22;transform:translateY(7px);background:#3a4a63}}
@keyframes fw-k-pulse{0%,100%{transform:scale(1)}50%{transform:scale(1.1)}}
@keyframes fw-k-glow{0%,100%{box-shadow:0 0 0 0 rgba(59,130,246,0)}50%{box-shadow:0 0 18px 2px rgba(59,130,246,.55)}}
@keyframes fw-k-grow{0%,10%{transform:scaleX(.08)}42%,82%{transform:scaleX(1)}94%,100%{transform:scaleX(.08)}}
@keyframes fw-k-dash{to{stroke-dashoffset:-56}}
.fwdoc .scene-bar{position:absolute;top:10px;right:12px;display:flex;gap:5px;z-index:9}
.fwdoc .scene-bar button{background:rgba(13,21,36,.88);color:#9fb4d4;border:1px solid #2c4166;border-radius:7px;
  font-size:12px;padding:3px 10px;cursor:pointer;font-family:inherit}
.fwdoc .scene-bar button:hover{color:#fff;border-color:var(--accent)}
.fwdoc .scene-bar button.on{color:#fff;background:#1f4fd8;border-color:#1f4fd8}
.fwdoc .scene.paused *{animation-play-state:paused !important}
.fwdoc .scene.hold *{animation:none !important}
@media(prefers-reduced-motion:reduce){.fwdoc .scene,.fwdoc .scene *{animation:none !important}}
.fwdoc .sc-cap{font-size:13.5px;color:var(--muted);margin:0 0 26px;padding:0 4px}
.fwdoc .sc-cap strong{color:#fff}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:22px;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 .station{animation:fw-stationGlow 2.4s ease-in-out infinite}
@keyframes fw-stationGlow{0%,100%{opacity:.55}50%{opacity:1}}
.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 .oneline{font-size:13.5px;color:var(--text);margin:10px 0 6px;padding-left:12px;border-left:3px solid var(--accent)}
.fwdoc ul.feat{list-style:none;margin:8px 0}
.fwdoc ul.feat li{padding:6px 0 6px 26px;position:relative;font-size:13px;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-blinkdot 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
.fwdoc .paths{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0 2px}
.fwdoc .paths .filepath{font-size:10.5px}
.fwdoc .full{color:var(--good);font-weight:700}
.fwdoc .half{color:var(--warn);font-weight:700}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-svgflowmove 1.2s linear infinite}
@keyframes fw-svgflowmove{to{stroke-dashoffset:-14}}
.fwdoc .svgpulse{animation:fw-svgpulse 2s ease-in-out infinite;transform-origin:center;transform-box:fill-box}
@keyframes fw-svgpulse{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-tokrun{0%{transform:translateX(-6px);opacity:0}15%{opacity:1}85%{opacity:1}100%{transform:translateX(150px);opacity:0}}
@keyframes fw-growbar{from{width:0}to{width:100%}}
/* ===== 导入面板附加样式 ===== */
.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>

<div class="toc"><div class="toc-title">本页目录 · 先动画建立直觉,再源码落到实地</div><ol><li><a href="#anim">0. 动画速览 · 建立直觉</a></li><li><a href="#sec-1">1. 概述:NCCL 在 SGLang 中的两条主线</a></li><li><a href="#sec-2">2. 通信栈分层与关键组件</a></li><li><a href="#sec-3">3. PyNccl 封装代码走读:为什么绕过 torch.distributed</a></li><li><a href="#sec-4">4. 逐场景枚举:NCCL 到底用在哪里</a></li><li><a href="#sec-5">5. 非 NCCL 通信路径与后端选择决策</a></li><li><a href="#sec-6">6. NCCL 相关环境变量与配置项</a></li><li><a href="#sec-7">7. 部署侧:Dockerfile 与脚本中的 NCCL</a></li><li><a href="#sec-8">8. NCCL 使用场景矩阵(大汇总)</a></li><li><a href="#sec-9">9. 现状与演进</a></li><li><a href="#sec-10">10. 小结</a></li></ol></div>

  <section>
<h2 class="sec" id="anim"><span class="num">0</span>动画速览 · 建立直觉</h2>
<p class="lede">多张 GPU 合力跑一个大模型,第一件事不是"算",而是"说话"。本篇用四个动画看清 NCCL 这门多卡通用语:它怎么沿环接力求和、备了哪几种常用句式、为什么小消息反而常走 SGLang 自家的快车道,以及为什么连"录音磁带"里都必须能说话。</p>


  <div class="callout c-tip"><strong>一句话理解:</strong>NCCL 是 NVIDIA 造的"多卡通用语",专管集合通信——allreduce 求和、all-gather 拼齐、broadcast 一传多;它懂硬件拓扑(NVLink、PCIe、网络),会自己挑最快的路径。SGLang 里凡是"多卡合力算一层、词表结果汇总、采样决策对齐"的时刻都靠它传话;而框架对它"既用又管":小消息让给自家快车道,"录音"场景则与本尊直接握手。</div>

  

  <p>先说清楚"为什么要说话"。一台 GPU 再强,也常常装不下今天的大模型,于是有了"并行":把一层层大矩阵切开,分给多张卡同时算。但切开只是第一步——每张卡算完自己那份,手里握着的只是<strong>半成品</strong>。要把半成品拼成完整结果,卡与卡之间就必须交换数据;交换越频繁,协作越紧密。说话,是多卡推理里和"算"同等重要的日常。</p>
  <p>说话就要有语言。NCCL 就是 NVIDIA 为 GPU 量身打造的"多卡通用语":它只干一类事——<strong>集合通信</strong>,让一组 GPU 像一个配合默契的班组一样统一行动(人人交一份数、换回一个总和;每人举一块拼图、换回整幅图;一人喊话、全员听到)。它还特别"懂路":机箱里有 NVLink 高速内联就走近道,只有 PCIe 就走总线,跨机器就走网络——同一句话,它自己挑当前硬件上最快的走法,不用你操心。在 SGLang 里,这门语言无处不在:凡是"多卡合力算一层、把词表结果拼齐、让各卡采样决策对齐"的时刻,背后都是它在跑腿。</p>

  <h3 class="sub" id="s1">环形求和:四张卡的接力加法</h3>
  <p>先看使用频率最高的一句话:<strong>环形求和(allreduce)</strong>。张量并行把一个大矩阵按行切开,四张卡各算出四分之一的结果——注意,是"四分之一份完整结果",不是"最终答案的四分之一块"。要得到最终答案,必须把四份<strong>全部加起来</strong>,而且四张卡每张都要拿到这个总和,下一层才能继续各算各的。</p>
  <p>最笨的办法是"中心化":所有卡把数发给卡 0,卡 0 加完再发回所有人。卡 0 既当邮差又当会计,别人全在排队等它。NCCL 的经典做法是<strong>环形接力</strong>:四张卡围成一圈,报文沿环逐段传递,每到一站就把手里的数和这一站的数加在一起;跑完第一圈,总和已经算出;第二圈再把总和送回每一站。环上没有谁是中心,带宽被均匀摊到每一段链路上——卡越多,这种"人人有活干、没人当瓶颈"的结构越划算。在 SGLang 里,只要把模型切开多卡算,几乎每一层的前后半程都要来一次这样的求和,它是多卡推理中名副其实的"口头禅"。</p>

  <div class="scene" style="height:380px">
    <div class="sc-title">场景 · 环形求和:四张卡转两圈,人人拿到总和</div>
    <div class="abs" style="left:calc(50% - 340px);top:36px;width:680px;height:320px">
      <div class="gpu abs glow d18" style="left:0;top:10px;width:150px">GPU 0<small>我出 1</small><span class="bub">1</span> → <span class="bub hit d18">10</span></div>
      <div class="gpu abs glow d18" style="left:530px;top:10px;width:150px">GPU 1<small>我出 2</small><span class="bub">2</span> → <span class="bub hit d18">10</span></div>
      <div class="gpu abs glow d18" style="left:530px;top:210px;width:150px">GPU 2<small>我出 3</small><span class="bub">3</span> → <span class="bub hit d18">10</span></div>
      <div class="gpu abs glow d18" style="left:0;top:210px;width:150px">GPU 3<small>我出 4</small><span class="bub">4</span> → <span class="bub hit d18">10</span></div>
      <div class="wire abs" style="left:158px;top:56px;width:364px"></div>
      <div class="wire v abs" style="left:604px;top:114px;height:94px"></div>
      <div class="wire abs" style="left:158px;top:256px;width:364px"></div>
      <div class="wire v abs" style="left:74px;top:114px;height:94px"></div>
      <div class="lbl abs" style="left:200px;top:26px">第一圈 · 边走边加(求和)</div>
      <div class="lbl abs" style="left:196px;top:268px">第二圈 · 总和送回每家(分发)</div>
      <div class="pkt mv" style="left:160px;top:51px;--tx:358px;--ty:0px;--T:1.6s;animation-delay:.2s"></div>
      <div class="pkt mv" style="left:599px;top:118px;--tx:0px;--ty:82px;--T:1.6s;animation-delay:.6s"></div>
      <div class="pkt mv" style="left:516px;top:251px;--tx:-356px;--ty:0px;--T:1.6s;animation-delay:1s"></div>
      <div class="pkt mv" style="left:69px;top:200px;--tx:0px;--ty:-82px;--T:1.6s;animation-delay:1.4s"></div>
      <div class="pkt g mv" style="left:160px;top:51px;--tx:358px;--ty:0px;--T:1.6s;animation-delay:1s"></div>
      <div class="pkt g mv" style="left:599px;top:118px;--tx:0px;--ty:82px;--T:1.6s;animation-delay:1.4s"></div>
      <div class="pkt g mv" style="left:516px;top:251px;--tx:-356px;--ty:0px;--T:1.6s;animation-delay:1.8s"></div>
      <div class="pkt g mv" style="left:69px;top:200px;--tx:0px;--ty:-82px;--T:1.6s;animation-delay:2.2s"></div>
    </div>
    <div class="sc-hint">蓝 = 求和圈 · 绿 = 分发圈 · 末尾同时亮出总和</div>
  </div>
  <p class="sc-cap">动画解说:<strong>蓝色报文沿环逐段接力</strong>,每经过一张卡就"顺手加上一份"——转完第一圈,总和 10 已经算出(<strong>求和</strong>);<strong>绿色报文紧跟着再转一圈</strong>,把总和送到每一站(<strong>分发</strong>);动画末尾,四张卡上的"10"<strong>同时亮起</strong>——人人手里都有完整结果,而整条环上没有谁是中心。</p>

  <h3 class="sub" id="s2">原语三兄弟:拼齐、广播、各拿一段</h3>
  <p>allreduce 只是"原语三兄弟"里的大哥。集合通信的常用句式一共就那么几个,每一个都在 SGLang 里有明确戏份:</p>
  <ul>
    <li><strong>all-gather(拼齐)</strong>:词表通常按卡切开,每张卡只算出自己那段词的得分;要挑下一个 token,得先把所有卡的分段<strong>拼成完整的一行</strong>。每人交出自己那块拼图,换回整幅图——词表汇总正是这个句式。</li>
    <li><strong>broadcast(一传多)</strong>:有些决定必须全员一致——比如采样出的下一个 token、某条请求要不要中止。一张卡拍板,<strong>一句话广播给所有卡</strong>,免得各副本各走各路、输出对不上。</li>
    <li><strong>reduce-scatter(各拿一段)</strong>:allreduce 的"省钱版"。同样把大家的数加起来,但每张卡<strong>只保留结果中自己负责的那一段</strong>——下一层反正要按段切开算,何必人人背整份总和?四张卡时通信量直接省下四分之三,卡越多省得越多。把各卡凑到一起的中间结果算完再各拿回自己那份,用的也是它。</li>
  </ul>
  <p>这些句式还有不少亲戚(all-to-all 交换、变长拼齐等),思想都一样:把"一群卡各自手里的东西",变成"一群卡都想要的东西"。下面把三兄弟并排演一遍。</p>

  <div class="scene">
    <div class="sc-title">场景 · 原语三兄弟:all-gather / broadcast / reduce-scatter</div>
    <div class="stack mt">
      <div class="zone">
        <div><span class="lbl">all-gather · 拼齐</span></div>
        <div class="col">
          <div class="row cen">
            <div class="col cen"><span class="lbl">卡 0</span><span class="tok a"></span></div>
            <div class="col cen"><span class="lbl">卡 1</span><span class="tok b"></span></div>
            <div class="col cen"><span class="lbl">卡 2</span><span class="tok c"></span></div>
            <div class="col cen"><span class="lbl">卡 3</span><span class="tok d"></span></div>
          </div>
          <div class="row cen"><div class="wire" style="width:120px"></div></div>
          <div class="row"><span class="lbl">卡 0 拿到</span><div class="trow"><span class="tok a pop d8"></span><span class="tok b pop d8"></span><span class="tok c pop d8"></span><span class="tok d pop d8"></span></div></div>
          <div class="row"><span class="lbl">卡 1 拿到</span><div class="trow"><span class="tok a pop d10"></span><span class="tok b pop d10"></span><span class="tok c pop d10"></span><span class="tok d pop d10"></span></div></div>
          <div class="row"><span class="lbl">卡 2 拿到</span><div class="trow"><span class="tok a pop d12"></span><span class="tok b pop d12"></span><span class="tok c pop d12"></span><span class="tok d pop d12"></span></div></div>
          <div class="row"><span class="lbl">卡 3 拿到</span><div class="trow"><span class="tok a pop d14"></span><span class="tok b pop d14"></span><span class="tok c pop d14"></span><span class="tok d pop d14"></span></div></div>
        </div>
      </div>
      <div class="zone">
        <div><span class="lbl">broadcast · 一传多</span></div>
        <div class="col">
          <div class="row cen"><div class="gpu pulse">卡 0 · 源头<small>整份数据 <span class="tok e"></span></small></div></div>
          <div class="row cen"><div class="wire" style="width:200px"></div></div>
          <div class="row cen">
            <div class="row cen" style="width:78px"><div class="wire v"></div></div>
            <div class="row cen" style="width:78px"><div class="wire v"></div></div>
            <div class="row cen" style="width:78px"><div class="wire v"></div></div>
          </div>
          <div class="row cen">
            <div class="gpu">卡 1<small>收到</small><span class="tok e hit" style="animation-delay:1.5s"></span></div>
            <div class="gpu">卡 2<small>收到</small><span class="tok e hit" style="animation-delay:1.5s"></span></div>
            <div class="gpu">卡 3<small>收到</small><span class="tok e hit" style="animation-delay:1.5s"></span></div>
          </div>
        </div>
      </div>
      <div class="zone">
        <div><span class="lbl">reduce-scatter · 各拿一段</span></div>
        <div class="col">
          <div class="row cen">
            <div class="col cen"><span class="lbl">卡 0</span><span class="tok a"></span></div>
            <div class="col cen"><span class="lbl">卡 1</span><span class="tok b"></span></div>
            <div class="col cen"><span class="lbl">卡 2</span><span class="tok c"></span></div>
            <div class="col cen"><span class="lbl">卡 3</span><span class="tok d"></span></div>
          </div>
          <div class="row cen"><div class="wire" style="width:120px"></div></div>
          <div class="row"><span class="lbl">卡 0 → 留第 1 段</span><div class="trow"><span class="tok a ok d12"></span><span class="tok b dim"></span><span class="tok c dim"></span><span class="tok d dim"></span></div></div>
          <div class="row"><span class="lbl">卡 1 → 留第 2 段</span><div class="trow"><span class="tok a dim"></span><span class="tok b ok d14"></span><span class="tok c dim"></span><span class="tok d dim"></span></div></div>
          <div class="row"><span class="lbl">卡 2 → 留第 3 段</span><div class="trow"><span class="tok a dim"></span><span class="tok b dim"></span><span class="tok c ok d16"></span><span class="tok d dim"></span></div></div>
          <div class="row"><span class="lbl">卡 3 → 留第 4 段</span><div class="trow"><span class="tok a dim"></span><span class="tok b dim"></span><span class="tok c dim"></span><span class="tok d ok d18"></span></div></div>
        </div>
      </div>
    </div>
    <div class="pkt mv" style="left:49.5%;top:160px;--tx:-87px;--ty:64px;--T:1.2s;animation-delay:.3s"></div>
    <div class="pkt mv" style="left:49.5%;top:160px;--tx:0px;--ty:66px;--T:1.2s;animation-delay:.45s"></div>
    <div class="pkt mv" style="left:49.5%;top:160px;--tx:95px;--ty:64px;--T:1.2s;animation-delay:.6s"></div>
  </div>
  <p class="sc-cap">动画解说:左——四张卡各举一块拼图,交换之后<strong>人人都有完整的一行</strong>(all-gather),词表汇总正是这个句式;中——<strong>一张卡向四周发包</strong>(broadcast),三张卡同时拿到同一份数据并确认收到,采样决策靠它对齐;右——大家算的是同一份结果,但<strong>每张卡只亮自己那一段</strong>(reduce-scatter),其余变暗,通信量省下四分之三。</p>

  <h3 class="sub" id="s3">大小消息分道:快车道与高速公路</h3>
  <p>既然 NCCL 这么全能,是不是所有消息都该交给它?未必。这里有个反直觉的事实:<strong>小消息反而常常不走 NCCL,走的是 SGLang 自家的"快车道"</strong>。原因在于,NCCL 是通用语,为了适应千奇百怪的机器和消息,它每说一句话前都要"铺垫"——选算法、排通道、对齐进度。消息足够大时,这些铺垫被摊薄,吞吐极高,像高速公路,又宽又稳;可消息只有几十个数字时,铺垫本身比"话"还长,上高速就亏了。</p>
  <p>于是 SGLang 在同一段路 上修了两种道:<strong>小消息走自研快车道</strong>——同一台机器里的卡之间"手递手":进程间直通(IPC)一跳送达,或者用对称内存提前摆好一块几张卡共用的"黑板",写完直接互相可见,几乎零铺垫;<strong>大消息、跨机器的消息、以及快车道不认识的"包裹类型",统统交给 NCCL 这条高速公路</strong>。选道不看心情,看尺寸:消息大小长过阈值,自动换道。解码时每一层的求和消息往往不大,快道收益最明显;预填充长上下文时消息很大,正是高速的主场。</p>

  <div class="scene">
    <div class="sc-title">场景 · 分道行驶:小消息抄近路,大消息上高速</div>
    <div class="col mt">
      <div class="row cen"><span class="lbl">① 小消息 → 自研快车道:点对点直递,一跳送达</span></div>
      <div class="row cen">
        <div class="node">卡组 A</div>
        <div class="wire" style="width:90px"></div>
        <div class="node">卡组 B</div>
      </div>
      <div class="row cen"><span class="lbl">② 大消息 → NCCL 高速:环形多车道,又宽又稳</span></div>
      <div class="row cen">
        <div class="node">卡组 A</div>
        <div class="wire" style="width:360px;height:6px"></div>
        <div class="node">卡组 B</div>
      </div>
      <div class="row cen">
        <span class="lbl">③ 消息多大,走哪条道?</span>
        <div class="bar o grow" style="width:230px"></div>
        <span class="lbl">长过虚线阈值 → 换走橙色高速</span>
      </div>
    </div>
    <div class="pkt g mv" style="left:45%;top:97px;--tx:82px;--ty:0px;--T:1.4s;animation-delay:.1s"></div>
    <div class="pkt g mv" style="left:45%;top:97px;--tx:82px;--ty:0px;--T:1.4s;animation-delay:.8s"></div>
    <div class="pkt o mv" style="left:32%;top:184px;--tx:340px;--ty:0px;--T:4.5s;animation-delay:.5s;width:16px;height:16px"></div>
    <div class="pkt o mv" style="left:32%;top:184px;--tx:340px;--ty:0px;--T:4.5s;animation-delay:2.75s;width:16px;height:16px"></div>
    <div class="wire v abs" style="left:49%;top:216px;height:30px"></div>
  </div>
  <p class="sc-cap">动画解说:<strong>绿色小包在短道上接连闪过</strong>——小消息走自研快车道,点对点直递,几乎零铺垫,一闪即到;<strong>橙色大包在宽道上稳稳滑行</strong>——大消息交给 NCCL 高速公路,车道宽、多路径并行,吞吐拉满;底部那把<strong>"尺子"随消息变大而增长</strong>,一旦长过虚线阈值,同样的数据就换上橙色、改走高速。</p>

  <h3 class="sub" id="s4">磁带里也要说话:直连握手本尊</h3>
  <p>还有一件事,逼着 SGLang 和 NCCL"直接握手"。前面讲过 CUDA Graph(见<a href="/docs/inference-engines/sglang/05-cuda-graph/">第 06 篇</a>):把一整段解码计算<strong>"录音"成磁带</strong>,之后每个解码步直接"回放",省掉 CPU 反复排活的功夫。问题来了:磁带里录的不该只有计算,还得有通信——解码时每一层都要求和,如果通信留在磁带外面,每次回放还得 CPU 临时去叫邮差,录音的好处就被吃掉了。</p>
  <p>但"录音棚"有规矩:录制期间,所有动作必须能被<strong>原样记下、回放时原样重演</strong>。SGLang 平时是借道 PyTorch 的通用分布式封装和 NCCL 说话的——平时很好用,可这个封装要照顾的场景太多,不保证守录音棚的规矩:它时不时会"抢话筒",做一些录制期不允许的小动作。所以 SGLang 又修了一条<strong>直连通道:绕过封装,直接与 NCCL 本尊握手</strong>——把"通信"当成和"矩阵乘"一样的普通音符,老老实实排进磁带。回放时,报文就在磁带盒子内部流动,计算与通信一气呵成。</p>

  <div class="scene" style="height:340px">
    <div class="sc-title">场景 · 磁带里的对话:录进去的不只是计算,还有通信</div>
    <div class="zone abs" style="left:calc(50% - 350px);top:40px;width:700px;height:150px">
      <div><span class="lbl">已录制的"计算磁带" · 回放中</span> <span class="tok b pulse"></span></div>
      <div class="row cen">
        <div class="node">注意力计算<small>本卡算自己那份</small></div>
        <div class="wire" style="width:60px"></div>
        <div class="node glow">通信 · 求和<small>NCCL 直连</small></div>
        <div class="wire" style="width:60px"></div>
        <div class="node">前馈计算<small>本卡算自己那份</small></div>
      </div>
    </div>
    <div class="pkt mv" style="left:20%;top:100px;--tx:120px;--ty:0px;--T:2.4s;animation-delay:.2s"></div>
    <div class="pkt mv" style="left:37%;top:100px;--tx:52px;--ty:0px;--T:2.4s;animation-delay:1s"></div>
    <div class="pkt g mv" style="left:57%;top:100px;--tx:54px;--ty:0px;--T:2.4s;animation-delay:1.8s"></div>
    <div class="mt" style="height:160px"></div>
    <div class="row cen">
      <div class="col cen">
        <div class="node no d10">借道通用封装<small>录音时会"抢话筒" → 录不进去</small></div>
        <span class="lbl">平时好用 · 录音被拒</span>
      </div>
      <div class="wire v"></div>
      <div class="col cen">
        <div class="node ok d14">直连握手 NCCL 本尊<small>通信像计算一样,老实排队进带</small></div>
        <span class="lbl">磁带内外都听话</span>
      </div>
    </div>
  </div>
  <p class="sc-cap">动画解说:大盒子是一盘<strong>已录好、正在回放的计算磁带</strong>——里面不只有计算节点,还有一个<strong>通信节点</strong>;回放时报文就在盒子内部流动,算一步、说一句,一气呵成。下方是这一切能成立的原因:<strong>借道通用封装的报文,录音那一刻会被拒</strong>(红色抖动、沉底);而<strong>直连握手 NCCL 本尊</strong>的报文,像普通计算一样老实排队,被原样录进磁带。</p>

  <h3 class="sub" id="summary">小结:多卡世界的 TCP/IP,既用又管</h3>
  <p>把本篇压成一句话:<strong>NCCL 之于多卡世界,就像 TCP/IP 之于互联网</strong>——你不必关心信件具体走哪条光缆,只管把信写好;它负责让信又快又稳地送达每一方。对 SGLang 来说,它是所有"多卡合力"时刻的默认底座。</p>
  <div class="grid-2">
    <div class="card">
      <div class="card-title">为什么快</div>
      <p>它懂路:NVLink、PCIe、网络各有多条走法,环形、树形、多播按消息大小与拓扑自动选型;大消息上高速,把每条链路都吃满,不浪费一丝带宽。</p>
    </div>
    <div class="card">
      <div class="card-title">为什么省</div>
      <p>句式按需挑:要整份就 all-gather,只要自己那段就 reduce-scatter,不传用不上的字节;小消息干脆走零铺垫的自家快道,不劳高速公路大驾。</p>
    </div>
    <div class="card">
      <div class="card-title">为什么稳</div>
      <p>它是兜底:快车道不接的活——超大消息、跨机器、不认识的包裹类型——最终都落回 NCCL;不挑食、覆盖全,换了硬件也不用改用法。</p>
    </div>
  </div>
  <p>而 SGLang 对它的态度是<strong>"既用又管"</strong>:用——一切集合通信的底座;管——通过一批环境变量开关替它调优(选哪种算法、开多少通道、启不启新特性),像替高速公路发布行车守则;并且按"消息多大、是否在磁带里、什么包裹类型"自动换道,让每句话都走当下最划算的那条路。并行策略的总体设计见<a href="/docs/inference-engines/sglang/03-parallelism/">第 04 篇</a>,录音机的原理见<a href="/docs/inference-engines/sglang/05-cuda-graph/">第 06 篇</a>;下一篇我们讲这门语言自己的故事——<a href="/docs/inference-engines/sglang/12-nccl-pr-history/">NCCL 演进史:从单一依赖到多后端并存</a>。</p>

  <h3 class="sub" id="faq">常见误解 FAQ</h3>
  <div class="callout c-info">
    <strong>误解一:"NCCL 也在算,它占算力吗?"</strong>
    <p>它不产算力,只管传话。搬运路上顺手把几份数加在一起,那点"算术"是为搬运服务的;真正的模型计算仍由各卡的算力完成。可以把它理解成一位跑得飞快的"邮差兼记账助理"——账还是 GPU 的账。</p>
  </div>
  <div class="callout c-info">
    <strong>误解二:"SGLang 自研快车道,是想取代 NCCL?"</strong>
    <p>恰恰相反,它的对手是自己人。自研快车道只抢小消息的活:同机直递、零铺垫;大消息、跨机器、以及一切快车道不接的包裹,全是 NCCL 的。两者是分工,不是替代——就像小区门口的直达班车再方便,也不会取代高速公路。</p>
  </div>
  <div class="callout c-info">
    <strong>误解三:"既然有通用封装,为什么还要直连本尊?"</strong>
    <p>不是封装不好,而是"录音棚"的规矩特殊:录进 CUDA Graph 的每个动作都必须可原样重放,通用封装要照顾的场景太多,不保证守这个规矩。直连版本专为守规矩而生——让磁带里也能说话,解码回放才能真正一气呵成。</p>
  </div>

  
</section>

<section>
<h2 class="sec" id="sec-1"><span class="num">1</span>概述:NCCL 在 SGLang 中的两条主线</h2>
  <p>SGLang 是多 GPU/多机推理框架,张量并行(TP)、流水线并行(PP)、专家并行(EP)、注意力数据并行(DP Attention)、上下文并行(CP)等一切并行策略最终都落在<strong>集合通信</strong>上,而 NCCL 是 NVIDIA GPU 上集合通信的默认底座。从代码看,SGLang 使用 NCCL 的方式有两条清晰的主线:</p>
  <ul>
    <li><strong>主线一:torch.distributed 进程组</strong>。由 <span class="filepath">python/sglang/srt/distributed/parallel_state.py</span> 的 <code>init_distributed_environment</code>(parallel_state.py:2465)调用 <code>torch.distributed.init_process_group(backend="nccl")</code> 建立 WORLD 组,再由 <code>initialize_model_parallel</code>(parallel_state.py:2563)切出 TP / ATTN_TP / ATTN_CP / DCP / MOE_EP / MOE_TP / PP 等子组。每个子组同时建一个 NCCL 设备组和一个 <strong>gloo CPU 辅助组</strong>(parallel_state.py:404),后者承担对象广播、barrier 等控制面通信。eager 模式下的大多数通信直接走 <code>torch.distributed.*</code> + 设备组。</li>
    <li><strong>主线二:PyNccl 自研封装</strong>。<span class="filepath">python/sglang/srt/distributed/device_communicators/pynccl_wrapper.py</span> 用 ctypes 直接绑定 <code>libnccl.so.2</code>(ROCm 上为 <code>librccl.so.1</code>,MUSA 上为 <code>libmccl.so.2</code>),<span class="filepath">pynccl.py</span> 在其上实现 <code>PyNcclCommunicator</code>。它存在的第一动机是 <strong>CUDA Graph 捕获兼容</strong>:<code>torch.distributed.all_reduce</code> 内部包含捕获期非法的 CUDA API(见 pynccl_wrapper.py:5-24 的注释);第二动机是把通信提交到<strong>指定 CUDA 流</strong>、复用自管理句柄,以及访问 NCCL 新 API(ncclMemAlloc / ncclCommWindowRegister / ncclConfig_t.CTAPolicy)。</li>
  </ul>
  <div class="stat-grid">
    <div class="stat"><div class="stat-value">183</div><div class="stat-label">python/ 下涉及 nccl 的 .py 文件</div></div>
    <div class="stat"><div class="stat-value">130</div><div class="stat-label">srt/ 内涉及 nccl 的 .py 文件</div></div>
    <div class="stat"><div class="stat-value">21</div><div class="stat-label">device_communicators/ 通信模块</div></div>
    <div class="stat"><div class="stat-value">2.30.7</div><div class="stat-label">主 Dockerfile 锁定的 NCCL 版本</div></div>
  </div>
  <p>两条主线不是二选一,而是<strong>按模式切换</strong>:同一处 <code>GroupCoordinator.all_reduce</code> 调用,eager 下可能走 torch.distributed 或自定义 kernel,进入 CUDA Graph 捕获(<code>graph_capture()</code> 上下文)后由 <code>pynccl_comm.change_state(enable=True)</code> 打开 PyNccl。这个「一调用点、多后端、按图内/图外切换」的设计是理解 SGLang 通信代码的钥匙。</p>
  <div class="callout c-info"><strong>平台矩阵:</strong>NCCL(NVIDIA)/ RCCL(AMD ROCm)/ HCCL(Ascend NPU)/ MCCL(MUSA)在代码里是同一套抽象的不同后端名:PyNccl 按 torch 后缀自动挑 so 文件(pynccl_wrapper.py:56-63),进程组 backend 由 <code>get_default_distributed_backend</code>(parallel_state.py:2385)按平台返回;bootstrap 的预热函数对三者统一处理(<span class="filepath">python/sglang/srt/distributed/bootstrap.py:351</span>)。</div>
</section>

<section>
<h2 class="sec" id="sec-2"><span class="num">2</span>通信栈分层与关键组件</h2>
  <p>自上而下,SGLang 的通信栈可以分为五层,NCCL 相关代码集中在中间三层:</p>
  <div class="flow">
    <div class="node">模型层<small>linear.py / dp_attention.py / moe/</small></div><div class="arrow">→</div>
    <div class="node">通信门面<small>communication_op.py + GroupCoordinator</small></div><div class="arrow">→</div>
    <div class="node node-accent">通信器层<small>pynccl / custom_ar / mscclpp …</small></div><div class="arrow">→</div>
    <div class="node">libnccl.so.2<small>ctypes 直绑</small></div>
  </div>
  <table class="tbl">
    <tr><th>层级</th><th>模块 / 文件</th><th>职责</th></tr>
    <tr><td>初始化引导</td><td><span class="filepath">srt/distributed/bootstrap.py</span></td><td><code>init_parallel_runtime</code>(bootstrap.py:89)解析 backend 与 dist_init_method,建组后执行三类 NCCL 预热</td></tr>
    <tr><td>进程组状态</td><td><span class="filepath">srt/distributed/parallel_state.py</span>(3531 行)</td><td><code>GroupCoordinator</code>(parallel_state.py:254)持有 device_group/cpu_group 与全部通信器;<code>graph_capture</code>(parallel_state.py:2299)统一开关图内通信</td></tr>
    <tr><td>通信门面</td><td><span class="filepath">srt/distributed/communication_op.py</span></td><td><code>tensor_model_parallel_all_reduce</code> 等按语义命名的薄封装,模型代码的主要入口</td></tr>
    <tr><td>NCCL 直绑</td><td><span class="filepath">device_communicators/pynccl.py</span> · <span class="filepath">pynccl_wrapper.py</span> · <span class="filepath">pynccl_allocator.py</span></td><td>PyNccl 通信器、ctypes 符号表、NCCL 对称内存分配器</td></tr>
    <tr><td>替代后端</td><td><span class="filepath">custom_all_reduce(_v2).py</span> · <span class="filepath">quick_all_reduce.py</span> · <span class="filepath">pcie_ipc_ar.py</span> · <span class="filepath">torch_symm_mem.py</span> · <span class="filepath">triton_symm_mem_ag.py</span> · <span class="filepath">pymscclpp.py</span></td><td>IPC/共享内存/对称内存/MSCCL++ 等非 NCCL 快路径(见第 5 节)</td></tr>
    <tr><td>控制面</td><td><span class="filepath">shm_broadcast.py</span> · gloo CPU 组 · <span class="filepath">StatelessProcessGroup</span>(utils.py:154)</td><td>ZMQ/共享内存环缓冲、TCPStore,不占 GPU 通信带宽</td></tr>
  </table>
  <p><code>GroupCoordinator.__init__</code>(parallel_state.py:295-567)是通信器的装配车间,按 world_size&gt;1 依次尝试创建:pynccl_comm(464 行)、pymscclpp_comm(472 行)、pcie_ipc_comm(495 行)、ca_comm/qr_comm(502-530 行)、torch_symm_mem_comm(536 行)、hpu/xpu communicator、mq_broadcaster(565 行)。每个通信器初始化失败都只是降级(打 warning),不会中止启动——这保证了「没有 NVLink 的机器自动回落 NCCL」这类鲁棒性。</p>
</section>

<section>
<h2 class="sec" id="sec-3"><span class="num">3</span>PyNccl 封装代码走读:为什么绕过 torch.distributed</h2>
  <h3>3.1 动机:文件头注释里的三个否决方案</h3>
  <p><span class="filepath">pynccl_wrapper.py</span> 开头(pynccl_wrapper.py:5-24)完整记录了设计动机,这段注释值得逐条翻译:</p>
  <ul>
    <li>试过 <strong>cupy</strong>:调 NCCL 正确,但初始化 communicator 时经常卡死 → 否决;</li>
    <li>试过 <strong>torch.distributed</strong>:<code>all_reduce</code> 内部混入若干 CUDA API,在 CUDA Graph 捕获期间非法(PyTorch 官方论坛有对应 issue)→ 否决;</li>
    <li>考虑过 <strong>C/C++ 扩展绑定</strong>:每次切换 NCCL 版本都要重新编译,而 NCCL 版本兼容性问题高发(NVIDIA/nccl#1234)→ 否决。</li>
  </ul>
  <p>最终方案是纯 Python ctypes 包装:换 NCCL 版本只需改环境变量 <code>SGLANG_NCCL_SO_PATH</code>(pynccl_wrapper.py:48),不触碰编译产物。库查找顺序为:显式 so 路径 → torch 附带的 <code>libnccl.so.2</code>/<code>librccl.so.1</code>/<code>libmccl.so.2</code>。</p>
  <h3>3.2 通信器生命周期</h3>
  <p><code>PyNcclCommunicator.__init__</code>(pynccl.py:31-144)的关键步骤:</p>
  <pre class="code"><code># pynccl.py:54-58 断言挂在非 NCCL 组上(用 gloo CPU 组做 bootstrap)
assert dist.get_backend(group) != dist.Backend.NCCL, \
    "PyNcclCommunicator should be attached to a non-NCCL group."
# pynccl.py:89-105 rank0 生成 ncclUniqueId,经 gloo 组 broadcast 分发
self.unique_id = self.nccl.ncclGetUniqueId()
dist.broadcast(tensor, src=ranks[0], group=group)
# pynccl.py:125-131 对称内存/CTA 策略走 ncclCommInitRankConfig
self.comm = self.nccl.ncclCommInitRankConfig(world_size, unique_id, rank, config)
# pynccl.py:132-139 预热:小 all_reduce 排空冷启动
data = torch.zeros(1, device=device); self.all_reduce(data)
# pynccl.py:141-144 默认 disabled,图捕获时经 change_state(enable=True) 打开
self.disabled = True</code></pre>
  <div class="callout c-tip"><strong>为什么默认 disabled:</strong>PyNccl 只在 CUDA Graph 捕获/重放、对称内存、变长聚合(all_gatherv)等明确需要它的语境下启用。pynccl.py:141 注释写道「默认禁用,例如在 profiling 模型和 prefill 阶段;使用 <code>with obj.change_state(enable=True)</code> 启用,通常在 CUDA graph 中」。这避免了 eager 路径和 torch.distributed 争抢 NCCL channel 资源。</div>
  <h3>3.3 原语实现:流显式传入</h3>
  <p>PyNcclCommunicator 暴露 9 类原语:<code>all_reduce</code>(pynccl.py:150)、<code>outplace_all_reduce</code>(:171)、<code>all_gather</code>(:199,带 <code>sizes</code> 时退化为 ncclGroupStart 包裹的逐 root ncclBroadcast)、<code>reduce_scatter</code>(:243,带 <code>sizes</code> 时为逐 root ncclReduce)、<code>send/recv</code>(:290/:307)、<code>all_to_all_single</code>(:324,ncclGroupStart + 等分 ncclSend/ncclRecv 融合,图内可捕获)、<code>broadcast</code>(:378)、<code>group_start/group_end</code>、以及对称内存窗口注册接口 <code>register_comm_window_raw</code>(:404)。所有调用都遵循同一模式:</p>
  <pre class="code"><code># pynccl.py:160-169 流由 _resolve_stream() 取当前设备流,显式传给 NCCL
stream = self._resolve_stream()
self.nccl.ncclAllReduce(
    buffer_type(tensor.data_ptr()), buffer_type(tensor.data_ptr()),
    tensor.numel(), ncclDataTypeEnum.from_torch(tensor.dtype),
    ncclRedOpTypeEnum.from_torch(op), self.comm,
    cudaStream_t(stream.cuda_stream))   # ← 捕获期安全的关键</code></pre>
  <p>这正是图捕获兼容性的来源:不产生隐式同步、不查 stream、不分配资源,只是往指定流上排 kernel。<code>all_to_all_single</code> 的 docstring 明确写着「CUDA-graph-capturable(用于 DCP a2a 通信后端)」(pynccl.py:332-333)。</p>
  <div class="flow-v">
    <div class="node">GroupCoordinator.all_reduce / all_gather / reduce_scatter</div><div class="arrow-v">↓</div>
    <div class="node">get_available_pynccl_comm() + change_state(enable=True)</div><div class="arrow-v">↓</div>
    <div class="node node-accent">PyNcclCommunicator.all_reduce 等<small>取当前流 → 构造 ctypes 参数</small></div><div class="arrow-v">↓</div>
    <div class="node">NCCLLibrary.ncclAllReduce<small>NCCL_CHECK 校验返回值</small></div><div class="arrow-v">↓</div>
    <div class="node">libnccl.so.2 的 ncclAllReduce C 符号</div>
  </div>
  <h3>3.4 pynccl_allocator:cuMem 分配与 NCCL 窗口注册</h3>
  <p><span class="filepath">device_communicators/pynccl_allocator.py</span> 解决的是 NCCL 2.27+ 的<strong>对称内存(symmetric memory)</strong>要求:buffer 必须由 <code>ncclMemAlloc</code> 分配并经 <code>ncclCommWindowRegister</code> 注册为对称窗口,NCCL 才能走免拷贝的 NVLS/多播快路径。实现分两半:</p>
  <ul>
    <li><code>allocate_symmetric_buffer</code>(pynccl_allocator.py:55):ncclMemAlloc → 注册窗口 → 用 <code>__cuda_array_interface__</code> 包装成 torch 张量,weakref.finalize 保证最后一个视图释放时 deregister + ncclMemFree。NCCL ≥ 2.29.2 无对称支持时窗口返回 NULL(:72-75)。</li>
    <li><code>get_nccl_mem_pool</code>(pynccl_allocator.py:259)把 ncclMemAlloc 做成 <strong>torch CUDAPluggableAllocator</strong>:内联 C++ 源码(nccl_allocator_source,:107-222)实现 alloc/free 插桩与按 communicator 的增量段注册;<code>SymmetricMemoryContext</code>(:326)进入时把当前线程分配绑定到该池(图捕获时还会临时暂停 graph pool,:360-374),退出时调用 <code>nccl_allocator_register_segments_with_comm</code> 批量注册。所有组共享一个池以避免碎片(:259-265)。</li>
  </ul>
  <p>上层入口是 <code>use_symmetric_memory(group)</code>(pynccl_allocator.py:423),被 <code>RowParallelLinear.forward</code>(linear.py:1779-1784)、<code>reduce_scatter_along_dim</code>(parallel_state.py:1114)、dp_attention 的全局缓冲(dp_attention.py:292-316)等用 <code>with</code> 包住通信输入/输出张量的分配。启用后 PyNccl 的 all_reduce 走对称内存路径(parallel_state.py:771-780),并以 <code>config.graphUsageMode=1</code> 关闭 NCCL 内部 CUDA event 同步换取性能(pynccl.py:117-122,对应 PR #27089)。</p>
  <h3>3.5 何时用 PyNccl、何时用 torch 进程组</h3>
  <table class="tbl">
    <tr><th>维度</th><th>torch.distributed(NCCL backend)</th><th>PyNccl(ctypes)</th></tr>
    <tr><td>CUDA Graph 捕获</td><td>不可用(parallel_state.py:659 注释矩阵中 Graph 列为 disabled)</td><td>可用,专为捕获设计</td></tr>
    <tr><td>eager 模式</td><td>默认路径(<code>_all_reduce_in_place</code> 兜底,parallel_state.py:1097)</td><td>默认 disabled;对称内存/变长 all_gatherv 场景强制启用</td></tr>
    <tr><td>NCCL 新 API</td><td>受 torch 版本约束</td><td>直接绑定:ncclCommWindowRegister、ncclMemAlloc、ncclConfig_t(CTAPolicy/graphUsageMode)</td></tr>
    <tr><td>对象/控制面</td><td>gloo CPU 组广播 pyobj</td><td>不支持(纯 device 端)</td></tr>
    <tr><td>依赖面</td><td>随 torch 发布,零额外成本</td><td>需要 libnccl 可被 ctypes 找到;NPU/XPU/mooncake 后端禁用(parallel_state.py:2194-2199)</td></tr>
  </table>
</section>

<section>
<h2 class="sec" id="sec-4"><span class="num">4</span>逐场景枚举:NCCL 到底用在哪里</h2>
  <h3>4.1 场景一:TP 线性层的 allreduce / reduce-scatter</h3>
  <p><strong>触发条件:</strong><code>tp_size &gt; 1</code> 且线性层声明 <code>reduce_results=True</code>(RowParallelLinear,如 o_proj、down_proj)。</p>
  <p><strong>调用链:</strong><span class="filepath">srt/layers/linear.py:1803-1824</span> → <code>get_parallel().tp_group.all_reduce()</code> 或 <code>attn_tp_group.all_reduce()</code>(DP attention 下)→ <code>GroupCoordinator.all_reduce</code>(parallel_state.py:689)。</p>
  <pre class="code"><code># linear.py:1803-1824(节选)
if ((self.reduce_results and tp_size &gt; 1) or self.use_decode_attn_tp) \
        and not skip_all_reduce and not should_skip_mlp_all_reduce():
    if self.use_dp_attention_reduce:
        output = get_parallel().attn_tp_group.all_reduce(output_parallel)
    ...
    elif self.parallel_group == "tp":
        output = get_parallel().tp_group.all_reduce(output_parallel)
    else:
        output = tensor_model_parallel_all_reduce(output_parallel)</code></pre>
  <p><strong>通信原语:</strong>allreduce(SUM)。注意 Column-parallel(q_proj/k_proj/up_proj)本身不通信,只有行切分的输出需要归约;输入的切分由 <code>split_tensor_along_last_dim</code> 本地完成。<strong>编译模式</strong>下(含 piecewise CUDA Graph),all_reduce 改走注册的 custom op <code>outplace_all_reduce</code>,把方法选择推迟到运行时以避免按符号形状反复重编译(parallel_state.py:733-760)。</p>
  <p><strong>序列并行(SP)变体:</strong>开启 layernorm SP 时,RowParallelLinear 走 <code>layernorm_sp.row_parallel_gbar_matmul</code>(linear.py:1768-1776)做 reduce-scatter;MLP 边界由 <code>--boundary-reduction</code>(auto/ar/rs/rsv,fields/exec_.py:755-767)选择 allreduce 或 reduce-scatter/rsv 变长归约。VocabParallelEmbedding 的输入侧则在 attn-TP 组内 allreduce(vocab_parallel_embedding.py:530-533)。</p>
  <h3>4.2 场景二:DP Attention 的跨 rank gather/scatter</h3>
  <p><strong>触发条件:</strong><code>--enable-dp-attention</code>(attn_dp_size&gt;1),attention 按 DP 复制、MoE/MLP 在全局 TP 组内跑。</p>
  <p><strong>调用链与原语:</strong><span class="filepath">srt/layers/dp_attention.py</span> 的 <code>_dp_gather</code> 有两种实现,按 padding 模式选择(dp_attention.py:153-221):</p>
  <ul>
    <li><code>_dp_gather_via_all_reduce</code>(dp_attention.py:661):每 rank 把局部 token 写进零初始化全局缓冲的自己的槽,再 SUM allreduce。world 组启用时直接 <code>torch.distributed.all_reduce(group=WORLD)</code>(:694);<strong>整数行(input_ids 等)强制走 in-place NCCL 路径</strong>,因为自定义 allreduce kernel 只支持浮点(:699-706);浮点走 <code>tensor_model_parallel_all_reduce</code> 兜底自定义 kernel。</li>
    <li><code>_dp_gather_via_all_gather</code>(dp_attention.py:711):MAX_LEN padding 下 all_gather 拼接;attn_tp&gt;1 时先在 attn-TP 组 <code>reduce_scatter_tensor</code> 归零多余副本再 gather(:736-748)。</li>
  </ul>
  <p>反向 <code>dp_scatter</code>(dp_attention.py:1075)是纯本地 memcpy,不通信;<code>dp_reduce_scatter_tensor</code>(dp_attention.py:1115)在 combine 侧做 reduce-scatter 或 allreduce+narrow。变长优化 <code>SGLANG_DP_USE_GATHERV</code> 走 <code>all_gatherv</code>/<code>reduce_scatterv</code>(pynccl 逐 root broadcast/reduce 实现)。</p>
  <h3>4.3 场景三:词表并行 lm_head 的 gather</h3>
  <p><strong>触发条件:</strong>TP 切分词表(lm_head 按行切),每 rank 持有部分 vocab 的 logits。</p>
  <p><strong>实现分层</strong>(按优先级):</p>
  <ul>
    <li><code>LogitsProcessor._logits_gatherer</code> 是 <code>MultimemAllGatherer</code>(<span class="filepath">device_communicators/triton_symm_mem_ag.py:449</span>):bf16、二维、对齐、行数不超过预算且拿到 multicast 指针时走 Triton <code>multimem.st</code> 多播 all-gather,<strong>否则回落 <code>tensor_model_parallel_all_gather</code>(即 PyNccl/NCCL 环)</strong>(triton_symm_mem_ag.py:495-521)。跨节点 TP 组会被探测并禁用(:484-493)。</li>
    <li><span class="filepath">device_communicators/vocab_gather.py</span> 的 <code>NcclVocabGather</code>(vocab_gather.py:41)是 <code>group.all_gather(dim=-1)</code> 的薄包装,同时充当 <code>NVLinkVocabGather</code>(走 CustomAllReduceV2 多播平面)的 <strong>fallback</strong>;由 <code>make_vocab_gather</code>(vocab_gather.py:198)按组拓扑选择,目前主要被 DSpark 投机采样模型使用(models/dspark.py:229、deepseek_v4_dspark.py:484)。</li>
    <li>TP lm-head all-to-all(<code>--enable-tp-lm-head-all-to-all</code>):<code>_tp_lm_head_all_to_all</code>(logits_processor.py:1368)调用 <code>tp_group.all_to_all_single</code> → <code>GroupCoordinator._all_to_all_single</code>(parallel_state.py:1223)<strong>强制 PyNccl</strong>(pynccl 可捕获),否则 torch.distributed 兜底。每 rank 只交换目标 DP rank 拥有的行块,把 all-gather 的 O(W·V) 降为 O(V)。bootstrap 会专门预热这条 P2P 路径(bootstrap.py:406-437),因为 CUDA Graph 捕获依赖 PyNCCL 的持久传输资源。</li>
  </ul>
  <h3>4.4 场景四:MoE / EP 的 token 分发</h3>
  <p><strong>触发条件:</strong>MoE 模型 + <code>--moe-a2a-backend</code> 选择(fields/exec_.py:843-876,共 12 个枚举值)。</p>
  <ul>
    <li><code>none</code>(默认,StandardDispatcher):不做 a2a。DP attention 组合下用 <code>tp_group.all_gatherv</code>(token_dispatcher/standard.py:169/208,PyNccl 逐 root broadcast)收集各 DP rank 的 topk 权重/hidden states,combine 时 <code>reduce_scatterv</code>(standard.py:295,PyNccl 逐 root reduce)归还。这两个 v-变体 <strong>require_pynccl_comm</strong>(parallel_state.py:1459/1284),是少数 eager 下也强制 PyNccl 的路径。</li>
    <li><code>deepep / deepep_v2</code>:DeepEP 库自建 NVSHMEM/RDMA 传输,<strong>不经 NCCL</strong>;但 deepep_v2 的 ElasticBuffer 需要 cuMem,故 SGLang 为其 setdefault <code>NCCL_CUMEM_ENABLE=1</code>(token_dispatcher/deepep_v2.py:191 及 arg_groups/moe_hook.py:457),并默认关闭 <code>EP_REUSE_NCCL_COMM</code> 避免 DeepEP 与 NCCL 抢 communicator。</li>
    <li><code>mooncake / nixl / mori / megamoe / flashinfer*</code>:各自专有传输(mooncake 传输引擎、NIXL、MNNVL 等),同样绕开 NCCL;<code>mooncake</code> 甚至是把 torch.distributed 的 backend 整体换成 <code>"mooncake"</code>(parallel_state.py:339-387,bootstrap.py:226-228),此时 <code>use_pynccl=False</code>。</li>
    <li><code>pplx</code>:为 NVSHMEM rendezvous 额外注册一个 <code>"cpu:gloo,cuda:nccl"</code> 混合进程组(token_dispatcher/pplx.py:111)——NCCL 在这里只做辅助控制面。</li>
    <li><strong>DCP a2a</strong>(decode context parallel,<span class="filepath">srt/layers/dcp/comm.py</span>):KV 分片跨 CP rank 交换用 <code>cp_group.all_to_all_single</code>(comm.py:144/545)——PyNccl 的 ncclGroupStart+Send/Recv 实现;fp8 KV 以字节搬运,因为「pynccl 的 dtype 枚举没有 fp8」(comm.py:169 注释)。</li>
  </ul>
  <div class="callout c-warn"><strong>选择逻辑总结:</strong>单机小规模 EP 用 standard(纯 NCCL 集合);大规模/多机 EP 用 DeepEP 等专有 a2a(NVSHMEM/RDMA,低延迟 P2P);NCCL 在 MoE 里主要承担 <em>DP 收拢/归还</em>(all_gatherv/reduce_scatterv)与 EPLB 专家统计(allreduce),而非 token 路由本身。</div>
  <h3>4.5 场景五:采样与 logits 的跨 rank 同步</h3>
  <ul>
    <li><strong>采样 token 一致性:</strong><code>Sampler._sync_token_ids_across_tp</code>(<span class="filepath">srt/layers/sampler.py:718-732</span>)默认关闭以省一次 allreduce;开启条件为 <code>SYNC_TOKEN_IDS_ACROSS_TP</code> 或带 grammar 约束(xgrammar 下各 rank 容易失步)。用 <code>torch.distributed.all_reduce(op=MIN, group=tp_sync_group)</code>——直接 torch.distributed,因为采样在图外/重放后由 CPU 侧消费。tp_sync_group 是 attn-TP 的 device_group(sampler.py:122-128)。</li>
    <li><strong>mask 采样状态同步:</strong>sampling mask 输出的 statuses 用 <code>dist.all_reduce(op=MAX)</code> 跨 TP/CP 组取最坏值,保证「所有副本对同一请求做出相同的 abort 决定」(sampler.py:596-608)。</li>
    <li><strong>EPLB 专家分布:</strong><code>ExpertDistributionRecorder.dump</code> 用 <code>torch.distributed.all_reduce(SUM)</code>(默认 WORLD 组)聚合各 rank 的专家命中计数(eplb/expert_distribution.py:997);bootstrap 里还有 EPLB 专用的 P2P 批量 warmup(bootstrap.py:369-403)。</li>
  </ul>
  <h3>4.6 场景六:初始化与多机 bootstrap</h3>
  <p><strong>调用链:</strong><span class="filepath">srt/distributed/bootstrap.py:89</span> <code>init_parallel_runtime</code> → <code>_resolve_backend</code>(CUDA→"nccl",:224-228)→ <code>_resolve_dist_init_method</code>(tcp://host:port,支持 <code>SGLANG_DISTRIBUTED_INIT_METHOD_OVERRIDE</code> 与 dist_init_addr)→ <code>init_distributed_environment</code>(torch.distributed.init_process_group,backend="nccl",parallel_state.py:2514)→ <code>initialize_model_parallel</code> 切子组 → <code>initialize_dp_attention</code>。</p>
  <p>多机要点:(1)每个子组同时创建 gloo CPU 组做 bootstrap 与对象面(parallel_state.py:402-410);(2)PyNccl 的 ncclUniqueId 也经该 gloo 组广播(pynccl.py:96-105);(3)moe_a2a_backend=nixl 时额外建全局 TCPStore(parallel_state.py:2396-2462);(4)弹性 EP 的 joiner 用 <code>use_local_synchronization</code> 局部建组、rank_offset 偏移进全局 rank 空间(parallel_state.py:320-337,bootstrap.py:302-338)。(5)三类预热:<code>_prewarm_nccl</code>(bootstrap.py:351,一次小 allreduce 排空 communicator 建立,--pre-warm-nccl)、<code>_prewarm_eplb_p2p</code>(:369,batch_isend_irecv + allreduce)、<code>_prewarm_tp_lm_head_all_to_all</code>(:406,显式 <code>change_state(enable=True)</code> 打开 PyNccl 做 a2a 预热,把持久传输资源计入 KV cache 估算前的显存基线)。</p>
  <h3>4.7 场景七:CUDA Graph 捕获期通信</h3>
  <p><strong>定义:</strong>模块级 <code>graph_capture(stream=None)</code>(parallel_state.py:2299-2323)嵌套进入 TP 组、PP 组以及 _DCP/_ATTN_TP/_SHARED_EXPERTS_TP/_MOE_EP/_MOE_TP 各组的 <code>GroupCoordinator.graph_capture</code>(parallel_state.py:626-687)。后者:(1)切换到捕获流;(2)进入 ca_comm.capture()(自定义 AR 的图内注册);(3)<strong>对所有可用 PyNccl/MSCCL++ 通信器执行 change_state(enable=True)</strong>。源码注释里有一张权威的模式矩阵(parallel_state.py:650-659):</p>
  <table class="tbl">
    <tr><th>allreduce 实现</th><th>Eager</th><th>Graph</th></tr>
    <tr><td>quick allreduce(ROCm)</td><td>enabled</td><td>enabled</td></tr>
    <tr><td>custom allreduce</td><td>enabled</td><td>enabled</td></tr>
    <tr><td>PyNccl</td><td>disabled</td><td><strong>enabled</strong></td></tr>
    <tr><td>PyMscclpp</td><td>disabled</td><td>enabled(需预注册张量)</td></tr>
    <tr><td>TorchSymmMem</td><td>disabled</td><td>enabled</td></tr>
    <tr><td>torch.distributed</td><td>enabled</td><td>disabled</td></tr>
  </table>
  <p><strong>使用者:</strong>decode 图(<span class="filepath">srt/model_executor/runner/decode_cuda_graph_runner.py:1326</span>)、prefill 图(prefill_cuda_graph_runner.py:1720)、row bucket 图(row_bucket_graph_runner.py:301)、EAGLE target-verify 图(speculative/eagle_post_verify_graphs.py:384)、DSpark 采样接受图(speculative/dspark_components/dspark_sampling_accept_graph.py:230-232,注释直言「graph_capture() enables pynccl, which the in-graph accept broadcast needs」——图内跨 TP 广播接受结果必须走 PyNccl)。MiniMax 索引 CP 的 warmup 也同时预热 torch.distributed 与 PyNccl 两条 all-gather 路径(attention/minimax_sparse_ops/indexer_cp.py:124-135)。</p>
  <h3>4.8 场景八:KV cache 分片与注意力辅助通信</h3>
  <ul>
    <li><strong>Page-interleave KV 分片 gather:</strong><span class="filepath">srt/mem_cache/page_interleave_pool.py:217</span> 为 KV shard 组创建<strong>专用 PyNcclCommunicator + 专用 CUDA 流</strong>,避免与主组集合通信交错;启用对称 scratch 时以 <code>NCCL_CTA_POLICY_ZERO</code>(pynccl_wrapper.py:92,2.30 新 config 字段)请求「零 SM、纯 copy engine」的收集(0SM KV allgather,PR #44029),scratch 由 <code>allocate_symmetric_buffer</code> 注册为对称窗口。入口环境变量 <code>SGLANG_ENABLE_KV_SHARD_ZERO_SM_GATHER</code>(默认 True,environ.py:646)。</li>
    <li><strong>DSA 层分片广播:</strong><span class="filepath">srt/mem_cache/dsa_cache_layer_split.py:262</span> 为 CP 组建独立的 layer_broadcast_comm,非 owner rank 用 <code>comm.broadcast(tensor, src=owner_rank)</code> 拉取层 KV(:288-300,注意必须 change_state 否则「静默 no-op 读到陈旧远程缓冲」);<code>srt/layers/attention/dsa/dsa_indexer.py:209-216</code> 同样用 pynccl broadcast 同步 topk_indices。</li>
    <li><strong>hisparse / engram:</strong>协调器用 <code>torch.distributed.all_reduce</code>(managers/hisparse_coordinator.py:1076)做稀疏注意力元数据同步;engram 记忆层用 <code>torch.distributed.all_to_all_single</code> / <code>group.all_to_all_single</code>(layers/engram.py:1320-1329)交换哈希桶。</li>
  </ul>
  <h3>4.9 场景九:通信量优化路径(仍落在 NCCL 上)</h3>
  <ul>
    <li><strong>DP gather fp8 量化:</strong><code>SGLANG_ENABLE_DP_GATHER_FP8</code>(dp_attention.py:763)把 DP gather 的 hidden states 量化成 fp8 再通信,「halves the gathered hidden-state bytes over NCCL」;combine 侧保持 bf16,因为 NCCL SUM 不支持 fp8(environ.py:1028-1029)。</li>
    <li><strong>TP 通信 INT8 量化:</strong><code>--enable-quant-communications</code>(fields/exec_.py:768)走 <code>tensor_model_parallel_quant_all_reduce</code>(communication_op.py:26),仅 NPU 等有限支持。</li>
    <li><strong>重叠调度同步:</strong>overlap scheduler 的 batch 同步可选走 NCCL all-gather(<code>SGLANG_NCCL_ALL_GATHER_IN_OVERLAP_SCHEDULER_SYNC_BATCH</code>,environ.py:754;managers/scheduler_components/dp_attn.py:609、prefill_delayer.py:115)。</li>
  </ul>
</section>

<section>
<h2 class="sec" id="sec-5"><span class="num">5</span>非 NCCL 通信路径与后端选择决策</h2>
  <p>SGLang 在 NCCL 之外维护了一整套「按消息大小/拓扑/是否图内」的快路径,全部注册在 GroupCoordinator 上参与同一个分发函数的竞选。allreduce 的竞选顺序见 <code>_resolve_outplace_all_reduce_method</code>(parallel_state.py:966-1013):<strong>ca(custom AR)→ pcie_ipc → qr(quick reduce)→ pymscclpp → torch_symm_mem → pynccl(piecewise 图)→ None(回落 in-place:PyNccl→TorchSymmMem→torch.distributed)</strong>。</p>
  <div class="flow-v">
    <div class="node">GroupCoordinator.all_reduce(input)</div><div class="arrow-v">↓</div>
    <div class="node">world_size==1? → 直接返回;CPU 张量 → shm_allreduce / gloo</div><div class="arrow-v">↓</div>
    <div class="node">torch.compile 中? → flashinfer_allreduce / outplace custom op(method="auto")</div><div class="arrow-v">↓</div>
    <div class="node">对称内存启用且无更快后端? → PyNccl all_reduce(对称窗口)</div><div class="arrow-v">↓</div>
    <div class="node node-accent">_resolve_outplace_all_reduce_method<small>ca → pcie_ipc → qr → mscclpp → symm_mem → pynccl(仅 piecewise 图)</small></div><div class="arrow-v">↓</div>
    <div class="node">命中 → 对应 outplace kernel;否则 in-place:PyNccl → TorchSymmMem → torch.distributed.all_reduce(NCCL 兜底)</div>
  </div>
  <table class="tbl">
    <tr><th>后端</th><th>机制</th><th>典型阈值/条件</th><th>图内?</th><th>开关</th><th>关键文件</th></tr>
    <tr><td>CustomAllreduce</td><td>NCCL 之外的 IPC + 一次性 kernel(1shot/2shot)</td><td>world_size ∈ {2,4,6,8};fp32/fp16/bf16;≤8MiB(ROCm 16MiB、MUSA 128MiB)</td><td>是</td><td>默认开;<code>--disable-custom-all-reduce</code></td><td>custom_all_reduce.py:40-50</td></tr>
    <tr><td>CustomAllReduceV2</td><td>多播平面 push/pull 对称内存(3.x 新)</td><td>SM90+,多播可用;方向无关 max_size</td><td>是</td><td>自动 dispatch(custom_all_reduce.py:377)</td><td>custom_all_reduce_v2.py:113</td></tr>
    <tr><td>QuickAllReduce</td><td>quickreduce(ROCm gfx942+)</td><td>16B 对齐、≥_QR_MIN_SIZE、≤2GB(可配)</td><td>是(静态 IPC buffer)</td><td>仅 HIP</td><td>quick_all_reduce.py:52,223</td></tr>
    <tr><td>PcieIpcCommunicator</td><td>FlashInfer PCIe-IPC kernel</td><td>仅 "tp" 组、bf16、≤工作区上限;无 NVLink  fabric 后端的主机</td><td>是</td><td><code>SGLANG_ENABLE_PCIE_IPC_ALLREDUCE</code>(默认 False)</td><td>pcie_ipc_ar.py:98,387</td></tr>
    <tr><td>TorchSymmMemCommunicator</td><td>torch 对称内存 multimem allreduce</td><td>SM90:ws∈{4,6,8}≤64-128MiB;SM100 同;bf16</td><td>是</td><td><code>--enable-torch-symm-mem</code></td><td>torch_symm_mem.py:34;all_reduce_utils.py:3</td></tr>
    <tr><td>PyMscclppCommunicator</td><td>MSCCL++(调优算法表)</td><td>按消息大小的 tuned config;piecewise 图各阶段禁用</td><td>是(需预注册)</td><td><code>--enable-mscclpp</code></td><td>pymscclpp.py:552,1139</td></tr>
    <tr><td>FlashInfer AR fusion</td><td>trtllm/mnnvl/cutedsl 融合 AR+RMSNorm(+MoE finalize)</td><td>SM90/SM10X;工作区按组打标(_fi_workspace_hint)</td><td>是</td><td><code>--flashinfer-allreduce-fusion-backend</code></td><td>parallel_state.py:2354-2381</td></tr>
    <tr><td>Aiter AR/AG/RS fusion</td><td>ROCm aiter 融合 kernel</td><td>HIP + 形状/16B 对齐检查</td><td>是(reg/unreg 两态)</td><td><code>--enable-aiter-allreduce-fusion</code>、<code>SGLANG_USE_AITER_AG</code>、<code>SGLANG_DP_USE_REDUCE_SCATTER</code></td><td>parallel_state.py:1182-1340</td></tr>
    <tr><td>MultimemAllGatherer</td><td>Triton multimem.st all-gather</td><td>bf16、单机 TP、≤max_tokens</td><td>是</td><td>自动(失败回落 NCCL)</td><td>triton_symm_mem_ag.py:449</td></tr>
    <tr><td>ShmRingBuffer / MessageQueue</td><td>/dev/shm 环缓冲(ZMQ XPUB/SUB 控制面)</td><td>控制面小对象广播</td><td>不适用</td><td>elastic EP 自动建</td><td>shm_broadcast.py:33,174</td></tr>
    <tr><td>NCCL(PyNccl / torch.distributed)</td><td>环/树/NVLS 集合通信</td><td><strong>一切不满足上述快路径条件的兜底</strong>;大消息、跨节点、整数 dtype、fp8 KV 字节搬运</td><td>仅 PyNccl</td><td>默认</td><td>pynccl.py;parallel_state.py</td></tr>
  </table>
  <div class="callout c-tip"><strong>决策表速读:</strong>消息小 + NVLink 全互联 + 浮点 → custom AR(v2)/quick reduce;PCIe 主机 + bf16 + tp 组 → pcie_ipc;需要融合(norm/quant)→ FlashInfer/Aiter fusion;对称内存可用 → PyNccl 对称窗口;其余(大消息、跨节点、非浮点、无开关)→ NCCL。所有快路径都带「不支持就返回 False」的 should_* 谓词,失败静默回落 NCCL,这就是 NCCL 作为兜底的工程意义。</div>
</section>

<section>
<h2 class="sec" id="sec-6"><span class="num">6</span>NCCL 相关环境变量与配置项</h2>
  <h3>6.1 SGLang 主动设置/读取的 NCCL 环境变量</h3>
  <table class="tbl">
    <tr><th>变量</th><th>设置位置</th><th>作用</th></tr>
    <tr><td>NCCL_CUMEM_ENABLE</td><td>entrypoints/engine.py:1925(GB200/300 多节点默认 1)、:1938-1947(enable_symm_mem 或 KV-shard 对称 scratch 时强制 1);arg_groups/moe_hook.py:457(deepep_v2)</td><td>NCCL 用 cuMem 分配内部缓冲;对称内存(ncclMemAlloc)与 MNNVL 的前置条件</td></tr>
    <tr><td>NCCL_MNNVL_ENABLE</td><td>engine.py:1926</td><td>GB200/GB300 跨节点 NVLink(MNNVL fabric)传输,多节点 fabric 机器默认开</td></tr>
    <tr><td>NCCL_NVLS_ENABLE</td><td>engine.py:1948-1955;<code>--enable-nccl-nvls</code> / <code>--enable-symm-mem</code> 联动</td><td>NVLS(NVLink SHARP)多播 allreduce,预填充重请求可受益</td></tr>
    <tr><td>NCCL_GRAPH_MIXING_SUPPORT</td><td>engine.py:1956-1960</td><td>dcp_size&gt;1 时设 0:图内静态通信与图外动态通信不混流,对称 kernel 性能更稳(nccl-tests#333 讨论)</td></tr>
    <tr><td>NCCL_GRAPH_REGISTER</td><td>arg_groups/parallel_hook.py:405-431</td><td>默认 setdefault 0:图注册的 send/recv 缓冲在 graph-pool 地址复用与 memory-saver resume 下会悬挂(TP lm-head a2a 实测 tp4/dp4/ep4 与多节点 tp16 复现)</td></tr>
    <tr><td>NCCL_ALGO</td><td>arg_groups/attention_hook.py:685</td><td>确定性推理设 <code>allreduce:tree</code>,固定归约顺序保证可复现</td></tr>
    <tr><td>NCCL_MIN/MAX_NCHANNELS</td><td>attention_hook.py:705-707;docker/rocm.Dockerfile:1271(MI300 系设 112)</td><td>钉死 channel 数,避免消息大小改变归约顺序(确定性);ROCm 上是 RCCL 带宽调优</td></tr>
    <tr><td>EP_REUSE_NCCL_COMM</td><td>token_dispatcher/deepep_v2.py:191</td><td>默认 0,禁止 DeepEP 复用 NCCL communicator</td></tr>
    <tr><td>SGLANG_NCCL_SO_PATH</td><td>pynccl_wrapper.py:48-53</td><td>指定 PyNccl 加载的 libnccl/librccl so 路径(版本切换)</td></tr>
    <tr><td>SGLANG_NCCL_ALL_GATHER_IN_OVERLAP_SCHEDULER_SYNC_BATCH</td><td>environ.py:754</td><td>overlap scheduler 的批同步改走 NCCL all-gather</td></tr>
    <tr><td>SGLANG_DETERMINISTIC_NCCL_NCHANNELS</td><td>environ.py:1597</td><td>确定性推理钉 channel 数的取值(默认 8)</td></tr>
    <tr><td>NCCL_IB_HCA / NCCL_SOCKET_IFNAME / NCCL_IB_DISABLE</td><td>scripts/ci/slurm/launch_mi355x.sh:407-469 等</td><td>部署脚本里指定网卡/RDMA HCA,避免 ncclCommInitRank 网络错误</td></tr>
  </table>
  <h3>6.2 影响 NCCL 路径选择的 ServerArgs / exec.comm 配置</h3>
  <table class="tbl">
    <tr><th>参数(exec.comm 命名空间)</th><th>默认值</th><th>说明</th></tr>
    <tr><td>enable_symm_mem</td><td>False</td><td>NCCL 对称内存快路径(ncclMemAlloc + 窗口注册),联动 CUMEM/NVLS 环境变量(fields/exec_.py:725)</td></tr>
    <tr><td>disable_custom_all_reduce</td><td>False</td><td>关闭自定义 AR,回落 NCCL(fields/exec_.py:732)</td></tr>
    <tr><td>enable_mscclpp</td><td>False</td><td>MSCCL++ 调优消息,NCCL 兜底(fields/exec_.py:739)</td></tr>
    <tr><td>enable_torch_symm_mem</td><td>False</td><td>torch 对称内存 AR;仅 SM90(ws 4/6/8)/SM100(ws 6/8)(fields/exec_.py:743)</td></tr>
    <tr><td>enable_nccl_nvls</td><td>False</td><td>预填充重请求开启 NCCL NVLS(fields/exec_.py:722)</td></tr>
    <tr><td>pre_warm_nccl</td><td>False</td><td>启动期预热 NCCL/RCCL/HCCL,降 P99 TTFT 冷启动;仅 CUDA/HIP/NPU 生效(fields/exec_.py:751;platform_hook.py:70)</td></tr>
    <tr><td>enable_quant_communications</td><td>False</td><td>TP 通信 INT8 量化(有限支持,fields/exec_.py:768)</td></tr>
    <tr><td>boundary_reduction</td><td>"auto"</td><td>FFN 边界归约选择 ar/rs/rsv(fields/exec_.py:755)</td></tr>
    <tr><td>flashinfer_allreduce_fusion_backend</td><td>None</td><td>auto/trtllm/mnnvl/cutedsl 融合 AR(fields/exec_.py:777)</td></tr>
    <tr><td>moe_a2a_backend(exec.moe)</td><td>"none"</td><td>MoE a2a 后端,12 选(fields/exec_.py:843)</td></tr>
  </table>
  <p>另有影响对称内存行为的 <code>SGLANG_SYMM_MEM_PREALLOC_GB_SIZE</code>(默认 -1,即不预分配;pynccl_allocator.py:508-535 会在启用时预占大块以抗碎片)与 <code>SGLANG_DEBUG_SYMM_MEM</code>(校验通信张量确实落在对称池,environ.py:2283)。</p>
</section>

<section>
<h2 class="sec" id="sec-7"><span class="num">7</span>部署侧:Dockerfile 与脚本中的 NCCL</h2>
  <ul>
    <li><strong>主 Dockerfile</strong>(<span class="filepath">docker/Dockerfile</span>):<code>ARG SGL_NCCL_VERSION=2.30.7</code>(Dockerfile:16)。注释说明改名原因:nvidia/cuda 基础镜像自带 <code>ENV NCCL_VERSION</code>(Debian 格式如 2.28.3-1)会遮蔽同名 ARG(Dockerfile:395-397)。安装方式是 uv 解依赖后 <code>uv pip install --reinstall --no-deps "nvidia-nccl-cu13==${SGL_NCCL_VERSION}"</code>,因为 DeepEP 运行时需要新 NCCL 而 torch 会 pin 旧版(Dockerfile:508-512)。运行镜像还装 <code>libnccl2 / libnccl-dev</code>,供 <strong>pynccl_allocator 的 JIT 编译链接 -lnccl</strong>(Dockerfile:739-741)——这是 PyNccl 对称内存分配器与部署侧的直接耦合点。</li>
    <li><strong>DeepEP 专用镜像</strong>:sgl-deep-ep.Dockerfile 用 NCCL 2.30.7,sgl-deep-ep-v25.Dockerfile 升到 2.32.3("PyTorch pins an older nvidia-nccl-cu13, so install the NCCL that DeepEP 2.5 needs over it")。</li>
    <li><strong>ROCm</strong>:rocm.Dockerfile 在构建期用 ctypes 断言只加载一份 librccl(Dockerfile:1141),并设 <code>NCCL_MIN_NCHANNELS=112</code>(MI300 调优,:1271)。</li>
    <li><strong>AWS EFA</strong>:efa.Dockerfile 装 aws-ofi-nccl 插件,供 <code>NCCL_NET_PLUGIN=ofi</code>/<code>NCCL_TUNER_PLUGIN=ofi</code> 解析。</li>
    <li><strong>K8s 示例</strong>:k8s-sglang-distributed-sts.yaml 设 <code>NCCL_DEBUG</code> 便于排障;scripts/ci/slurm/launch_mi355x.sh 集中管理 NCCL_IB_HCA/NCCL_SOCKET_IFNAME/NCCL_IB_DISABLE 等网络面变量。</li>
  </ul>
</section>

<section>
<h2 class="sec" id="sec-8"><span class="num">8</span>NCCL 使用场景矩阵(大汇总)</h2>
  <table class="tbl">
    <tr><th>场景</th><th>通信原语</th><th>通信器</th><th>触发条件</th><th>关键文件</th></tr>
    <tr><td>TP 行并行输出归约</td><td>allreduce(SUM)</td><td>custom AR 系列 → symm_mem → PyNccl → torch.distributed</td><td>tp_size&gt;1 且 reduce_results</td><td>linear.py:1803;parallel_state.py:689</td></tr>
    <tr><td>TP 序列并行边界</td><td>reduce-scatter / all-gather / rsv</td><td>PyNccl(sizes 逐 root reduce)/ aiter(ROCm)</td><td>layernorm SP / --boundary-reduction</td><td>parallel_state.py:1136-1303</td></tr>
    <tr><td>Embedding 输出归约</td><td>allreduce</td><td>attn-TP 组,同上分发</td><td>词表并行 embedding</td><td>vocab_parallel_embedding.py:530</td></tr>
    <tr><td>lm_head logits 拼接</td><td>all-gather(last dim)</td><td>MultimemAllGatherer → NCCL 环回落</td><td>TP&gt;1,采样/logprob 需要</td><td>logits_processor.py:1079-1091;triton_symm_mem_ag.py:449</td></tr>
    <tr><td>DSpark 词表 gather</td><td>all-gather(dim 0/-1)</td><td>NVLink push/pull → NcclVocabGather</td><td>DSpark 投机模型 TP 分片</td><td>vocab_gather.py:41,198</td></tr>
    <tr><td>TP lm-head all-to-all</td><td>all-to-all(等分)</td><td><strong>强制 PyNccl</strong>(ncclGroupStart+Send/Recv)</td><td>--enable-tp-lm-head-all-to-all 且行布局等分</td><td>logits_processor.py:1368;pynccl.py:324;bootstrap.py:406</td></tr>
    <tr><td>DP Attention gather</td><td>allreduce(SUM,零缓冲)/ all-gather / all_gatherv</td><td>WORLD 组 torch.distributed 或 TP 组;整数强制 in-place NCCL</td><td>attn_dp_size&gt;1</td><td>dp_attention.py:661-748</td></tr>
    <tr><td>DP Attention combine</td><td>reduce-scatter(变长 rsv)</td><td>PyNccl sizes 模式</td><td>MoE/MLP 输出归还各 DP rank</td><td>dp_attention.py:1115;parallel_state.py:1273</td></tr>
    <tr><td>MoE standard DP 收拢/归还</td><td>all_gatherv / reduce_scatterv</td><td><strong>require PyNccl</strong>(逐 root broadcast/reduce)</td><td>moe_a2a_backend=none + DP attention</td><td>token_dispatcher/standard.py:169,208,295</td></tr>
    <tr><td>MoE EP a2a(专有后端)</td><td>—(不经 NCCL)</td><td>DeepEP/NVSHMEM/Mooncake/NIXL/Megamoe</td><td>--moe-a2a-backend ≠ none</td><td>token_dispatcher/deepep*.py 等</td></tr>
    <tr><td>DCP a2a(KV 交换)</td><td>all-to-all(字节)</td><td><strong>PyNccl</strong>(图内可捕获;fp8 走 uint8)</td><td>decode context parallel</td><td>layers/dcp/comm.py:144,545</td></tr>
    <tr><td>采样 token/状态同步</td><td>allreduce(MIN/MAX)</td><td>torch.distributed(attn-TP device_group)</td><td>SYNC_TOKEN_IDS / grammar / mask 状态</td><td>sampler.py:596-608,718</td></tr>
    <tr><td>EPLB 专家统计</td><td>allreduce(SUM)+ batch_isend_irecv 预热</td><td>torch.distributed 默认组</td><td>expert distribution dump / rebalance</td><td>eplb/expert_distribution.py:997;bootstrap.py:369</td></tr>
    <tr><td>多机 bootstrap / 建组</td><td>UniqueId 广播(gloo)、barrier、pyobj 广播</td><td>gloo CPU 组 + TCPStore</td><td>每次启动</td><td>parallel_state.py:2465;bootstrap.py:89;pynccl.py:89</td></tr>
    <tr><td>CUDA Graph 捕获期</td><td>全部原语</td><td><strong>PyNccl(+Mscclpp/SymmMem)</strong>,torch.distributed 禁用</td><td>graph_capture() 上下文</td><td>parallel_state.py:626-687,2299</td></tr>
    <tr><td>Page-interleave KV gather</td><td>对称窗口收集(0SM)</td><td><strong>专用 PyNccl</strong>+专用流+CTA_POLICY_ZERO</td><td>KV cache 分片 + ZERO_SM_GATHER</td><td>page_interleave_pool.py:217</td></tr>
    <tr><td>DSA 层分片广播</td><td>broadcast(src=owner)</td><td>专用 PyNccl / 组内 PyNccl</td><td>DSA 模型 CP 层分片</td><td>dsa_cache_layer_split.py:262;dsa_indexer.py:209</td></tr>
    <tr><td>engram 记忆交换</td><td>all-to-all</td><td>torch.distributed / 组 a2a</td><td>engram 层</td><td>layers/engram.py:1320-1329</td></tr>
    <tr><td>overlap scheduler 批同步</td><td>all-gather</td><td>torch.distributed</td><td>环境变量开启</td><td>dp_attn.py:609;environ.py:754</td></tr>
  </table>
</section>

<section>
<h2 class="sec" id="sec-9"><span class="num">9</span>现状与演进</h2>
  <h3>9.1 近期演进时间线</h3>
  <div class="timeline">
    <div class="timeline-item">
      <div class="timeline-time">早期 · #20866</div>
      <div class="timeline-body"><span class="timeline-tag">Refactor</span><strong>Parallel State Refactor:移除 PyNCCL 的固定流</strong>
        <p>PyNccl 从持有专属 stream 改为 <code>_resolve_stream()</code> 取当前设备流,通信跟随调用方流(为图捕获与多流复用铺路),见 <span class="filepath">pynccl.py:146-148</span>。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025 · #12065</div>
      <div class="timeline-body"><span class="timeline-tag">Feat</span><strong>DeepSeek v3.2 DSA 的上下文并行</strong>
        <p>引入 DSA 索引 topk 的 PyNccl broadcast 与 KV 层分片,后续演化出 dsa_cache_layer_split 的专用 layer_broadcast_comm。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025 · #21637</div>
      <div class="timeline-body"><span class="timeline-tag">Feat</span><strong>DCP:A2A + FlashInfer-MNNVL 通信后端</strong>
        <p>PyNccl 增加 <code>all_to_all_single</code>(ncclGroupStart 融合),服务 decode context parallel 的 KV 交换;<code>layers/dcp/comm.py</code> 落地。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025 · #27089</div>
      <div class="timeline-body"><span class="timeline-tag">Perf</span><strong>对称内存下关闭 NCCL 内部 CUDA event 同步</strong>
        <p>PyNccl 走 <code>ncclCommInitRankConfig</code> 并设 <code>graphUsageMode=1</code>(pynccl.py:117-122)。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025-2026 · #34355 / #43077</div>
      <div class="timeline-body"><span class="timeline-tag">Feat/Fix</span><strong>XPU DCP 与 AMD DP-attention 图内修复</strong>
        <p>DCP 扩展到 Intel XPU;AMD 上修复 DP attention + TP MoE 图内 NaN,引入 aiter reg/unreg 双路径与 <code>_AITER_CAPTURE_COPY_IN</code>。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2026 · #44029</div>
      <div class="timeline-body"><span class="timeline-tag">Perf</span><strong>KVShard:0SM KV Cache Allgather</strong>
        <p>page_interleave 池用专用 PyNccl + <code>NCCL_CTA_POLICY_ZERO</code>(copy engine、零 SM 占用)+ 对称 scratch,把 KV gather 的 SM 开销彻底移出推理路径。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2026 · #45503</div>
      <div class="timeline-body"><span class="timeline-tag">Fix</span><strong>禁止启用不可用的 PyNccl 通信器</strong>
        <p><code>get_available_pynccl_comm</code> 收紧可用性判定,不可用时 fail-fast(parallel_state.py:610-624),避免静默走错后端。</p>
      </div>
    </div>
  </div>
  <h3>9.2 分布式通信模块代码量分布(wc -l 实测)</h3>
  <div class="chart">
    <div class="chart-row">
      <div class="chart-label">parallel_state.py</div>
      <div class="chart-track"><div class="chart-bar bar-blue" style="width:100%"></div></div>
      <div class="chart-value">3531 行</div>
    </div>
    <div class="chart-row">
      <div class="chart-label">pymscclpp.py</div>
      <div class="chart-track"><div class="chart-bar bar-purple" style="width:36%"></div></div>
      <div class="chart-value">1278 行</div>
    </div>
    <div class="chart-row">
      <div class="chart-label">custom_all_reduce_v2.py</div>
      <div class="chart-track"><div class="chart-bar bar-green" style="width:17%"></div></div>
      <div class="chart-value">597 行</div>
    </div>
    <div class="chart-row">
      <div class="chart-label">triton_symm_mem_ag.py</div>
      <div class="chart-track"><div class="chart-bar bar-orange" style="width:16%"></div></div>
      <div class="chart-value">554 行</div>
    </div>
    <div class="chart-row">
      <div class="chart-label">pynccl_allocator.py</div>
      <div class="chart-track"><div class="chart-bar bar-red" style="width:15%"></div></div>
      <div class="chart-value">535 行</div>
    </div>
    <div class="chart-row">
      <div class="chart-label">shm_broadcast.py</div>
      <div class="chart-track"><div class="chart-bar bar-gray" style="width:15%"></div></div>
      <div class="chart-value">520 行</div>
    </div>
    <div class="chart-row">
      <div class="chart-label">pynccl_wrapper.py</div>
      <div class="chart-track"><div class="chart-bar bar-blue" style="width:20%"></div></div>
      <div class="chart-value">690 行</div>
    </div>
    <div class="chart-row">
      <div class="chart-label">pynccl.py</div>
      <div class="chart-track"><div class="chart-bar bar-green" style="width:12%"></div></div>
      <div class="chart-value">432 行</div>
    </div>
  </div>
  <p class="muted small">演进方向小结:NCCL 相关代码正从「单一 allreduce 兜底」走向「分层快路径 + NCCL 高级特性」——对称内存/cuMem/CTA 策略/窗口注册等 2.27+ 新 API 已成为 PyNccl 的主要增量,而 token 级 a2a 正被 DeepEP/NVSHMEM 等专有后端分流,NCCL 退守集合通信与图内兜底。</p>
</section>

<section>
<h2 class="sec" id="sec-10"><span class="num">10</span>小结</h2>
  <p>SGLang 对 NCCL 的使用可以压缩为三句话:<strong>(1)torch.distributed 进程组打底</strong>——WORLD/TP/EP/PP 各组建 NCCL 设备组 + gloo CPU 组,eager 模式与控制面通信都靠它;<strong>(2)PyNccl(ctypes 直绑)管图内与新特性</strong>——CUDA Graph 捕获期唯一可用的 NCCL 通道,同时承载对称内存、变长 v-集合、DCP/TP-lm-head all-to-all、0SM KV gather 等需要精细流/句柄控制的场景;<strong>(3)一套 should_* 谓词竞选的快路径体系</strong>把 NCCL 放在兜底位置,消息大小、拓扑、dtype、是否图内共同决定每一次集合通信落到 custom AR、IPC、对称内存还是 NCCL。</p>
  <p>工程上值得注意的三个细节:NCCL 环境变量(CUMEM/NVLS/GRAPH_REGISTER/GRAPH_MIXING_SUPPORT)由引擎按配置统一治理而非放任用户;<code>change_state</code> 的默认禁用 + 显式启用模式贯穿全部 PyNccl 调用点,误用(如 DSA 广播忘记启用)会静默产出错误结果而非报错;部署侧 libnccl-dev 的存在纯粹是为 pynccl_allocator 的 JIT 链接,升级 NCCL 版本需同时照顾 torch pin 与 DeepEP 需求。</p>
  <p>延伸阅读:并行策略总体设计见本系列<a href="/docs/inference-engines/sglang/03-parallelism/">第 04 篇·并行策略</a>,CUDA Graph 捕获机制见<a href="/docs/inference-engines/sglang/05-cuda-graph/">第 06 篇</a>,NCCL 相关 PR 的合入时间线见<a href="/docs/inference-engines/sglang/12-nccl-pr-history/">第 13 篇·NCCL PR 合入历史全景图</a>。</p>
</section>

  <div class="pgnav">
    <span>SGLang 深度解析系列 · ⑪ NCCL 使用场景全景 · 源码级分析基于 main @ b146a8576d · ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/sglang/10-model-zoo/">← 模型动物园</a> &nbsp;·&nbsp; <a href="/docs/inference-engines/sglang/12-nccl-pr-history/">NCCL 相关 PR 历史 →</a> &nbsp;·&nbsp; <a href="/docs/inference-engines/sglang/">返回总览</a></span>
  </div>
<script>
(function(){
// 滚动显现
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)});
// ===== 动画场景播放控制(暂停/重播/倍速) =====
function mkBtn(t){var b=document.createElement('button');b.type='button';b.textContent=t;return b}
function setRate(sc,rate){
  var els=sc.querySelectorAll('*');
  for(var i=0;i<els.length;i++){
    var el=els[i];
    if(el.classList&&el.classList.contains('scene-bar'))continue;
    var cs=window.getComputedStyle(el);
    if(!cs.animationDuration||cs.animationDuration==='0s')continue;
    if(!el.getAttribute('data-base-dur'))el.setAttribute('data-base-dur',cs.animationDuration);
    if(!el.getAttribute('data-base-del'))el.setAttribute('data-base-del',cs.animationDelay);
    el.style.animationDuration=(parseFloat(el.getAttribute('data-base-dur'))/rate)+'s';
    el.style.animationDelay=(parseFloat(el.getAttribute('data-base-del'))/rate)+'s';
  }
}
function initScene(sc){
  if(sc.getAttribute('data-anim-init'))return;
  sc.setAttribute('data-anim-init','1');
  var bar=document.createElement('div');bar.className='scene-bar';
  var bp=mkBtn('\u23F8 暂停');
  bp.addEventListener('click',function(){
    var p=sc.classList.toggle('paused');
    bp.textContent=p?'\u25B6 播放':'\u23F8 暂停';
    bp.classList.toggle('on',p);
  });
  var br=mkBtn('\u21BA 重播');
  br.addEventListener('click',function(){
    sc.classList.remove('paused');bp.textContent='\u23F8 暂停';bp.classList.remove('on');
    sc.classList.add('hold');void sc.offsetWidth;sc.classList.remove('hold');
  });
  var sps=[];
  [['0.5\u00D7',0.5],['1\u00D7',1],['2\u00D7',2]].forEach(function(s){
    var b=mkBtn(s[0]);b.setAttribute('data-rate',String(s[1]));
    if(s[1]===1)b.classList.add('on');
    b.addEventListener('click',function(){
      for(var k=0;k<sps.length;k++)sps[k].classList.remove('on');
      b.classList.add('on');setRate(sc,s[1]);
    });
    sps.push(b);
  });
  bar.appendChild(bp);bar.appendChild(br);
  for(var j=0;j<sps.length;j++)bar.appendChild(sps[j]);
  sc.appendChild(bar);
}
var ss=document.querySelectorAll('.scene');
for(var i=0;i<ss.length;i++)initScene(ss[i]);
})();
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>NCCL 相关 PR 合入历史全景图</title><link>https://hccl.club/docs/inference-engines/sglang/12-nccl-pr-history/</link><pubDate>Sun, 08 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/sglang/12-nccl-pr-history/</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:30px;
  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:2px;margin-bottom:12px}
.fwdoc .hero h1{font-size:33px;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 .hero h1 .cursor{display:inline-block;width:10px;height:28px;vertical-align:-3px;margin-left:6px;border-radius:2px;
  background:var(--accent2);animation:curblink 1.1s steps(1) infinite}
.fwdoc .statrow{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px;margin-top:26px}
.fwdoc .statrow .stat{background:rgba(20,29,51,.72);border:1px solid var(--border);border-radius:12px;padding:14px 18px;text-align:center;backdrop-filter:blur(4px)}
.fwdoc .statrow .stat .v{font-size:26px;font-weight:800;color:#fff;font-family:Consolas,monospace}
.fwdoc .statrow .stat .v .u{font-size:13px;color:var(--accent2);margin-left:2px}
.fwdoc .statrow .stat .k{font-size:12px;color:var(--muted);margin-top:2px}
.fwdoc .klabel{font-size:11px;color:#5a6b92;letter-spacing:1px;text-transform:uppercase;margin-bottom:10px}
.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 .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 p{margin:10px 0;color:var(--text);font-size:14.5px}
.fwdoc ul{list-style:disc;padding-left:26px;margin:10px 0}
.fwdoc ol{list-style:decimal;padding-left:26px;margin:10px 0}
.fwdoc li{margin:6px 0}
.fwdoc h3{font-size:18.5px;color:#fff;margin:28px 0 10px}
.fwdoc h3.sub{border-left:3px solid var(--accent);padding-left:12px}
.fwdoc h4{font-size:15.5px;color:#e6ecf9;margin:20px 0 8px}
.fwdoc h5{font-size:14px;color:var(--muted);margin:14px 0 6px}
.fwdoc a{color:var(--accent2)}
.fwdoc a:hover{text-decoration:underline}
.fwdoc hr{border:0;border-top:1px dashed #2a3a5c;margin:26px 0}
.fwdoc strong{color:#fff;font-weight:700}
.fwdoc blockquote{border-left:3px solid var(--accent);padding:6px 16px;margin:14px 0;color:var(--muted)}
.fwdoc code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:.88em}
.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 8px}
.fwdoc .tag{display:inline-block;background:rgba(79,140,255,.12);color:var(--accent2);border-radius:6px;
  padding:2px 9px;font-size:12px;font-weight:600;margin:2px 4px 2px 0}
.fwdoc .muted{color:var(--muted)}
.fwdoc .small{font-size:12.5px}
.fwdoc .two-col{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@media(max-width:800px){.fwdoc .two-col{grid-template-columns:1fr}}
.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 code{background:transparent;padding:0;color:#cfe0f5;font-size:inherit}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border);display:block;overflow-x:auto}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px;white-space:nowrap}
.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 .grid-2{display:grid;gap:16px;grid-template-columns:repeat(auto-fit,minmax(320px,1fr))}
.fwdoc .grid-3{display:grid;gap:16px;grid-template-columns:repeat(auto-fit,minmax(240px,1fr))}
.fwdoc .grid-2 .card,.fwdoc .grid-3 .card{margin:0}
.fwdoc .card-title{font-size:16.5px;color:#fff;font-weight:700;margin:0 0 8px}
.fwdoc .stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:14px;margin:20px 0}
.fwdoc .stat-grid .stat{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:12px;padding:16px 12px;text-align:center}
.fwdoc .stat-value{font-size:27px;font-weight:800;color:#fff}
.fwdoc .stat-label{font-size:12px;color:var(--muted);margin-top:4px}
.fwdoc .callout{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13.5px;margin:16px 0}
.fwdoc .callout p{margin:6px 0}
.fwdoc .callout.c-info{border-left-color:var(--accent)}
.fwdoc .callout.c-tip{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .callout.c-warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .callout.c-danger{border-left-color:var(--bad);background:rgba(248,113,113,.06)}
.fwdoc .callout strong{color:#fff}
.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 .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px;margin:0 5px 4px 0}
.fwdoc .badge.b-blue{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.b-green{background:rgba(52,211,153,.12);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.b-orange{background:rgba(251,146,60,.12);color:#fb923c;border:1px solid rgba(251,146,60,.4)}
.fwdoc .badge.b-red{background:rgba(248,113,113,.12);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.b-gray{background:rgba(142,160,194,.12);color:var(--muted);border:1px solid rgba(142,160,194,.35)}
.fwdoc .badge.b-purple{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .toc{background:rgba(20,29,51,.6);border:1px solid var(--border);border-radius:12px;padding:16px 22px;margin:0 0 30px}
.fwdoc .toc-title{font-size:12.5px;font-weight:700;color:var(--muted);letter-spacing:2px;margin-bottom:8px}
.fwdoc .toc ol,.fwdoc .toc ul{columns:2;column-gap:28px;margin:0;padding-left:20px}
.fwdoc .toc li{margin:4px 0;font-size:13.5px;break-inside:avoid}
.fwdoc .toc a{color:var(--text);text-decoration:none}
.fwdoc .toc a:hover{color:var(--accent2)}
@media(max-width:800px){.fwdoc .toc ol,.fwdoc .toc ul{columns:1}}
.fwdoc .timeline{position:relative;padding-left:28px;margin:20px 0}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .timeline-item{position:relative;margin-bottom:24px}
.fwdoc .timeline-item::before{content:"";position:absolute;left:-24px;top:6px;width:11px;height:11px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.15);animation:fw-tlpulse 2.4s infinite}
@keyframes fw-tlpulse{0%,100%{opacity:.55}50%{opacity:1}}
.fwdoc .timeline-time{font-size:12px;color:var(--accent2);font-weight:700;font-family:Consolas,monospace}
.fwdoc .timeline-body{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:10px;padding:12px 16px;margin-top:6px}
.fwdoc .timeline-body p{margin:6px 0 0;font-size:13.5px}
.fwdoc .timeline-tag{display:inline-block;font-size:11px;font-weight:700;padding:1px 8px;border-radius:4px;
  background:rgba(79,140,255,.14);color:var(--accent2);margin-left:8px;vertical-align:1px}
.fwdoc .flow{display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin:18px 0}
.fwdoc .flow-v{display:flex;flex-direction:column;align-items:flex-start;gap:6px;margin:18px 0}
.fwdoc .flow .node,.fwdoc .flow-v .node{background:#101a2d;border:1.5px solid #3a5a8c;border-radius:9px;
  padding:8px 13px;font-size:13.5px;font-weight:600;color:#e6eefb}
.fwdoc .flow .node small,.fwdoc .flow-v .node small{display:block;font-weight:400;color:var(--muted);font-size:11.5px;margin-top:2px}
.fwdoc .node-accent{border-color:var(--accent) !important;background:rgba(79,140,255,.12) !important;color:#cfe4ff !important}
.fwdoc .arrow{color:#7d9ac4;font-size:19px;font-weight:700;line-height:1}
.fwdoc .arrow-v{color:#7d9ac4;font-size:17px;font-weight:700;padding-left:16px}
.fwdoc .chart{margin:20px 0}
.fwdoc .chart-row{display:grid;grid-template-columns:230px 1fr 70px;gap:10px;align-items:center;margin:8px 0;font-size:13.5px}
.fwdoc .chart-label{text-align:right;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.fwdoc .chart-track{background:rgba(10,16,32,.85);border-radius:6px;height:20px;overflow:hidden}
.fwdoc .chart-bar{height:100%;border-radius:6px 0 0 6px;background:var(--accent);min-width:2px}
.fwdoc .bar-blue{background:var(--accent)}
.fwdoc .bar-green{background:var(--good)}
.fwdoc .bar-orange{background:#fb923c}
.fwdoc .bar-red{background:var(--bad)}
.fwdoc .bar-purple{background:var(--purple)}
.fwdoc .bar-gray{background:#64748b}
.fwdoc .chart-value{font-family:Consolas,monospace;font-size:12px;color:var(--muted)}
.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:.1s}
.fwdoc .reveal.d2{transition-delay:.2s}
.fwdoc .reveal.d3{transition-delay:.3s}
.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 .pgnav a:hover{text-decoration:underline}
.fwdoc .scene{--T:6s;position:relative;background:radial-gradient(1100px 420px at 18% -12%,#16273f 0%,#0d1729 55%,#0a0f1c 100%);
  border:1px solid var(--border);border-radius:var(--radius);padding:20px 22px 18px;min-height:200px;
  color:#d7e3f4;overflow:hidden;margin:20px 0 8px}
.fwdoc .scene .sc-title{position:absolute;top:12px;left:16px;font-size:12.5px;font-weight:700;color:#8fa7c9;letter-spacing:.05em}
.fwdoc .scene .sc-hint{position:absolute;bottom:10px;right:14px;font-size:11px;color:#5d7396}
.fwdoc .scene .row{display:flex;align-items:center;gap:14px;flex-wrap:wrap}
.fwdoc .scene .col{display:flex;flex-direction:column;gap:12px;align-items:flex-start}
.fwdoc .scene .cen{justify-content:center;align-items:center}
.fwdoc .scene .stack{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px}
.fwdoc .scene .trow{display:flex;gap:4px;flex-wrap:wrap;align-items:center}
.fwdoc .scene .abs{position:absolute}
.fwdoc .scene .mt{margin-top:30px}
.fwdoc .scene .lbl{font-size:11.5px;color:#7d92b4;font-weight:600}
.fwdoc .scene .big{font-size:19px;font-weight:800;color:#eaf2ff}
.fwdoc .scene .dim{opacity:.42}
.fwdoc .scene .gpu{background:#101a2d;border:1.5px solid #31507e;border-radius:10px;padding:9px 14px;min-width:78px;
  text-align:center;font-weight:700;font-size:14px;color:#e6eefb}
.fwdoc .scene .gpu small{display:block;font-weight:400;color:#7d92b4;font-size:11.5px;margin-top:2px}
.fwdoc .scene .node{background:#101a2d;border:1.5px solid #3a5a8c;border-radius:10px;padding:8px 13px;text-align:center;
  font-weight:700;font-size:13.5px;color:#e6eefb}
.fwdoc .scene .node small{display:block;font-weight:400;color:#7d92b4;font-size:11.5px;margin-top:2px}
.fwdoc .scene .srv{border:1.5px solid #3b6ea5;border-radius:12px;padding:12px 14px;background:rgba(16,26,45,.78);min-width:170px}
.fwdoc .scene .srv-head{font-weight:800;color:#bfe0ff;font-size:13.5px;margin-bottom:8px}
.fwdoc .scene .zone{border:1.5px dashed #3a5b8f;border-radius:10px;padding:10px 12px}
.fwdoc .scene .bub{width:36px;height:36px;border-radius:50%;background:#16233c;border:1.5px solid #3a5a8c;
  display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#cfe0f7}
.fwdoc .scene .tok{width:16px;height:16px;border-radius:4px;background:#3a4a63;display:inline-block}
.fwdoc .scene .tok.a{background:#3b82f6}
.fwdoc .scene .tok.b{background:#22c55e}
.fwdoc .scene .tok.c{background:#f59e0b}
.fwdoc .scene .tok.d{background:#a78bfa}
.fwdoc .scene .tok.e{background:#f472b6}
.fwdoc .scene .kv{width:22px;height:14px;border-radius:3px;background:#3a4a63;display:inline-block}
.fwdoc .scene .bar{height:14px;border-radius:4px;background:#3b82f6;min-width:70px;transform-origin:left center}
.fwdoc .scene .bar.g{background:#22c55e}
.fwdoc .scene .bar.o{background:#f59e0b}
.fwdoc .scene .bar.r{background:#ef4444}
.fwdoc .scene .wire{height:2px;flex:none;min-width:40px;background:repeating-linear-gradient(90deg,#3f6db3 0 8px,transparent 8px 16px);animation:fw-k-flow .9s linear infinite}
.fwdoc .scene .wire.v{width:2px;min-width:0;height:auto;align-self:stretch;min-height:34px;
  background:repeating-linear-gradient(180deg,#3f6db3 0 8px,transparent 8px 16px);animation:fw-k-flowv .9s linear infinite}
.fwdoc .scene .pkt{position:absolute;width:12px;height:12px;border-radius:50%;background:#38bdf8;box-shadow:0 0 12px rgba(56,189,248,.8)}
.fwdoc .scene .pkt.g{background:#34d399;box-shadow:0 0 12px rgba(52,211,153,.8)}
.fwdoc .scene .pkt.o{background:#fb923c;box-shadow:0 0 12px rgba(251,146,60,.8)}
.fwdoc .scene .pkt.r{background:#f87171;box-shadow:0 0 12px rgba(248,113,113,.8)}
.fwdoc .scene .pkt.v{background:#a78bfa;box-shadow:0 0 12px rgba(167,139,250,.8)}
.fwdoc .scene .mv{animation:fw-k-mv var(--T) linear infinite}
.fwdoc .scene .pop{animation:fw-k-pop var(--T) ease-in-out infinite}
.fwdoc .scene .fadein{animation:fw-k-fadein var(--T) ease-in-out infinite}
.fwdoc .scene .hit{animation:fw-k-on var(--T) ease-in-out infinite}
.fwdoc .scene .hit.o{animation-name:fw-k-on-o}
.fwdoc .scene .hit.r{animation-name:fw-k-on-r}
.fwdoc .scene .hit.b{animation-name:fw-k-on-b}
.fwdoc .scene .ok{animation:fw-k-ok var(--T) ease-in-out infinite}
.fwdoc .scene .no{animation:fw-k-no var(--T) ease-in-out infinite}
.fwdoc .scene .pulse{animation:fw-k-pulse 1.8s ease-in-out infinite}
.fwdoc .scene .glow{animation:fw-k-glow 2.4s ease-in-out infinite}
.fwdoc .scene .grow{animation:fw-k-grow var(--T) ease-in-out infinite;transform-origin:left center}
.fwdoc .scene .alt{animation-direction:alternate}
.fwdoc .scene .svgflow{stroke-dasharray:5 9;animation:fw-k-dash 1.1s linear infinite}
.fwdoc .scene .d1{animation-delay:calc(var(--T)*.04)}
.fwdoc .scene .d2{animation-delay:calc(var(--T)*.08)}
.fwdoc .scene .d3{animation-delay:calc(var(--T)*.12)}
.fwdoc .scene .d4{animation-delay:calc(var(--T)*.16)}
.fwdoc .scene .d5{animation-delay:calc(var(--T)*.20)}
.fwdoc .scene .d6{animation-delay:calc(var(--T)*.24)}
.fwdoc .scene .d7{animation-delay:calc(var(--T)*.28)}
.fwdoc .scene .d8{animation-delay:calc(var(--T)*.32)}
.fwdoc .scene .d9{animation-delay:calc(var(--T)*.36)}
.fwdoc .scene .d10{animation-delay:calc(var(--T)*.40)}
.fwdoc .scene .d11{animation-delay:calc(var(--T)*.44)}
.fwdoc .scene .d12{animation-delay:calc(var(--T)*.48)}
.fwdoc .scene .d13{animation-delay:calc(var(--T)*.52)}
.fwdoc .scene .d14{animation-delay:calc(var(--T)*.56)}
.fwdoc .scene .d15{animation-delay:calc(var(--T)*.60)}
.fwdoc .scene .d16{animation-delay:calc(var(--T)*.64)}
.fwdoc .scene .d17{animation-delay:calc(var(--T)*.68)}
.fwdoc .scene .d18{animation-delay:calc(var(--T)*.72)}
.fwdoc .scene .d19{animation-delay:calc(var(--T)*.76)}
.fwdoc .scene .d20{animation-delay:calc(var(--T)*.80)}
.fwdoc .scene .d21{animation-delay:calc(var(--T)*.84)}
.fwdoc .scene .d22{animation-delay:calc(var(--T)*.88)}
.fwdoc .scene .d23{animation-delay:calc(var(--T)*.92)}
.fwdoc .scene .d24{animation-delay:calc(var(--T)*.96)}
@keyframes fw-k-flow{to{background-position:16px 0}}
@keyframes fw-k-flowv{to{background-position:0 16px}}
@keyframes fw-k-mv{0%{transform:translate(0,0);opacity:0}10%{opacity:1}85%{opacity:1}100%{transform:translate(var(--tx,120px),var(--ty,0));opacity:0}}
@keyframes fw-k-pop{0%,8%{transform:scale(0);opacity:0}20%,82%{transform:scale(1);opacity:1}94%,100%{transform:scale(0);opacity:0}}
@keyframes fw-k-fadein{0%,10%{opacity:0}28%,84%{opacity:1}96%,100%{opacity:0}}
@keyframes fw-k-on{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#22c55e;box-shadow:0 0 12px rgba(34,197,94,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-on-o{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#f59e0b;box-shadow:0 0 12px rgba(245,158,11,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-on-r{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#ef4444;box-shadow:0 0 12px rgba(239,68,68,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-on-b{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#3b82f6;box-shadow:0 0 12px rgba(59,130,246,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-ok{0%,18%{background:#3a4a63;transform:scale(1);box-shadow:none}34%,86%{background:#22c55e;transform:scale(1.22);box-shadow:0 0 12px rgba(34,197,94,.6)}100%{background:#22c55e;transform:scale(1)}}
@keyframes fw-k-no{0%,16%{background:#3a4a63;opacity:1;transform:translateX(0)}30%{background:#ef4444}38%{transform:translateX(-4px)}48%{transform:translateX(4px)}62%{opacity:.22;transform:translateY(7px)}100%{opacity:.22;transform:translateY(7px);background:#3a4a63}}
@keyframes fw-k-pulse{0%,100%{transform:scale(1)}50%{transform:scale(1.1)}}
@keyframes fw-k-glow{0%,100%{box-shadow:0 0 0 0 rgba(59,130,246,0)}50%{box-shadow:0 0 18px 2px rgba(59,130,246,.55)}}
@keyframes fw-k-grow{0%,10%{transform:scaleX(.08)}42%,82%{transform:scaleX(1)}94%,100%{transform:scaleX(.08)}}
@keyframes fw-k-dash{to{stroke-dashoffset:-56}}
.fwdoc .scene-bar{position:absolute;top:10px;right:12px;display:flex;gap:5px;z-index:9}
.fwdoc .scene-bar button{background:rgba(13,21,36,.88);color:#9fb4d4;border:1px solid #2c4166;border-radius:7px;
  font-size:12px;padding:3px 10px;cursor:pointer;font-family:inherit}
.fwdoc .scene-bar button:hover{color:#fff;border-color:var(--accent)}
.fwdoc .scene-bar button.on{color:#fff;background:#1f4fd8;border-color:#1f4fd8}
.fwdoc .scene.paused *{animation-play-state:paused !important}
.fwdoc .scene.hold *{animation:none !important}
@media(prefers-reduced-motion:reduce){.fwdoc .scene,.fwdoc .scene *{animation:none !important}}
.fwdoc .sc-cap{font-size:13.5px;color:var(--muted);margin:0 0 26px;padding:0 4px}
.fwdoc .sc-cap strong{color:#fff}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:22px;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 .station{animation:fw-stationGlow 2.4s ease-in-out infinite}
@keyframes fw-stationGlow{0%,100%{opacity:.55}50%{opacity:1}}
.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 .oneline{font-size:13.5px;color:var(--text);margin:10px 0 6px;padding-left:12px;border-left:3px solid var(--accent)}
.fwdoc ul.feat{list-style:none;margin:8px 0}
.fwdoc ul.feat li{padding:6px 0 6px 26px;position:relative;font-size:13px;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-blinkdot 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
.fwdoc .paths{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0 2px}
.fwdoc .paths .filepath{font-size:10.5px}
.fwdoc .full{color:var(--good);font-weight:700}
.fwdoc .half{color:var(--warn);font-weight:700}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-svgflowmove 1.2s linear infinite}
@keyframes fw-svgflowmove{to{stroke-dashoffset:-14}}
.fwdoc .svgpulse{animation:fw-svgpulse 2s ease-in-out infinite;transform-origin:center;transform-box:fill-box}
@keyframes fw-svgpulse{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-tokrun{0%{transform:translateX(-6px);opacity:0}15%{opacity:1}85%{opacity:1}100%{transform:translateX(150px);opacity:0}}
@keyframes fw-growbar{from{width:0}to{width:100%}}
/* ===== 导入面板附加样式 ===== */
.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>

<div class="toc"><div class="toc-title">本页目录 · 先动画建立直觉,再源码落到实地</div><ol><li><a href="#anim">0. 动画速览 · 建立直觉</a></li><li><a href="#sec-1">1. 检索方法与总览统计</a></li><li><a href="#sec-2">2. 全景矩阵:主题 × 时间段</a></li><li><a href="#sec-3">3. 里程碑时间线</a></li><li><a href="#sec-4">4. 主题深潜:特性支持线与问题解决线</a></li><li><a href="#sec-5">5. 重点 PR 深读(--stat 摘要)</a></li><li><a href="#sec-6">6. 配置项与开关的演进痕迹</a></li><li><a href="#sec-7">7. 修复问题模式总结</a></li><li><a href="#sec-8">8. 小结:NCCL 在 SGLang 通信栈中的角色演进</a></li></ol></div>

  <section>
<h2 class="sec" id="anim"><span class="num">0</span>动画速览 · 建立直觉</h2>
<p class="lede">两年半、一百八十多次与通信相关的合入,可以压成三幕剧:先借 PyTorch 的分布式封装,拿环境变量当创可贴;再绕过中间层、直接与 NCCL 本尊握手,把方向盘拿回自己手里;最后在它头顶架起一条条专用快车道,让它安心退居默认底座。</p>

  

  <div class="callout c-tip"><strong>一句话理解:</strong>SGLang 与 NCCL 的关系,走完了「用别人的 → 自己握方向盘 → 多条道各跑各的车」三个阶段;今天 NCCL 依然是多卡通信的默认底座,但早已不是唯一的干道。</div>

  

  <div class="stat-grid">
    <div class="stat"><div class="stat-value">3 幕</div><div class="stat-label">依赖期 → 自控期 → 共存期</div></div>
    <div class="stat"><div class="stat-value">180+</div><div class="stat-label">两年半里的 NCCL 相关合入(次)</div></div>
    <div class="stat"><div class="stat-value">约 3 成</div><div class="stat-label">修复与稳定性类合入占比</div></div>
    <div class="stat"><div class="stat-value">11 次</div><div class="stat-label">「回滚 → 再恢复」的拉锯</div></div>
  </div>

  <h3 class="sub" id="s1">三幕时间线:借来的轮子、自己的方向盘、并存的快车道</h3>
  <p>时间回到 2024 年年中。那时的 SGLang 刚学会多卡推理,通信这件事几乎是「整包外包」:直接借用 PyTorch 自带的分布式封装,NCCL 藏在这层封装底下,像一台借来的车——能开,但引擎盖不敢掀。整整半年,与 NCCL 相关的改动只有寥寥几笔,而且清一色是「环境变量级」的防御:多卡场景不稳?那就默认关掉一个名叫 NVLS 的可疑加速特性(仓库里最早的一笔,编号 <span class="tag">PR 631</span>);某种网络下握手不畅?那就补一个环境变量绕开。这像什么呢?车子异响,你只能往仪表盘上贴张纸条:「时速别超过八十」——因为你既没有工具,也没有权限去修发动机。更麻烦的是,两个真问题很快浮出水面:<strong>多机偶发集体卡死</strong>,所有进程安静地等一个永远不到的信号,只能重启;<strong>图内通信不通</strong>,SGLang 靠「把解码过程录成一张 CUDA Graph 反复回放」吃饭(见<a href="/docs/inference-engines/sglang/05-cuda-graph/">第 6 篇</a>),而借来的通信封装在「录音」的时候不配合,这一段录不进去,回放就断片。两个病有个共同点:病根都不在 SGLang 自己的代码里,修不动。</p>
  <p>于是在 2024 年底,有了那个关键决定:绕过借来的封装,直接与 NCCL 本尊握手——自建一层很薄的直连封装(<span class="tag">PR 2244</span>)。它小得不起眼,意义却极大:通信的每个动作,何时发、走哪条流、能不能录进图里,从此都由 SGLang 自己说了算;第一个目标非常具体,就是把集合通信录进 CUDA Graph。拿下之后,2025 年一路深挖:「对称内存」让数据直接落进对端 GPU「看得见」的显存窗口,跳过通信库内部的层层拷贝(<span class="tag">PR 8238</span>);「专用分配器」把通信用的显存单独管理、防止碎片;「变长集合通信」让长短不一的消息按实际长度收发,不再为对齐而白白搬运。到了 2026 年,剧情再次反转:自控的终点不是取代 NCCL,而是在它上面修路——自研 allreduce、PCIe 直递、MSCCL++ 等专用快车道相继架起,系统按消息大小与拓扑自动选路,NCCL 退居「默认底座」。下面这个场景,就是压缩版的三幕剧。</p>

  <div class="scene" style="--T:12s">
    <div class="sc-title">场景 · 三幕时间线:借来的轮子 → 自己的方向盘 → 并存的快车道</div>
    <div class="row mt cen">
      <div class="zone" style="width:30%;height:300px">
        <div class="col cen" style="width:100%;height:100%">
          <div class="bub hit d1">2024</div>
          <div class="lbl">第一幕 · 依赖期</div>
          <div class="node fadein d2" style="width:94%">整包借用 PyTorch 封装<small>方向盘在别人手里</small></div>
          <div class="node hit.b d4" style="width:94%">环境变量级防御<small>出问题先关掉可疑开关</small></div>
          <div class="node hit.r d6" style="width:94%">多机卡死 · 图内不通<small>病根不在自己代码里</small></div>
        </div>
      </div>
      <div class="zone" style="width:32%;height:300px">
        <div class="col cen" style="width:100%;height:100%">
          <div class="bub hit d7">2025</div>
          <div class="lbl">第二幕 · 自控期</div>
          <div class="node ok d8" style="width:94%">自建轻量直连封装<small>直接与 NCCL 本尊握手</small></div>
          <div class="node hit d10" style="width:94%">对称内存 + 专用分配器<small>数据直达对端,通信内存自己管</small></div>
          <div class="node hit d12" style="width:94%">变长集合通信<small>长短消息按实际长度收发</small></div>
        </div>
      </div>
      <div class="zone" style="width:34%;height:300px">
        <div class="col cen" style="width:100%;height:100%">
          <div class="bub hit d13">2026</div>
          <div class="lbl">第三幕 · 共存期</div>
          <div class="row cen" style="width:100%">
            <div class="node pop d15" style="width:46%">自研 allreduce</div>
            <div class="node pop d16" style="width:46%">PCIe 直递</div>
            <div class="node pop d17" style="width:46%">MSCCL++</div>
            <div class="node pop d18" style="width:46%">torch 对称内存</div>
          </div>
          <div class="node glow" style="width:94%">自动选路<small>按消息大小与拓扑分道,NCCL 退居底座</small></div>
        </div>
      </div>
    </div>
    <div class="sc-hint">蓝 = 铺垫,红 = 问题,绿 = 落地;盒子按合入时间依次点亮</div>
  </div>
  <p class="sc-cap">动画解说:三个虚线框是三幕。<strong>2024 框</strong>里,蓝色盒子先亮(环境变量防御),紧接着泛红(多机卡死、图内不通)——创可贴贴不住;<strong>2025 框</strong>里,放大泛绿的盒子是自建直连封装,随后对称内存、专用分配器、变长通信依次点亮;<strong>2026 框</strong>里,四条快车道并排弹出,最底下「自动选路」节点泛起蓝光——每条消息走哪条道,由它说了算。</p>

  <h3 class="sub" id="s2">暗线:上线、闪红、回滚、再上岗</h3>
  <p>三幕剧是明线,这段历史里还藏着一条暗线:<strong>修 bug 的拉锯</strong>。通信是整个系统里试错成本最高的子系统,因为它的 bug 有三个残忍的特点:一,只在特定拓扑下复现——你办公室的机器八张卡全互通,用户的机器却要走交换机;二,只在特定组合下爆炸——新后端、某个模型、图回放,三者同时成立才会死;三,死法安静——不是报错,而是所有进程一起沉默地等。CI 跑得再勤,也盖不住这些排列组合。</p>
  <p>于是几乎每个新后端都要走同一套剧本:<strong>满怀希望上线 → 闪红 → 回滚保命 → 找到病根 → 带着防御性默认值和补齐的测试重新上岗</strong>。对称内存曾整体回滚,九天后修复回归;自研 allreduce 经历过著名的「NaN 三连」——回滚、修、再回滚、再修,才终于站稳;连 PyTorch 官方的对称内存路径,也在三天之内上演回滚又上岗。把这段历史翻完:修复与稳定性类的合入大约占三成,而全部十一次「回滚再恢复」的拉锯,几乎无一例外落在通信路径上。这不是鲁莽,是这个子系统的宿命——轮胎的问题,只有真开上高速才会暴露;而通信的新路,永远只能在真实车流里验证。</p>

  <div class="scene" style="--T:12s">
    <div class="sc-title">场景 · 一个新后端的一生:上线 → 闪红回滚 → 修复上岗</div>
    <div class="col mt cen" style="width:100%">
      <div class="row cen">
        <div class="col cen">
          <span class="lbl">第一步 · 上线</span>
          <div class="node pop d2" style="width:180px">新通信后端<small>更快的路径</small></div>
        </div>
        <div class="wire" style="width:60px"></div>
        <div class="col cen">
          <span class="lbl">第二步 · 闪红回滚</span>
          <div class="node no d10" style="width:180px">线上出问题<small>先回滚保命</small></div>
        </div>
        <div class="wire" style="width:60px"></div>
        <div class="col cen">
          <span class="lbl">第三步 · 修复上岗</span>
          <div class="node ok d18" style="width:180px">修好再上岗<small>带着防御与补齐的测试</small></div>
        </div>
      </div>
      <div class="row cen">
        <span class="lbl">同一剧本,反复上演</span>
        <div class="node ok d16" style="width:170px">对称内存<small>整体回滚,九天后回归</small></div>
        <div class="node ok d18" style="width:170px">自研 allreduce<small>「NaN 三连」后站稳</small></div>
        <div class="node ok d20" style="width:170px">torch 对称内存<small>三天内回滚又上岗</small></div>
      </div>
      <div class="row cen">
        <span class="lbl">稳定性投入</span>
        <div class="bar g grow d4" style="width:80px"></div>
        <div class="bar g grow d12" style="width:130px"></div>
        <div class="bar g grow d20" style="width:180px"></div>
      </div>
    </div>
    <div class="sc-hint">三成合入在修 bug;回滚几乎全部落在通信路径上</div>
  </div>
  <p class="sc-cap">动画解说:上面一行是新后端的「一生」——盒子先弹出(<strong>上线</strong>),再<strong>变红抖动、沉底</strong>(发现问题、回滚保命),最后<strong>放大泛绿</strong>(修复、带着防御重新上岗)。中间一行是真实上演过的三例,全都以「重新上岗」收场;底部绿色条一轮轮生长,代表稳定性投入在整段历史里持续累积。</p>

  <h3 class="sub" id="s3">终局画面:一条底座,几条快车道</h3>
  <p>到 2026 年,画面稳定成这样:底层是宽厚的 <strong>NCCL 底座</strong>,常亮、兜底;上方一条条专用快车道依次架起。<strong>自研 allreduce</strong> 专为单机小消息的低延迟而生,迭代到第二代之后已经默认启用;<strong>PCIe 直递</strong>照顾没有交换机的机器,让 GPU 之间点对点直达;<strong>MSCCL++</strong> 的故事最曲折:最初是自研内核,后来发现上游官方包更成熟,干脆删掉自研、直接改用上游(<span class="tag">PR 22734</span>),适用范围还从一两个节点扩展到了八个。这些快车道各有所长,也各有门槛:有的只吃小消息,有的要求特定拓扑,有的只在特定代次的显卡上有效。</p>
  <p>于是「怎么选」成了新问题,答案是<strong>把选择权交给系统</strong>:启动时探测拓扑——谁与谁直连、走不走交换机、一共几张卡;运行时按消息大小自动选路——小消息上高架,大消息下底座;任何一条快车道不适用,随时退回 NCCL 兜底。NCCL 的角色,就这样从「唯一的路」变成了「最宽的路,兼所有路的地基」。这也是本篇叫「演进史」而不叫「替换史」的原因:自研的每一步,都在让 NCCL 的位置更稳固,而不是更边缘。</p>

  <div class="scene" style="--T:12s">
    <div class="sc-title">场景 · 终局:一条底座,几条快车道</div>
    <div class="col mt" style="width:100%">
      <div class="row" style="height:44px;width:100%">
        <span class="lbl" style="width:230px">小消息 · 自研 allreduce 直达</span>
        <div class="wire pop d3" style="width:66%"></div>
      </div>
      <div class="row" style="height:44px;width:100%">
        <span class="lbl" style="width:230px">PCIe 拓扑 · 点对点直递</span>
        <div class="wire pop d7" style="width:66%"></div>
      </div>
      <div class="row" style="height:44px;width:100%">
        <span class="lbl" style="width:230px">节点间 · MSCCL++ 一段式</span>
        <div class="wire pop d11" style="width:66%"></div>
      </div>
      <div class="zone glow" style="width:100%">
        <div class="col cen" style="width:100%">
          <div class="row cen"><span class="lbl">NCCL 默认底座 · 常亮 · 兜底</span></div>
          <div class="row cen">
            <div class="gpu">GPU 0</div><div class="wire" style="width:36px"></div><div class="gpu">GPU 1</div><div class="wire" style="width:36px"></div><div class="gpu">GPU 2</div><div class="wire" style="width:36px"></div><div class="gpu">GPU 3</div>
          </div>
          <div class="row cen"><span class="lbl">大消息 · 多机复杂拓扑 · 所有快车道的回退终点</span></div>
        </div>
      </div>
    </div>
    <div class="pkt abs mv d5" style="left:28%;top:66px;--tx:560px"></div>
    <div class="pkt abs g mv d9" style="left:28%;top:122px;--tx:560px"></div>
    <div class="pkt abs v mv d13" style="left:28%;top:178px;--tx:560px"></div>
    <div class="pkt abs o mv d18" style="left:30%;top:265px;--tx:560px"></div>
    <div class="sc-hint">哪条道跑什么车,由拓扑探测与消息大小共同决定</div>
  </div>
  <p class="sc-cap">动画解说:底部虚线框是<strong>常亮的 NCCL 底座</strong>,蓝光呼吸,托着四张 GPU;上方三条<strong>高架快车道</strong>依次架起,彩色圆点是驶过的消息——小消息走高架专线,橙色的大消息走底座干道。哪条道跑什么车,由「自动选路」决定。</p>

  <h3 class="sub" id="summary">小结:性能与稳定性是一体两面</h3>
  <p>把三幕剧再压缩,其实就一句话:从「用别人的」,到「自己握方向盘」,再到「多条道各跑各的车」。</p>
  <div class="flow">
    <div class="node">借来的封装<small>2024:整包借用 PyTorch,环境变量当创可贴</small></div><div class="arrow">→</div>
    <div class="node node-accent">自建直连封装<small>2024 末–2025:图内通信 · 对称内存 · 分配器</small></div><div class="arrow">→</div>
    <div class="node node-accent">多后端并存<small>2026:快车道 + 自动选路,NCCL 当底座</small></div>
  </div>
  <div class="grid-2">
    <div class="card">
      <div class="card-title">一条主线,三步走</div>
      <p>第一步「用别人的」:整包借用,出问题只能贴创可贴,因为病根不在自己代码里;第二步「自己握方向盘」:自建轻量直连封装,先为图内通信,再深挖对称内存、分配器、变长收发;第三步「多条道各跑各的车」:快车道相继架起,自动选路上岗,NCCL 退居底座。</p>
    </div>
    <div class="card">
      <div class="card-title">性能与稳定性是一体两面</div>
      <p>每条快车道都是「先上车再补票」:修复与稳定性类合入约占三成,回滚几乎全部落在通信路径上;但每次回滚,最终都换来防御性默认值和补齐的测试。快是真的快,疼也是真的疼——这两者是同一枚硬币。</p>
    </div>
    <div class="card">
      <div class="card-title">能力越大,问题面越大</div>
      <p>能直接摆弄通信内存之后,显存碎片、图回放时的地址假设、通信库版本与硬件的耦合,全都变成了自己的问题面。收益与责任,是同步到账的。</p>
    </div>
    <div class="card">
      <div class="card-title">自研还是用上游?看生态成熟度</div>
      <p>标准化程度高、上游活跃的(如 MSCCL++)直接改用官方包;性能关键、讲究独到的(如自研 allreduce)握在自己手里。判据是生态成熟度与收益,不是自尊心。</p>
    </div>
  </div>
  <p class="small">延伸阅读:NCCL 今天具体在哪些场景被如何使用,见<a href="/docs/inference-engines/sglang/11-nccl-usage/">第 12 篇</a>;并行组与通信选路的架构背景,见<a href="/docs/inference-engines/sglang/03-parallelism/">第 4 篇</a>;CUDA Graph 的录制与回放,见<a href="/docs/inference-engines/sglang/05-cuda-graph/">第 6 篇</a>;更广的跨卡通信生态,见<a href="/docs/inference-engines/sglang/13-cross-card-comm/">第 14 篇</a>。</p>

  <h3 class="sub" id="faq">常见问题</h3>
  <div class="callout c-info">
    <strong>Q:为什么不干脆全部自研,把 NCCL 扔掉?</strong>
    <p>A:因为 NCCL 在大消息与复杂拓扑上依然最强。多机组网、异构互联、每一代新硬件——作为 NVIDIA 官方维护的通信库,它对自家拓扑的理解无人能及;而自研路径的收益,集中在「小消息、低延迟」这一段。全盘替换,等于放弃高速公路去修乡道。所以终局是「底座 + 快车道」,不是「替换」。</p>
  </div>
  <div class="callout c-info">
    <strong>Q:新后端经常闪红回滚,是不是不靠谱?</strong>
    <p>A:恰恰相反,回滚是工程上最诚实的止损。通信 bug 只在特定拓扑、负载、组合下复现,CI 覆盖不了;而每次回滚,最终都沉淀为防御性默认值与测试。判断一个通信子系统靠不靠谱,不看它有没有回滚过,看它每次回滚之后,是不是站得更稳。</p>
  </div>
  <div class="callout c-info">
    <strong>Q:那现在到底默认走哪条路?</strong>
    <p>A:没有固定答案——这正是「自动选路」的含义:启动时探测拓扑,运行时按消息大小分道;小消息走快车道,大消息与复杂拓扑走 NCCL,任何快车道失效都有回退。这条路的选择,不需要你替系统做。</p>
  </div>

  
</section>

<section>
<h2 class="sec" id="sec-1"><span class="num">1</span>检索方法与总览统计</h2>
  <p>SGLang 主分支共 21419 个提交(截至 2026-11-01,commit <code>b146a8576d</code>)。本篇采用"消息检索 + 文件历史"两路并集的方式圈定 NCCL 相关合入,全部命令只读、可复现:</p>
  <pre class="code"><code># A. 消息检索(大小写不敏感,多个 --grep 为 OR 关系)→ 83 条
git log --date=short --pretty='%h|%ad|%s' -i \
  --grep=nccl --grep=msccl --grep='symm mem' --grep='symm-mem' \
  --grep=cumem --grep=nvls --grep=rccl

# B. 文件历史(device_communicators 下 NCCL 家族文件)→ 116 条
git log --date=short --pretty='%h|%ad|%s' -- \
  python/sglang/srt/distributed/device_communicators/pynccl.py \
  python/sglang/srt/distributed/device_communicators/pynccl_wrapper.py \
  python/sglang/srt/distributed/device_communicators/pynccl_allocator.py \
  python/sglang/srt/distributed/device_communicators/custom_all_reduce.py \
  python/sglang/srt/distributed/device_communicators/custom_all_reduce_v2.py \
  python/sglang/srt/distributed/device_communicators/custom_all_reduce_ops.py \
  python/sglang/srt/distributed/device_communicators/custom_all_reduce_utils.py \
  python/sglang/srt/distributed/device_communicators/pymscclpp.py \
  python/sglang/srt/distributed/device_communicators/torch_symm_mem.py \
  python/sglang/srt/distributed/device_communicators/quick_all_reduce.py \
  python/sglang/srt/distributed/device_communicators/pcie_ipc_ar.py

# 去重合并:两路结果按 %h 执行 sort -u → 182 条</code></pre>
  <p>关键词刻意避开 "all" 类噪音:检索 <code>allreduce</code> 会命中 89 条、<code>all-reduce</code> 59 条,但其中大量属于 FlashInfer allreduce fusion、AMD aiter 融合算子等模型层融合话题,与 NCCL 通信栈无直接关系,故仅保留能落入上述文件集或 NCCL 语义关键词的合入。</p>

  <div class="stat-grid">
    <div class="stat"><div class="stat-value">182</div><div class="stat-label">NCCL 相关合入(A+B 去重)</div></div>
    <div class="stat"><div class="stat-value">28 个月</div><div class="stat-label">时间跨度(2024-07 → 2026-11)</div></div>
    <div class="stat"><div class="stat-value">8</div><div class="stat-label">主题聚类(另含 35 个工程杂项)</div></div>
    <div class="stat"><div class="stat-value">15</div><div class="stat-label">重点深读 PR(第 5 节)</div></div>
  </div>

  <p>最早的相关合入是 2024-07-16 的 <a href="https://github.com/sgl-project/sglang/pull/631">#631</a>(默认关闭 <code>NCCL_NVLS</code>),最晚是 2026-11-01 的 <a href="https://github.com/sgl-project/sglang/pull/47452">#47452</a>(kimi-k3 residual bank 分片走 NCCL)。按年份分布:</p>

  <div class="chart">
    <div class="chart-row">
      <div class="chart-label">2024 年</div>
      <div class="chart-track"><div class="chart-bar bar-blue" style="width:2%"></div></div>
      <div class="chart-value">3 个</div>
    </div>
    <div class="chart-row">
      <div class="chart-label">2025 年</div>
      <div class="chart-track"><div class="chart-bar bar-green" style="width:37%"></div></div>
      <div class="chart-value">67 个</div>
    </div>
    <div class="chart-row">
      <div class="chart-label">2026 年</div>
      <div class="chart-track"><div class="chart-bar bar-purple" style="width:62%"></div></div>
      <div class="chart-value">112 个</div>
    </div>
  </div>

  <p>对 182 个提交主题做关键词分类(非互斥,一个提交可同时落入多桶),得到类型分布:</p>
  <p>
    <span class="badge b-orange">修复/稳定性 59</span>
    <span class="badge b-blue">特性/支持 26</span>
    <span class="badge b-green">性能优化 20</span>
    <span class="badge b-gray">重构/清理 34</span>
    <span class="badge b-purple">CI/Docker/Doc 14</span>
    <span class="badge b-red">Revert/Reland 11</span>
  </p>
  <div class="callout c-info"><strong>口径说明:</strong>类型桶按 subject 关键词统计(如 fix|bug|revert|deadlock|hang|crash 归"修复",perf|optimi|overhead|latency|warmup 归"性能"),非互斥;主题矩阵(第 2 节)则对 182 个合入逐一人工归类、唯一归属,故 8 个主题 + 35 个工程杂项恰为 182。时间线与主题卡片另经定向检索补充极少量直接相关 PR(如 <a href="https://github.com/sgl-project/sglang/pull/17089">#17089</a>,未触及检索文件集故不在 182 内)。</div>
</section>

<section>
<h2 class="sec" id="sec-2"><span class="num">2</span>全景矩阵:主题 × 时间段</h2>
  <p>下表把 182 个合入按 8 个主题唯一归类,再按自然年切分。格内徽章为该主题该年度的合入数,后接代表性 PR。可以清晰看到三条主线的时间重心:<strong>custom all-reduce 家族</strong>贯穿 2025 全年并在 2026 走向 JIT v2;<strong>NCCL 对称内存与分配器</strong>自 2025-08 引入后持续高频;<strong>CUDA Graph 兼容</strong>在 2026 成为最大的问题解决战场。</p>
  <table class="tbl">
    <tr><th>主题</th><th>2024(3)</th><th>2025(67)</th><th>2026(112)</th></tr>
    <tr>
      <td><strong>A. PyNccl 封装与初始化</strong> <span class="badge b-blue">22</span></td>
      <td><span class="badge b-blue">2</span> <span class="small">#1194 #2244</span></td>
      <td><span class="badge b-blue">6</span> <span class="small">#3010 #5728/#5786 #7418 #13097</span></td>
      <td><span class="badge b-blue">14</span> <span class="small">#20477 #20866 #45503 #17499</span></td>
    </tr>
    <tr>
      <td><strong>B. NCCL 对称内存与分配器</strong> <span class="badge b-purple">27</span></td>
      <td><span class="badge b-gray">0</span></td>
      <td><span class="badge b-purple">9</span> <span class="small">#8238 #11987 #12524 #12715</span></td>
      <td><span class="badge b-purple">18</span> <span class="small">#29007 #29223 #21392 #44681</span></td>
    </tr>
    <tr>
      <td><strong>C. Custom All-Reduce 家族</strong> <span class="badge b-green">35</span></td>
      <td><span class="badge b-gray">0</span></td>
      <td><span class="badge b-green">15</span> <span class="small">#3406 #5080 #8532/#8663 #13710</span></td>
      <td><span class="badge b-green">20</span> <span class="small">#19880 #24363 #31049 #42811</span></td>
    </tr>
    <tr>
      <td><strong>D. 替代后端:MSCCL++ / Torch Symm / Quick AR / PCIe-IPC</strong> <span class="badge b-orange">13</span></td>
      <td><span class="badge b-gray">0</span></td>
      <td><span class="badge b-orange">8</span> <span class="small">#6277 #6619 #10571 #13102</span></td>
      <td><span class="badge b-orange">5</span> <span class="small">#22734 #37442 #31629 #34528</span></td>
    </tr>
    <tr>
      <td><strong>E. CUDA Graph 兼容与捕获</strong> <span class="badge b-red">14</span></td>
      <td><span class="badge b-gray">0</span></td>
      <td><span class="badge b-red">5</span> <span class="small">#10062 #14044/#14278</span></td>
      <td><span class="badge b-red">9</span> <span class="small">#33775 #38936 #40648 #43216</span></td>
    </tr>
    <tr>
      <td><strong>F. 多卡多机稳定性</strong> <span class="badge b-orange">10</span></td>
      <td><span class="badge b-orange">1</span> <span class="small">#631</span></td>
      <td><span class="badge b-orange">4</span> <span class="small">#3502 #3698 #8681</span></td>
      <td><span class="badge b-orange">5</span> <span class="small">#22458 #26923 #30829 #39560</span></td>
    </tr>
    <tr>
      <td><strong>G. DP/EP/CP 场景通信扩展</strong> <span class="badge b-blue">12</span></td>
      <td><span class="badge b-gray">0</span></td>
      <td><span class="badge b-blue">3</span> <span class="small">#4770 #7667 #12065</span></td>
      <td><span class="badge b-blue">9</span> <span class="small">#17288 #24768 #21637 #44029</span></td>
    </tr>
    <tr>
      <td><strong>H. 版本与构建兼容</strong> <span class="badge b-gray">14</span></td>
      <td><span class="badge b-gray">0</span></td>
      <td><span class="badge b-gray">5</span> <span class="small">#7195 #8182 #8359</span></td>
      <td><span class="badge b-gray">9</span> <span class="small">#18987 #35587 #45456 #45576</span></td>
    </tr>
    <tr>
      <td class="muted">工程杂项(lint/配置重构/日志/模型接入触及通信文件)</td>
      <td><span class="badge b-gray">0</span></td>
      <td><span class="badge b-gray">12</span></td>
      <td><span class="badge b-gray">23</span></td>
    </tr>
  </table>
  <div class="callout c-tip"><strong>读图要点:</strong>2024 年只有 3 个合入——通信栈几乎整体"外包"给 torch.distributed 与 vllm 移植代码;2025 年是替代后端的大年(custom AR 15 个、替代后端 8 个);2026 年重心转向"共存治理":按拓扑选择后端、CUDA Graph 兼容、对称内存分配器的工程化(18 个),以及 NPU/AMD/MUSA 等平台的版本兼容。</div>
</section>

<section>
<h2 class="sec" id="sec-3"><span class="num">3</span>里程碑时间线</h2>
  <p>从 182 个合入中筛选出引入新机制、大修、或修复知名问题的关键节点(优先级:新机制 &gt; 大型重构 &gt; 知名问题修复),按四个阶段展开。</p>

  <h3>3.1 奠基期(2024):NVLS 防御与 vllm 分布式模块移植</h3>
  <div class="timeline">
    <div class="timeline-item">
      <div class="timeline-time">2024-07 · #631</div>
      <div class="timeline-body"><span class="timeline-tag">Fix</span><strong>默认关闭 NCCL_NVLS</strong>
        <p>仓库最早的 NCCL 相关合入:启动时设置 <code>NCCL_NVLS_ENABLE=0</code> 规避多卡下 NVLS 引发的稳定性问题,开启此后"环境变量防御"的传统。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2024-08 · #1194</div>
      <div class="timeline-body"><span class="timeline-tag">Refactor</span><strong>清理 nccl init 流程</strong>
        <p>与 readme/示例一起清理 NCCL 初始化代码,通信初始化仍完全依赖 torch.distributed。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2024-12 · #2244</div>
      <div class="timeline-body"><span class="timeline-tag">Feat</span><strong>移植 vllm distributed 模块(3772 行)</strong>
        <p>一次性引入 <span class="filepath">python/sglang/srt/distributed/parallel_state.py</span>(1275 行)、<span class="filepath">device_communicators/pynccl.py</span>(204 行)、<span class="filepath">pynccl_wrapper.py</span>(362 行)、<span class="filepath">custom_all_reduce.py</span>(352 行)、<span class="filepath">shm_broadcast.py</span>(568 行)。SGLang 从此拥有自己的 NCCL ctypes 直连封装(PyNccl),不再只经由 torch.distributed ProcessGroup。</p>
      </div>
    </div>
  </div>

  <h3>3.2 替代后端萌芽(2025 上半年):AR 路线之争</h3>
  <div class="timeline">
    <div class="timeline-item">
      <div class="timeline-time">2025-01 · #2981/#3006</div>
      <div class="timeline-body"><span class="timeline-tag">Revert</span><strong>custom allreduce 一周内切走又切回</strong>
        <p>1-19 加入开关把 vllm custom AR 切到 sgl_kernel 实现,1-20 即回滚,<a href="https://github.com/sgl-project/sglang/pull/3010">#3010</a> 同日同步 vllm 0.6.4.post1 的 distributed 包修正封装层。通信底座的"先移植后自研"路线自此埋下。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025-02 · #3502</div>
      <div class="timeline-body"><span class="timeline-tag">Feat</span><strong>NVLS 可配置(--enable-nccl-nvls)</strong>
        <p>把 #631 的一刀切默认值改为可配置项,供 prefill 重载场景按需打开。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025-03 · #3406</div>
      <div class="timeline-body"><span class="timeline-tag">Feat</span><strong>AMD GPU 启用 custom AR 并迁入 sgl-kernel 维护</strong>
        <p>custom AR 从"仅 NVIDIA vllm kernel"扩展为跨平台内核,AMD 侧由此开始一条平行的 allreduce 演进线(#6097、#13102、#15340、#43809)。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025-06 · #6277</div>
      <div class="timeline-body"><span class="timeline-tag">Feat</span><strong>MSCCL++ 1-shot allreduce 首次集成(+2177 行)</strong>
        <p>新增 <span class="filepath">device_communicators/pymscclpp.py</span> 与 sgl-kernel 内自研 mscclpp_allreduce CUDA kernel,支持单/双节点 1-shot AR,带 <code>--enable-mscclpp</code> 开关与 NCCL 回退。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025-07 · #6619</div>
      <div class="timeline-body"><span class="timeline-tag">Feature</span><strong>quick allreduce + "选择最优 AR 实现"框架</strong>
        <p>引入 quick_all_reduce.py 与首个按输入尺寸选择 AR 实现的启发式框架(AMD),为后来 parallel_state 中的多后端 dispatch 打下地基。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025-07 · #7418</div>
      <div class="timeline-body"><span class="timeline-tag">RL</span><strong>--nccl-port 防端口冲突</strong>
        <p>RL 场景多副本并发启动时 NCCL rendezvous 端口互撞,提供显式端口参数;后续 #18009、#42405 持续打磨默认端口选择策略。</p>
      </div>
    </div>
  </div>

  <h3>3.3 对称内存落地(2025 下半年):NCCL 自身被深度改造</h3>
  <div class="timeline">
    <div class="timeline-item">
      <div class="timeline-time">2025-08 · #8238</div>
      <div class="timeline-body"><span class="timeline-tag">Feat</span><strong>NCCL symmetric memory for TP allreduce</strong>
        <p>NVIDIA 贡献:新增 <span class="filepath">pynccl_allocator.py</span>(ncclMemAlloc + ncclCommWindowRegister)、<code>--enable-symm-mem</code> 开关,PyNcclCommunicator 支持 ncclCommInitRankConfig(graphUsageMode)。TP allreduce 的权重/激活可走对称内存窗口直达对端,跳过 NCCL 协议栈内部拷贝。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025-09 · #10210/#10238</div>
      <div class="timeline-body"><span class="timeline-tag">Revert</span><strong>对称内存一度整体回滚,9 天后恢复</strong>
        <p>稳定性问题导致全量 revert,修复后同日 reland——对称内存此后再未离开主线,但回滚-恢复周期揭示了它的风险面。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025-10 · #10571</div>
      <div class="timeline-body"><span class="timeline-tag">Feat</span><strong>Torch Symm Mem AllReduce(第三条 AR 路线)</strong>
        <p>基于 torch.distributed._symmetric_memory 的 allreduce 后端(symm_mem.py,后于 <a href="https://github.com/sgl-project/sglang/pull/12506">#12506</a> 改名 torch_symm_mem.py),限 SM90/SM100 与特定 world size。三天后 #11381 优化 qwen-vl 即遭遇 revert(#11436)与 reland(#11457),又一次印证新通信后端的高风险。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025-11 · #12524/#12571</div>
      <div class="timeline-body"><span class="timeline-tag">Perf</span><strong>对称内存开销大修与 nccl.h 解耦</strong>
        <p>#12524 重构 allocator(14 文件):激活/权重直接在对称池分配、共享单一 MemPool 防碎片;#12571 移除对 nccl.h 头文件的编译期依赖,allocator 插件不再要求与运行时 NCCL 版本同头。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025-11 · #11987</div>
      <div class="timeline-body"><span class="timeline-tag">Perf</span><strong>多节点 NVLink(MNNVL)放开 NCCL cumem</strong>
        <p>engine 启动逻辑对多节点 NVLink 场景 setdefault NCCL_CUMEM_ENABLE=1,为 GB200/GB300 跨节点 NVLink 铺路——今天 <span class="filepath">python/sglang/srt/entrypoints/engine.py:1922</span> 的 MNNVL 分支即其后裔。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2025-11 · #12572/#12715</div>
      <div class="timeline-body"><span class="timeline-tag">Fix</span><strong>allgather/RS 缓冲注册与 deepgemm 编译 hang</strong>
        <p>#12572 把 allgather/reduce-scatter 缓冲也纳入对称窗口;#12715 修复对称内存开启时 deepgemm JIT 编译 hang——首个"编译期 × 通信内存池"交叠 bug。</p>
      </div>
    </div>
  </div>

  <h3>3.4 多后端生态与 Graph 兼容(2026):治理与自动选择</h3>
  <div class="timeline">
    <div class="timeline-item">
      <div class="timeline-time">2026-03 · #20477</div>
      <div class="timeline-body"><span class="timeline-tag">Perf</span><strong>NCCL/RCCL 预热(--pre-warm-nccl)</strong>
        <p>启动期预热通信器降低 P99 TTFT 冷启动延迟,37 行实现;随后 NPU 侧 #30312、#43039 持续修复其平台初始化顺序。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2026-03 · #19880</div>
      <div class="timeline-body"><span class="timeline-tag">Feat</span><strong>JIT custom all reduce v2(+2154 行)</strong>
        <p>用 JIT 内核基础设施重写 custom AR(push/pull kernel + FFI),新增 <span class="filepath">custom_all_reduce_v2.py</span>;<a href="https://github.com/sgl-project/sglang/pull/24363">#24363</a>(2026-05)将其设为默认。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2026-04 · #20866</div>
      <div class="timeline-body"><span class="timeline-tag">Refactor</span><strong>Remove stream of PyNCCL(净删 52 行)</strong>
        <p>Parallel State Refactor 第 1 步:PyNccl 不再持有专属 stream,统一解析当前设备流。消除了流同步开销与 greenctx(PD-Multiplexing)场景的流错配,是 PyNccl 封装自 #2244 以来最大的一次架构简化。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2026-06 · #22734</div>
      <div class="timeline-body"><span class="timeline-tag">Refactor</span><strong>MSCCL++ Integration:弃自研 kernel,改用上游包</strong>
        <p>删除 sgl-kernel 中 779+140 行自研 mscclpp kernel 与旧测试(-1776 行),pymscclpp.py 重写为直接绑定上游 mscclpp Python 包(398 行新增)。与 #19880 的"JIT 自研"路线形成鲜明对照:生态成熟的上游依赖直接接入。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2026-06 · #27593 / 2026-07 · #31049</div>
      <div class="timeline-body"><span class="timeline-tag">Perf</span><strong>custom AR 支持 VMM 分配 + v2 解耦重写</strong>
        <p>#27593 让 custom AR 缓冲走 CUDA VMM(+713 行,custom_all_reduce_vmm_utils.py);#31049 把 v2 的 kernel 与存储彻底解耦(23 文件,+1916/-1485),支撑后续 #35735 push/pull 分平面与 #42811 2shot_push 调优。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2026-09 · #37442</div>
      <div class="timeline-body"><span class="timeline-tag">Feat</span><strong>MSCCL++ 8 节点 AR/AG + MNVLS 算法</strong>
        <p>pymscclpp.py 扩展至 1276+ 行,把 MSCCL++ 的适用范围从单/双节点推到 8 节点,支持 MNVLS 算法——多机 fabric 上对 NCCL 的又一次正面替代。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2026-09 → 10 · #38936/#40648/#43216</div>
      <div class="timeline-body"><span class="timeline-tag">Fix</span><strong>NCCL graph buffer registration 三连修</strong>
        <p>2026 年最著名的通信问题:NCCL_GRAPH_REGISTER(默认开)注册 graph 捕获集合通信的收发缓冲,在 TP LM-head all-to-all(纯 DP 解码 burst hang)、pausable graph pool(torch_memory_saver 地址重映射)、以及最终确认的"任何多 rank 捕获"场景下引发 ncclDevKernel_SendRecv 永久自旋。#43216 以 41 行防御性默认值收尾,完整叙述见 <span class="filepath">arg_groups/parallel_hook.py:377-431</span>。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">2026-10 · #45503</div>
      <div class="timeline-body"><span class="timeline-tag">Fix</span><strong>阻止不可用的 PyNccl 被启用</strong>
        <p>把 PyNcclCommunicator 的可用性检查前移:世界数为 1、库缺失等场景直接拒绝 enable,并新增 test_pynccl.py 单测。PyNccl 封装在两年后进入"健全性收口"阶段。</p>
      </div>
    </div>
  </div>
</section>

<section>
<h2 class="sec" id="sec-4"><span class="num">4</span>主题深潜:特性支持线与问题解决线</h2>
  <p>以下 8 张卡片对应第 2 节矩阵的 8 个主题,每张梳理"特性支持线"(何时引入、如何演进)与"问题解决线"(修过哪些 hang/性能/兼容问题、典型模式)。</p>

  <div class="grid-2">
    <div class="card">
      <div class="card-title">A. PyNccl 封装与初始化(22 个合入)</div>
      <p><strong>特性支持线:</strong>#2244(2024-12)从 vllm 移植 pynccl.py/pynccl_wrapper.py——ctypes 直接 dlopen libnccl,绕过 torch.distributed 的 Python 层;#3010 同步 vllm 0.6.4.post1;#13097 自动同步 wrapper;#7418/<a href="https://github.com/sgl-project/sglang/pull/18009">#18009</a>/<a href="https://github.com/sgl-project/sglang/pull/42405">#42405</a> 打磨 rendezvous 端口(默认取临时端口范围以下);#20477 启动预热;<a href="https://github.com/sgl-project/sglang/pull/42026">#42026</a> EPLB 场景在 KV cache sizing 前预热默认组 P2P 传输;#17499 MUSA 平台 MTLink 连通性探测。</p>
      <p><strong>问题解决线:</strong>#5728 用 device_id 加速 communicator 创建,一天后即 revert(#5786);#5322 修 broadcast 张量设备与 NCCL 后端不匹配;#11594 PD-Multiplexing greenctx 流;#20866 去掉 PyNccl 专属 stream;#36963 PyNCCL 缺失时回退 process-group broadcast;#45503 拒绝启用不可用实例。</p>
      <p><span class="small">现状:<span class="filepath">pynccl.py:30</span> PyNcclCommunicator 默认 disabled(pynccl.py:141),仅在 CUDA Graph 捕获、预热等场景经 <code>change_state(enable=True)</code>(pynccl.py:417)打开。</span></p>
    </div>
    <div class="card">
      <div class="card-title">B. NCCL 对称内存与分配器(27 个合入)</div>
      <p><strong>特性支持线:</strong>#8238(2025-08)引入 --enable-symm-mem 与 pynccl_allocator.py(ncclMemAlloc 分配 + ncclCommWindowRegister 注册对称窗口);#11987 MNNVL 多节点放开 NCCL_CUMEM_ENABLE;#12524 激活/权重直接在池内分配并共享单一 MemPool;#12572/#17756/#24040 把 allgather、reduce-scatter、CP attention、KV allgather 缓冲逐个纳入窗口;#17089 预分配池;#29007 MoE TP allreduce 经 in-pool 输出分配自动命中对称内存;#29223 draft fc + symm-mem AG。</p>
      <p><strong>问题解决线:</strong>#10210/#10238 全量回滚后恢复;#12715 deepgemm 编译 hang;#17038 OOM 明确报错;#18129 无 dp padding 时强制关闭;#19082 预分配默认值 bug;#24190 绕过 torch.cuda.use_mem_pool 的 generator-CM;#21392 段跟踪与注册解耦;#18569 未注册张量的 debug 栈打印;#44681 watchdog dump 中命名窗口注册;#35538 单 rank 组不再预留 NCCL 设备缓冲;#29100 torch≥2.8 内存池 API 懒加载。</p>
      <p><span class="small">现状:<span class="filepath">pynccl_allocator.py:326</span> SymmetricMemoryContext、:423 use_symmetric_memory;池入口 <span class="filepath">entrypoints/engine.py:1938</span>。</span></p>
    </div>
    <div class="card">
      <div class="card-title">C. Custom All-Reduce 家族(35 个合入)</div>
      <p><strong>特性支持线:</strong>vllm kernel 移植(#2244 → #5079/#5080 由 TRT kernel 换 vllm kernel)→ 迁入 sgl-kernel 维护(#3406,2025-03)→ AMD 适配(#6097/#13102/#15340 deterministic AR)→ JIT v2(#19880,2026-03)→ 默认开启(#24363)→ VMM 分配(#27593)→ kernel/storage 解耦重写(#31049)→ push/pull 分平面(#35735)→ 2shot_push + SM100 重调(#42811)。另有 #13797 的 AR 基准对比框架。</p>
      <p><strong>问题解决线:</strong>#8532/#8642/#8663 NaN 三连(revert-修-reland);#24729 多节点禁用 v2;#24742 非 NVL 场景跟进修复;#25650 full_nvlink 不满足时优雅回退 CustomAllReduce;#35061 按拓扑能力选择 v2;#19162/#20155 graph capture 期间走 unreg 路径;#34543 deterministic AR 拒绝超大输入;#46994 整型 all-reduce 不得走 custom kernel;#46853 移除多节点 VMM allocator gate;#43809 AMD deterministic 模式 TP&gt;2 拒绝 RCCL AR。</p>
      <p><span class="small">现状:v1 <span class="filepath">custom_all_reduce.py</span>(454 行)与 v2 <span class="filepath">custom_all_reduce_v2.py</span>(597 行)并存,dispatch 见 <span class="filepath">parallel_state.py:966</span>。</span></p>
    </div>
    <div class="card">
      <div class="card-title">D. MSCCL++ / Torch Symm Mem / Quick AR / PCIe-IPC(13 个合入)</div>
      <p><strong>特性支持线:</strong>#6277(2025-06)MSCCL++ 首次集成(自研 CUDA kernel);#22734(2026-06)切换到上游 mscclpp Python 包;#37442 扩到 8 节点 + MNVLS;#31629 attention TP 组开启 graph capture 与 MSCCL++;#10571(2025-10)Torch Symm Mem AR → #12506 改名 → #27296 为 Qwen3.5 开启;#6619 quick AR(AMD);#34528 SM120 PCIe-IPC AR(无交换机主机)。</p>
      <p><strong>问题解决线:</strong>#11381/#11436/#11457 qwen-vl symm mem AR 的 revert-reland;#24548 限制 torch symm mem AR 的合法尺寸;#6097 ROCm 上无视 MSCCL 设置强制 custom AR(平台兜底)。</p>
      <p><span class="small">现状:pymscclpp.py 已达 1278 行,是 device_communicators 下仅次于 parallel_state 的第二大通信模块。</span></p>
    </div>
    <div class="card">
      <div class="card-title">E. CUDA Graph 兼容与捕获(14 个合入)</div>
      <p><strong>特性支持线:</strong>#10062(2025-10)Piecewise CUDA Graph 首次把"通信可捕获性"推上前台;#14044 尝试 piecewise 与主 graph 共享全局内存池(后因 #14278 回滚);#33775 capture-safe pynccl all-to-all;#31629 MSCCL++ × graph capture;#23906 graph runner 重构统一捕获路径。</p>
      <p><strong>问题解决线:</strong>#17739 PCG MoE 错误;#19162/#20155 ROCm custom AR 捕获期间走 unreg 路径;#27948 torch memory saver 下跳过 v2 捕获;最终章是 NCCL_GRAPH_REGISTER 三连修 #38936(纯 DP 解码 burst hang)→ #40648(pausable pool)→ #43216(只要图内可能含跨 rank 集合通信即默认关闭注册,41 行)。</p>
      <p><span class="small">根因叙述保留在 <span class="filepath">arg_groups/parallel_hook.py:403-431</span>:NCCL 把图捕获的收发缓冲按图生命周期注册,peers 直接经注册交换;graph pool 地址复用/torch_memory_saver 物理页重映射都会打破该假设。</span></p>
    </div>
    <div class="card">
      <div class="card-title">F. 多卡多机稳定性(10 个合入)</div>
      <p><strong>问题解决线(本主题几乎全是修):</strong>#631 默认关 NVLS → #3502 可配置;#3698 多节点 InfiniBand 设 NCCL_IB_GID_INDEX=3;#8681 修 ncclSystemError 与潜在显存错误;#22458 Qwen3 Next MTP 的 AllGather hang;#24694 diffusion ulysses 序列长度有余数时的 NCCL deadlock;#26923 HiCache writing_check 只在部分 rank 触发 all_reduce 导致死锁——修复方式是让 all_reduce 无条件执行;#30829 EPLB rebalance hang(改用分块 P2P);#39560 scheduler 退出时释放 NCCL 并交由 ASGI server 管理关停顺序。</p>
      <p><span class="small">模式:多机问题集中在"参与条件不对称"与"环境/fabric 假设不成立"两类,修复多为防御性默认值或无条件化。</span></p>
    </div>
    <div class="card">
      <div class="card-title">G. DP/EP/CP 场景通信扩展(12 个合入)</div>
      <p><strong>特性支持线:</strong>#4770(2025-03)DeepEP 下 1≤dp&lt;tp 的 DP attention;#7667 cutlass MoE DP 的 fp4 allgather 前量化;#12065 DeepSeek-V3.2 DSA context parallel;#17288 overlap scheduler 的 NCCL mlp sync batch 开关(SGLANG_NCCL_ALL_GATHER_IN_OVERLAP_SCHEDULER_SYNC_BATCH);#24768 PrefillDelayer 用 NCCL all-gather 做 cross-DP 信息同步;#29972 zigzag CP;#21637 diffusion CP 的 A2A + FlashInfer-MNNVL 后端;#44029 KVShard 0SM KV allgather(经对称窗口);#47567 MiniMax-H3 Ulysses 按 head 组流水;#47452 kimi-k3 residual bank 分片。</p>
      <p><span class="small">这些合入多数不改 NCCL 封装本身,而是把 pynccl/symm-mem 当作可复用的通信原语接入新并行维度——这是"自控通信栈"收益的直接体现。</span></p>
    </div>
    <div class="card">
      <div class="card-title">H. 版本与构建兼容(14 个合入)</div>
      <p><strong>问题解决线:</strong>NCCL 版本链:#5986 仅 cu128 升级 → #7195 docker 镜像缺 2.27.3 → #7787/#8182/#8359 升到 2.27.5/2.27.6 → #18987 NCCL 2.29+ 要求 FlashInfer autotune 走非默认流 → #37508 CI 装依赖后保住 2.30.7 → #45576 RCCL 2.32.3。CUDA 13 链:#17370 nixl-cu13 装错 nvidia-nccl-cu13 → #35587 NCCL_VERSION ARG 与基础镜像 ENV 撞名 → #35756 延迟 NCCL 覆盖到依赖解析之后 → #45456 CUDA 13.4 容器里禁 torch 2.15 nccl2 修 EPLB rebalance crash。另有 #15682 PEP440 版本比较修复(影响 allocator 的 torch≥2.8 判断)。</p>
      <p><span class="small">模式:通信库版本永远与 torch/CUDA/容器基镜像三方耦合,升级窗口期问题集中爆发。</span></p>
    </div>
  </div>
</section>

<section>
<h2 class="sec" id="sec-5"><span class="num">5</span>重点 PR 深读(--stat 摘要)</h2>
  <p>下列 15 个 PR 按"新机制引入 / 大型重构 / 知名问题修复"三个标准选出,规模数字来自 <code>git show --stat</code>:</p>
  <table class="tbl">
    <tr><th>PR</th><th>日期</th><th>类型</th><th>规模</th><th>关键改动</th></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/2244">#2244</a></td><td>2024-12-01</td><td><span class="badge b-blue">Feat</span></td><td>15 文件 +3772</td><td>移植 vllm distributed:parallel_state 1275 行、pynccl.py 204 行、pynccl_wrapper.py 362 行、custom_all_reduce.py 352 行、shm_broadcast.py 568 行</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/3010">#3010</a></td><td>2025-01-20</td><td><span class="badge b-gray">Sync</span></td><td>15 文件 +280/-93</td><td>同步 vllm 0.6.4.post1:pynccl.py +81、wrapper +112,配合 #3006 回滚修正 custom AR 路线</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/6277">#6277</a></td><td>2025-06-05</td><td><span class="badge b-blue">Feat</span></td><td>20 文件 +2177/-12</td><td>MSCCL++ 首次集成:pymscclpp.py 315 行、sgl-kernel 自研 mscclpp_allreduce.cuh 779 行、benchmark/test 全套</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/6619">#6619</a></td><td>2025-07-25</td><td><span class="badge b-blue">Feature</span></td><td>14 文件 +2031/-109</td><td>quick allreduce(AMD):quick_all_reduce.cuh 633 行 + Python 273 行,首个"多 AR 后端择优"框架</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/8238">#8238</a></td><td>2025-08-01</td><td><span class="badge b-blue">Feat</span></td><td>13 文件 +266/-30</td><td>NCCL 对称内存:pynccl_allocator.py 133 行、wrapper +45(ncclMemAlloc/WindowRegister)、deepseek_v2/linear/moe 层接入、--enable-symm-mem</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/10571">#10571</a></td><td>2025-10-06</td><td><span class="badge b-blue">Feat</span></td><td>8 文件 +466/-1</td><td>Torch Symm Mem AllReduce:symm_mem.py 164 行 + benchmark 234 行,SM90/SM100 限定</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/12524">#12524</a></td><td>2025-11-03</td><td><span class="badge b-green">Perf</span></td><td>14 文件 +219/-154</td><td>对称内存降开销:fp8/mxfp4/modelopt 量化层、linear、moe、deepseek_v2 全部改为池内分配;共享 MemPool</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/19880">#19880</a></td><td>2026-03-20</td><td><span class="badge b-blue">Feat</span></td><td>16 文件 +2154/-96</td><td>JIT custom AR v2:push/pull kernel + FFI 104 行、custom_all_reduce_v2.py 189 行、bench 377 行</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/20866">#20866</a></td><td>2026-04-03</td><td><span class="badge b-gray">Refactor</span></td><td>2 文件 +34/-86</td><td>Remove stream of PyNCCL:PyNccl 不再持有专属流,净删 52 行,统一走当前设备流</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/22734">#22734</a></td><td>2026-06-08</td><td><span class="badge b-gray">Refactor</span></td><td>17 文件 +398/-1776</td><td>MSCCL++ Integration:删自研 CUDA kernel(-1776),pymscclpp.py 重写为上游 mscclpp 包绑定</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/27593">#27593</a></td><td>2026-06-16</td><td><span class="badge b-green">Perf</span></td><td>7 文件 +713/-7</td><td>custom AR 支持 VMM 分配:custom_all_reduce_vmm_utils.py 579 行</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/31049">#31049</a></td><td>2026-07-17</td><td><span class="badge b-gray">Rewrite</span></td><td>23 文件 +1916/-1485</td><td>AR v2 解耦重写:communicator.cuh/ipc.cuh 新设计、configs/custom_all_reduce_v2.py 194 行拓扑配置</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/37442">#37442</a></td><td>2026-09-24</td><td><span class="badge b-blue">Feat</span></td><td>8 文件 +1452/-244</td><td>MSCCL++ 8 节点 AR/AG + MNVLS:pymscclpp.py 净增约 1200 行</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/43216">#43216</a></td><td>2026-10-22</td><td><span class="badge b-orange">Fix</span></td><td>2 文件 +96/-24</td><td>图内含跨 rank 集合通信时默认关闭 NCCL graph buffer registration,含 79 行参数解析单测</td></tr>
    <tr><td><a href="https://github.com/sgl-project/sglang/pull/45503">#45503</a></td><td>2026-10-28</td><td><span class="badge b-orange">Fix</span></td><td>9 文件 +195/-44</td><td>阻止不可用 PyNccl 被启用:require_pynccl_comm 化、bootstrap/parallel_state 收口、test_pynccl.py 126 行</td></tr>
  </table>

  <p>三个值得展开的样本:</p>
  <div class="card">
    <div class="card-title">#8238:一次引入即触及模型层</div>
    <p>这不是一个孤立的"device_communicators 内部" PR:为了让 TP allreduce 真正命中对称内存,<span class="filepath">layers/linear.py</span>、<span class="filepath">layers/moe/fused_moe_triton/layer.py</span>、<span class="filepath">models/deepseek_v2.py</span>、<span class="filepath">model_executor/cuda_graph_runner.py</span> 都被改造为在 <code>use_symmetric_memory()</code> 上下文中分配输出。这奠定了 SGLang 对称内存的实现风格:<strong>由使用侧保证张量落在注册窗口内,而非在通信前拷贝</strong>。#12524 后该模式扩展到 fp8/mxfp4 量化层,#29007 又把 MoE TP allreduce 的输出改为池内分配以自动命中。</p>
  </div>
  <div class="card">
    <div class="card-title">#22734:自研 kernel 与上游依赖的取舍</div>
    <p>与 #19880(JIT 自研 AR v2)仅隔三个月,#22734 却走向相反方向:删掉 sgl-kernel 里自研的 mscclpp CUDA kernel(-1776 行),直接绑定上游 MSCCL++ Python 包。判断依据是生态成熟度——MSCCL++ 上游本身持续演进(#37442 随后以纯 Python 侧改动拿到 8 节点与 MNVLS 能力),自研镜像只会成为负担。两条路线并存至今:性能关键、SGLang 独有的 custom AR 自研;标准化程度高的协议栈用上游。</p>
  </div>
  <div class="card">
    <div class="card-title">#43216:41 行修复收掉一个季度的问题</div>
    <p>#38936 修 TP LM-head all-to-all 的纯 DP 解码 hang 时,还只敢针对该特征关闭注册;#40648 补上 pausable graph pool(torch_memory_saver resume 换物理页但 NCCL 注册仍指向旧页,见 fzyzcjy/torch_memory_saver#88);#43216 承认根因(图池地址复用)无法在 NCCL 侧闭环,改为"只要多 rank 捕获图存在就默认 <code>NCCL_GRAPH_REGISTER=0</code>",并在 docstring 中完整记录了 tp4/dp4/ep4 与多节点 tp16/dp16/ep16 的复现路径(<span class="filepath">arg_groups/parallel_hook.py:403-431</span>)。</p>
  </div>
</section>

<section>
<h2 class="sec" id="sec-6"><span class="num">6</span>配置项与开关的演进痕迹</h2>
  <p>八个主题的演进最终沉淀为以下用户可见配置(当前默认值,来自 <span class="filepath">arg_groups/fields/parallel.py</span> 与 <span class="filepath">arg_groups/fields/exec_.py</span>):</p>
  <table class="tbl">
    <tr><th>参数</th><th>默认值</th><th>说明(引入背景)</th></tr>
    <tr><td><code>nccl_port</code></td><td>None(随机,取临时端口范围以下)</td><td>NCCL 分布式初始化端口;#7418 为 RL 多副本引入,#42405 改默认避开内核临时端口范围(fields/parallel.py:29)</td></tr>
    <tr><td><code>enable_nccl_nvls</code></td><td>False</td><td>prefill 重载请求可用时启用 NVLS;#631 默认关 → #3502 提为参数(exec_.py:722)</td></tr>
    <tr><td><code>enable_symm_mem</code></td><td>False</td><td>NCCL 对称内存快速集合通信;#8238 引入,torch≥2.8 且 CUDA/HIP 可用(exec_.py:725)</td></tr>
    <tr><td><code>disable_custom_all_reduce</code></td><td>False</td><td>禁用 custom AR 内核、回退 NCCL;#1148(2024-08)引入的最早 AR 开关(exec_.py:732)</td></tr>
    <tr><td><code>enable_mscclpp</code></td><td>False</td><td>MSCCL++ 调优 AR/AG,NCCL 回退;#6277 引入(exec_.py:739)</td></tr>
    <tr><td><code>enable_torch_symm_mem</code></td><td>False</td><td>torch symm mem AR;#10571 引入,SM90 限 ws 4/6/8、SM100 限 6/8(exec_.py:743)</td></tr>
    <tr><td><code>pre_warm_nccl</code></td><td>False(AMD/HIP 默认开)</td><td>启动预热 NCCL/RCCL 降 P99 TTFT;#20477 引入(exec_.py:751)</td></tr>
  </table>
  <p>以及若干环境变量(<span class="filepath">python/sglang/srt/environ.py</span> 与启动钩子):</p>
  <table class="tbl">
    <tr><th>环境变量</th><th>默认值</th><th>说明</th></tr>
    <tr><td><code>NCCL_CUMEM_ENABLE</code></td><td>按场景 setdefault "1"</td><td>MNNVL 多节点 / KV-shard 对称 scratch / --enable-symm-mem 时置 1;#11987 开启此策略(engine.py:1922-1945)</td></tr>
    <tr><td><code>NCCL_GRAPH_REGISTER</code></td><td>"0"(图内含跨 rank 通信时)</td><td>#38936/#40648/#43216 的最终防御;显式设置优先(parallel_hook.py:426)</td></tr>
    <tr><td><code>SGLANG_SYMM_MEM_PREALLOC_GB_SIZE</code></td><td>-1(--enable-symm-mem 时默认 4)</td><td>对称池预分配大小;#17089 引入(environ.py:2282)</td></tr>
    <tr><td><code>SGLANG_OPT_USE_CUSTOM_ALL_REDUCE_V2</code></td><td>True</td><td>选择 custom AR v2;#24297 更名、#24363 默认 True(environ.py:1598)</td></tr>
    <tr><td><code>SGLANG_NCCL_ALL_GATHER_IN_OVERLAP_SCHEDULER_SYNC_BATCH</code></td><td>False</td><td>overlap scheduler 的 NCCL mlp sync batch;#17288 引入(environ.py:754)</td></tr>
    <tr><td><code>SGLANG_DETERMINISTIC_NCCL_NCHANNELS</code></td><td>8</td><td>deterministic 推理固定 NCCL 通道数(environ.py:1597)</td></tr>
    <tr><td><code>SGLANG_DEBUG_SYMM_MEM</code></td><td>False</td><td>对称内存 debug 栈打印;#18569 引入(environ.py:2283)</td></tr>
  </table>
</section>

<section>
<h2 class="sec" id="sec-7"><span class="num">7</span>修复问题模式总结</h2>
  <div class="callout c-danger"><strong>Hang/Deadlock 类(最危险,贯穿始终):</strong>182 个合入的 subject 中含 hang/deadlock/stall 字样的有 11 个,若加上 revert 类则更多。归纳出四个反复出现的模式:(1)<strong>参与条件不对称</strong>——各 rank 对"是否进入集合通信"的判断分支不一致,如 #26923(HiCache writing_check 只在部分 rank 为真,修复是 all_reduce 无条件化)、#22458(MTP 前置条件分歧)、#24694(ulysses 余数);(2)<strong>graph 捕获 × 缓冲注册</strong>——#38936/#40648/#43216,NCCL 对图内集合通信的缓冲注册经不起图池地址复用与物理页重映射;(3)<strong>编译期 × 通信内存池</strong>——#12715 deepgemm JIT 编译在 symm 池激活时 hang;(4)<strong>生命周期错位</strong>——#39560 scheduler 退出顺序。经验法则:修 hang 的 PR 几乎都伴随"防御性默认值"或"无条件化",而非定位到根因后再精准修复。</div>
  <div class="callout c-warn"><strong>兼容类(平台与版本三方耦合):</strong>NCCL 版本(2.27.3 缺失 #7195、2.29+ 与 FlashInfer autotune 流冲突 #18987、CI 保 2.30.7 #37508)、CUDA 13 容器链(#17370/#35587/#35756)、torch 2.15 nccl2 与 EPLB(#45456)、torch≥2.8 内存池 API(#29100、#15682)、nccl.h 头文件依赖(#12571)。通信库从不单独升级,永远与 torch/CUDA/基镜像联动,升级窗口期是问题高发期。</div>
  <div class="callout c-tip"><strong>性能类(三条收益来源):</strong>(1)<strong>消除同步开销</strong>——#27089 对称内存下禁用 NCCL 内部 CUDA event 同步、#20866 去掉 PyNccl 专属流、#20477 预热消除冷启动;(2)<strong>绕过协议栈</strong>——对称内存窗口直达对端(#8238/#12524)、custom AR 一/二 shot(#42811)、MSCCL++ 1-shot(#6277);(3)<strong>降低通信量</strong>——#7667 allgather 前 fp4 量化、#22642 用 reduce_scatterv 替代 AR+scatter、#26970 复制 embed_tokens 免 post-embed AR。</div>
  <div class="callout c-info"><strong>显存类(分配器的独特问题域):</strong>#17038 OOM 时给出指向对称池的明确报错、#17089 预分配防碎片、#35538 单 rank 组不预留 NCCL 设备缓冲、#34842 GB 上 symm-mem×CUDA graph 禁用的反复。对称内存把"通信缓冲"与"常规张量"放进同一个 MemPool,因此显存碎片、图池、内存池 API 版本都成为它的直接问题面。</div>
</section>

<section>
<h2 class="sec" id="sec-8"><span class="num">8</span>小结:NCCL 在 SGLang 通信栈中的角色演进</h2>
  <p>把 182 个合入压缩成一条主线,SGLang 的 NCCL 角色经历了三个阶段:</p>
  <div class="flow">
    <div class="node">torch.distributed<small>2024:PG 全托管 + 环境变量防御</small></div><div class="arrow">→</div>
    <div class="node node-accent">PyNccl 自控封装<small>2024-12 #2244:ctypes 直连 + CUDA Graph 就绪</small></div><div class="arrow">→</div>
    <div class="node node-accent">NCCL 深度改造<small>2025:对称内存 + allocator + cumem</small></div><div class="arrow">→</div>
    <div class="node">多后端并存生态<small>2025→2026:AR v2 / MSCCL++ / torch symm / quick AR / PCIe-IPC</small></div>
  </div>
  <p>第一阶段(2024):通信完全交给 torch.distributed,仓库里只有环境变量级的防御(#631、#1194),7 个月内仅 3 个相关合入。</p>
  <p>第二阶段(2024-12 → 2025):#2244 移植 vllm distributed 后,SGLang 获得了 PyNccl 这个"可编程的 NCCL 句柄"——最初动机是 CUDA Graph 捕获需要直接操作 stream 与 comm(pynccl.py:141-144 的注释至今保留"默认 disabled,CUDA Graph 时再开"的设计)。2025 年它进一步成为新机制的载体:对称内存(#8238)、cumem(#11987)、预热(#20477)都长在 PyNccl 之上。</p>
  <p>第三阶段(2025-06 起至今):custom AR(v1→JIT v2)、MSCCL++、torch symm mem、quick AR、PCIe-IPC 相继入场,NCCL 从"唯一后端"降格为"默认后端 + 回退目标 + 对称内存提供者"。今天的调度逻辑是这一生态的终点形态——<span class="filepath">parallel_state.py:771-780</span> 先判对称内存直通,再走 FlashInfer 融合;不命中则进入 <code>_resolve_outplace_all_reduce_method</code>(parallel_state.py:966-1013)按 <code>pymscclpp → ca(custom AR v2)→ pcie_ipc → qr(quick AR)→ torch_symm_mem → pynccl</code> 的拓扑/尺寸启发式择优:</p>
  <pre class="code"><code># parallel_state.py:966-1013(择优顺序节选)
if ca_comm is not None and not ca_comm.disabled \
        and not should_use_pymscclpp_allreduce \
        and ca_comm.should_custom_ar(input_):
    return "ca"
if pcie_ipc_comm is not None and not pcie_ipc_comm.disabled \
        and not should_use_pymscclpp_allreduce \
        and pcie_ipc_comm.should_pcie_ipc_ar(input_):
    return "pcie_ipc"
if qr_comm is not None and not qr_comm.disabled \
        and qr_comm.should_quick_allreduce(input_):
    return "qr"
if self.pymscclpp_comm is not None and should_use_pymscclpp_allreduce:
    return "pymscclpp"
if self.torch_symm_mem_comm is not None ...:
    return "torch_symm_mem"
if is_in_tc_piecewise_cuda_graph() and self.get_available_pynccl_comm():
    return "pynccl"   # piecewise 图内固定用 PyNccl 的 outplace AR</code></pre>
  <p>三个观察作为收束:<strong>其一</strong>,问题与能力成正比——修复/稳定性类合入占 59/182,其中 11 个 revert/reland 几乎全部落在通信路径上,每个新后端(torch symm mem、symm mem 优化、custom AR v2)都经历过回滚;通信是 SGLang 中试错成本最高的子系统。<strong>其二</strong>,2026 年的重心从"加后端"转向"治理共存":按拓扑自动选择(#35061/#44642)、防御性默认值(#43216/#45503)、生命周期收口(#39560)。<strong>其三</strong>,PyNccl 本体在收缩(#20866 净删 52 行、#45503 健全性收口),而围绕它的 allocator(535 行)与 pymscclpp(1278 行)在膨胀——NCCL 在 SGLang 中的未来角色,是一个被精细管理的"默认底座",其上叠放着越来越多的专用快速路径。</p>
  <p><strong>延伸阅读:</strong>NCCL 在当前代码中的使用位置与调用链见本系列<a href="/docs/inference-engines/sglang/11-nccl-usage/">第 12 篇(NCCL 使用场景全景)</a>;并行组与 dispatch 的架构背景见<a href="/docs/inference-engines/sglang/03-parallelism/">第 4 篇(并行策略)</a>;CUDA Graph 捕获机制见<a href="/docs/inference-engines/sglang/05-cuda-graph/">第 6 篇</a>。</p>
</section>

  <div class="pgnav">
    <span>SGLang 深度解析系列 · ⑫ NCCL 相关 PR 历史 · 源码级分析基于 main @ b146a8576d · ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/sglang/11-nccl-usage/">← NCCL 使用场景全景</a> &nbsp;·&nbsp; <a href="/docs/inference-engines/sglang/13-cross-card-comm/">跨卡通信行为全景 →</a> &nbsp;·&nbsp; <a href="/docs/inference-engines/sglang/">返回总览</a></span>
  </div>
<script>
(function(){
// 滚动显现
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)});
// ===== 动画场景播放控制(暂停/重播/倍速) =====
function mkBtn(t){var b=document.createElement('button');b.type='button';b.textContent=t;return b}
function setRate(sc,rate){
  var els=sc.querySelectorAll('*');
  for(var i=0;i<els.length;i++){
    var el=els[i];
    if(el.classList&&el.classList.contains('scene-bar'))continue;
    var cs=window.getComputedStyle(el);
    if(!cs.animationDuration||cs.animationDuration==='0s')continue;
    if(!el.getAttribute('data-base-dur'))el.setAttribute('data-base-dur',cs.animationDuration);
    if(!el.getAttribute('data-base-del'))el.setAttribute('data-base-del',cs.animationDelay);
    el.style.animationDuration=(parseFloat(el.getAttribute('data-base-dur'))/rate)+'s';
    el.style.animationDelay=(parseFloat(el.getAttribute('data-base-del'))/rate)+'s';
  }
}
function initScene(sc){
  if(sc.getAttribute('data-anim-init'))return;
  sc.setAttribute('data-anim-init','1');
  var bar=document.createElement('div');bar.className='scene-bar';
  var bp=mkBtn('\u23F8 暂停');
  bp.addEventListener('click',function(){
    var p=sc.classList.toggle('paused');
    bp.textContent=p?'\u25B6 播放':'\u23F8 暂停';
    bp.classList.toggle('on',p);
  });
  var br=mkBtn('\u21BA 重播');
  br.addEventListener('click',function(){
    sc.classList.remove('paused');bp.textContent='\u23F8 暂停';bp.classList.remove('on');
    sc.classList.add('hold');void sc.offsetWidth;sc.classList.remove('hold');
  });
  var sps=[];
  [['0.5\u00D7',0.5],['1\u00D7',1],['2\u00D7',2]].forEach(function(s){
    var b=mkBtn(s[0]);b.setAttribute('data-rate',String(s[1]));
    if(s[1]===1)b.classList.add('on');
    b.addEventListener('click',function(){
      for(var k=0;k<sps.length;k++)sps[k].classList.remove('on');
      b.classList.add('on');setRate(sc,s[1]);
    });
    sps.push(b);
  });
  bar.appendChild(bp);bar.appendChild(br);
  for(var j=0;j<sps.length;j++)bar.appendChild(sps[j]);
  sc.appendChild(bar);
}
var ss=document.querySelectorAll('.scene');
for(var i=0;i<ss.length;i++)initScene(ss[i]);
})();
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>跨卡通信全景:通信行为与底层通信库</title><link>https://hccl.club/docs/inference-engines/sglang/13-cross-card-comm/</link><pubDate>Sun, 08 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/sglang/13-cross-card-comm/</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:30px;
  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:2px;margin-bottom:12px}
.fwdoc .hero h1{font-size:33px;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 .hero h1 .cursor{display:inline-block;width:10px;height:28px;vertical-align:-3px;margin-left:6px;border-radius:2px;
  background:var(--accent2);animation:curblink 1.1s steps(1) infinite}
.fwdoc .statrow{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px;margin-top:26px}
.fwdoc .statrow .stat{background:rgba(20,29,51,.72);border:1px solid var(--border);border-radius:12px;padding:14px 18px;text-align:center;backdrop-filter:blur(4px)}
.fwdoc .statrow .stat .v{font-size:26px;font-weight:800;color:#fff;font-family:Consolas,monospace}
.fwdoc .statrow .stat .v .u{font-size:13px;color:var(--accent2);margin-left:2px}
.fwdoc .statrow .stat .k{font-size:12px;color:var(--muted);margin-top:2px}
.fwdoc .klabel{font-size:11px;color:#5a6b92;letter-spacing:1px;text-transform:uppercase;margin-bottom:10px}
.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 .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 p{margin:10px 0;color:var(--text);font-size:14.5px}
.fwdoc ul{list-style:disc;padding-left:26px;margin:10px 0}
.fwdoc ol{list-style:decimal;padding-left:26px;margin:10px 0}
.fwdoc li{margin:6px 0}
.fwdoc h3{font-size:18.5px;color:#fff;margin:28px 0 10px}
.fwdoc h3.sub{border-left:3px solid var(--accent);padding-left:12px}
.fwdoc h4{font-size:15.5px;color:#e6ecf9;margin:20px 0 8px}
.fwdoc h5{font-size:14px;color:var(--muted);margin:14px 0 6px}
.fwdoc a{color:var(--accent2)}
.fwdoc a:hover{text-decoration:underline}
.fwdoc hr{border:0;border-top:1px dashed #2a3a5c;margin:26px 0}
.fwdoc strong{color:#fff;font-weight:700}
.fwdoc blockquote{border-left:3px solid var(--accent);padding:6px 16px;margin:14px 0;color:var(--muted)}
.fwdoc code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:.88em}
.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 8px}
.fwdoc .tag{display:inline-block;background:rgba(79,140,255,.12);color:var(--accent2);border-radius:6px;
  padding:2px 9px;font-size:12px;font-weight:600;margin:2px 4px 2px 0}
.fwdoc .muted{color:var(--muted)}
.fwdoc .small{font-size:12.5px}
.fwdoc .two-col{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@media(max-width:800px){.fwdoc .two-col{grid-template-columns:1fr}}
.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 code{background:transparent;padding:0;color:#cfe0f5;font-size:inherit}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border);display:block;overflow-x:auto}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px;white-space:nowrap}
.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 .grid-2{display:grid;gap:16px;grid-template-columns:repeat(auto-fit,minmax(320px,1fr))}
.fwdoc .grid-3{display:grid;gap:16px;grid-template-columns:repeat(auto-fit,minmax(240px,1fr))}
.fwdoc .grid-2 .card,.fwdoc .grid-3 .card{margin:0}
.fwdoc .card-title{font-size:16.5px;color:#fff;font-weight:700;margin:0 0 8px}
.fwdoc .stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:14px;margin:20px 0}
.fwdoc .stat-grid .stat{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:12px;padding:16px 12px;text-align:center}
.fwdoc .stat-value{font-size:27px;font-weight:800;color:#fff}
.fwdoc .stat-label{font-size:12px;color:var(--muted);margin-top:4px}
.fwdoc .callout{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13.5px;margin:16px 0}
.fwdoc .callout p{margin:6px 0}
.fwdoc .callout.c-info{border-left-color:var(--accent)}
.fwdoc .callout.c-tip{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .callout.c-warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .callout.c-danger{border-left-color:var(--bad);background:rgba(248,113,113,.06)}
.fwdoc .callout strong{color:#fff}
.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 .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px;margin:0 5px 4px 0}
.fwdoc .badge.b-blue{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.b-green{background:rgba(52,211,153,.12);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.b-orange{background:rgba(251,146,60,.12);color:#fb923c;border:1px solid rgba(251,146,60,.4)}
.fwdoc .badge.b-red{background:rgba(248,113,113,.12);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.b-gray{background:rgba(142,160,194,.12);color:var(--muted);border:1px solid rgba(142,160,194,.35)}
.fwdoc .badge.b-purple{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .toc{background:rgba(20,29,51,.6);border:1px solid var(--border);border-radius:12px;padding:16px 22px;margin:0 0 30px}
.fwdoc .toc-title{font-size:12.5px;font-weight:700;color:var(--muted);letter-spacing:2px;margin-bottom:8px}
.fwdoc .toc ol,.fwdoc .toc ul{columns:2;column-gap:28px;margin:0;padding-left:20px}
.fwdoc .toc li{margin:4px 0;font-size:13.5px;break-inside:avoid}
.fwdoc .toc a{color:var(--text);text-decoration:none}
.fwdoc .toc a:hover{color:var(--accent2)}
@media(max-width:800px){.fwdoc .toc ol,.fwdoc .toc ul{columns:1}}
.fwdoc .timeline{position:relative;padding-left:28px;margin:20px 0}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .timeline-item{position:relative;margin-bottom:24px}
.fwdoc .timeline-item::before{content:"";position:absolute;left:-24px;top:6px;width:11px;height:11px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.15);animation:fw-tlpulse 2.4s infinite}
@keyframes fw-tlpulse{0%,100%{opacity:.55}50%{opacity:1}}
.fwdoc .timeline-time{font-size:12px;color:var(--accent2);font-weight:700;font-family:Consolas,monospace}
.fwdoc .timeline-body{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:10px;padding:12px 16px;margin-top:6px}
.fwdoc .timeline-body p{margin:6px 0 0;font-size:13.5px}
.fwdoc .timeline-tag{display:inline-block;font-size:11px;font-weight:700;padding:1px 8px;border-radius:4px;
  background:rgba(79,140,255,.14);color:var(--accent2);margin-left:8px;vertical-align:1px}
.fwdoc .flow{display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin:18px 0}
.fwdoc .flow-v{display:flex;flex-direction:column;align-items:flex-start;gap:6px;margin:18px 0}
.fwdoc .flow .node,.fwdoc .flow-v .node{background:#101a2d;border:1.5px solid #3a5a8c;border-radius:9px;
  padding:8px 13px;font-size:13.5px;font-weight:600;color:#e6eefb}
.fwdoc .flow .node small,.fwdoc .flow-v .node small{display:block;font-weight:400;color:var(--muted);font-size:11.5px;margin-top:2px}
.fwdoc .node-accent{border-color:var(--accent) !important;background:rgba(79,140,255,.12) !important;color:#cfe4ff !important}
.fwdoc .arrow{color:#7d9ac4;font-size:19px;font-weight:700;line-height:1}
.fwdoc .arrow-v{color:#7d9ac4;font-size:17px;font-weight:700;padding-left:16px}
.fwdoc .chart{margin:20px 0}
.fwdoc .chart-row{display:grid;grid-template-columns:230px 1fr 70px;gap:10px;align-items:center;margin:8px 0;font-size:13.5px}
.fwdoc .chart-label{text-align:right;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.fwdoc .chart-track{background:rgba(10,16,32,.85);border-radius:6px;height:20px;overflow:hidden}
.fwdoc .chart-bar{height:100%;border-radius:6px 0 0 6px;background:var(--accent);min-width:2px}
.fwdoc .bar-blue{background:var(--accent)}
.fwdoc .bar-green{background:var(--good)}
.fwdoc .bar-orange{background:#fb923c}
.fwdoc .bar-red{background:var(--bad)}
.fwdoc .bar-purple{background:var(--purple)}
.fwdoc .bar-gray{background:#64748b}
.fwdoc .chart-value{font-family:Consolas,monospace;font-size:12px;color:var(--muted)}
.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:.1s}
.fwdoc .reveal.d2{transition-delay:.2s}
.fwdoc .reveal.d3{transition-delay:.3s}
.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 .pgnav a:hover{text-decoration:underline}
.fwdoc .scene{--T:6s;position:relative;background:radial-gradient(1100px 420px at 18% -12%,#16273f 0%,#0d1729 55%,#0a0f1c 100%);
  border:1px solid var(--border);border-radius:var(--radius);padding:20px 22px 18px;min-height:200px;
  color:#d7e3f4;overflow:hidden;margin:20px 0 8px}
.fwdoc .scene .sc-title{position:absolute;top:12px;left:16px;font-size:12.5px;font-weight:700;color:#8fa7c9;letter-spacing:.05em}
.fwdoc .scene .sc-hint{position:absolute;bottom:10px;right:14px;font-size:11px;color:#5d7396}
.fwdoc .scene .row{display:flex;align-items:center;gap:14px;flex-wrap:wrap}
.fwdoc .scene .col{display:flex;flex-direction:column;gap:12px;align-items:flex-start}
.fwdoc .scene .cen{justify-content:center;align-items:center}
.fwdoc .scene .stack{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px}
.fwdoc .scene .trow{display:flex;gap:4px;flex-wrap:wrap;align-items:center}
.fwdoc .scene .abs{position:absolute}
.fwdoc .scene .mt{margin-top:30px}
.fwdoc .scene .lbl{font-size:11.5px;color:#7d92b4;font-weight:600}
.fwdoc .scene .big{font-size:19px;font-weight:800;color:#eaf2ff}
.fwdoc .scene .dim{opacity:.42}
.fwdoc .scene .gpu{background:#101a2d;border:1.5px solid #31507e;border-radius:10px;padding:9px 14px;min-width:78px;
  text-align:center;font-weight:700;font-size:14px;color:#e6eefb}
.fwdoc .scene .gpu small{display:block;font-weight:400;color:#7d92b4;font-size:11.5px;margin-top:2px}
.fwdoc .scene .node{background:#101a2d;border:1.5px solid #3a5a8c;border-radius:10px;padding:8px 13px;text-align:center;
  font-weight:700;font-size:13.5px;color:#e6eefb}
.fwdoc .scene .node small{display:block;font-weight:400;color:#7d92b4;font-size:11.5px;margin-top:2px}
.fwdoc .scene .srv{border:1.5px solid #3b6ea5;border-radius:12px;padding:12px 14px;background:rgba(16,26,45,.78);min-width:170px}
.fwdoc .scene .srv-head{font-weight:800;color:#bfe0ff;font-size:13.5px;margin-bottom:8px}
.fwdoc .scene .zone{border:1.5px dashed #3a5b8f;border-radius:10px;padding:10px 12px}
.fwdoc .scene .bub{width:36px;height:36px;border-radius:50%;background:#16233c;border:1.5px solid #3a5a8c;
  display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#cfe0f7}
.fwdoc .scene .tok{width:16px;height:16px;border-radius:4px;background:#3a4a63;display:inline-block}
.fwdoc .scene .tok.a{background:#3b82f6}
.fwdoc .scene .tok.b{background:#22c55e}
.fwdoc .scene .tok.c{background:#f59e0b}
.fwdoc .scene .tok.d{background:#a78bfa}
.fwdoc .scene .tok.e{background:#f472b6}
.fwdoc .scene .kv{width:22px;height:14px;border-radius:3px;background:#3a4a63;display:inline-block}
.fwdoc .scene .bar{height:14px;border-radius:4px;background:#3b82f6;min-width:70px;transform-origin:left center}
.fwdoc .scene .bar.g{background:#22c55e}
.fwdoc .scene .bar.o{background:#f59e0b}
.fwdoc .scene .bar.r{background:#ef4444}
.fwdoc .scene .wire{height:2px;flex:none;min-width:40px;background:repeating-linear-gradient(90deg,#3f6db3 0 8px,transparent 8px 16px);animation:fw-k-flow .9s linear infinite}
.fwdoc .scene .wire.v{width:2px;min-width:0;height:auto;align-self:stretch;min-height:34px;
  background:repeating-linear-gradient(180deg,#3f6db3 0 8px,transparent 8px 16px);animation:fw-k-flowv .9s linear infinite}
.fwdoc .scene .pkt{position:absolute;width:12px;height:12px;border-radius:50%;background:#38bdf8;box-shadow:0 0 12px rgba(56,189,248,.8)}
.fwdoc .scene .pkt.g{background:#34d399;box-shadow:0 0 12px rgba(52,211,153,.8)}
.fwdoc .scene .pkt.o{background:#fb923c;box-shadow:0 0 12px rgba(251,146,60,.8)}
.fwdoc .scene .pkt.r{background:#f87171;box-shadow:0 0 12px rgba(248,113,113,.8)}
.fwdoc .scene .pkt.v{background:#a78bfa;box-shadow:0 0 12px rgba(167,139,250,.8)}
.fwdoc .scene .mv{animation:fw-k-mv var(--T) linear infinite}
.fwdoc .scene .pop{animation:fw-k-pop var(--T) ease-in-out infinite}
.fwdoc .scene .fadein{animation:fw-k-fadein var(--T) ease-in-out infinite}
.fwdoc .scene .hit{animation:fw-k-on var(--T) ease-in-out infinite}
.fwdoc .scene .hit.o{animation-name:fw-k-on-o}
.fwdoc .scene .hit.r{animation-name:fw-k-on-r}
.fwdoc .scene .hit.b{animation-name:fw-k-on-b}
.fwdoc .scene .ok{animation:fw-k-ok var(--T) ease-in-out infinite}
.fwdoc .scene .no{animation:fw-k-no var(--T) ease-in-out infinite}
.fwdoc .scene .pulse{animation:fw-k-pulse 1.8s ease-in-out infinite}
.fwdoc .scene .glow{animation:fw-k-glow 2.4s ease-in-out infinite}
.fwdoc .scene .grow{animation:fw-k-grow var(--T) ease-in-out infinite;transform-origin:left center}
.fwdoc .scene .alt{animation-direction:alternate}
.fwdoc .scene .svgflow{stroke-dasharray:5 9;animation:fw-k-dash 1.1s linear infinite}
.fwdoc .scene .d1{animation-delay:calc(var(--T)*.04)}
.fwdoc .scene .d2{animation-delay:calc(var(--T)*.08)}
.fwdoc .scene .d3{animation-delay:calc(var(--T)*.12)}
.fwdoc .scene .d4{animation-delay:calc(var(--T)*.16)}
.fwdoc .scene .d5{animation-delay:calc(var(--T)*.20)}
.fwdoc .scene .d6{animation-delay:calc(var(--T)*.24)}
.fwdoc .scene .d7{animation-delay:calc(var(--T)*.28)}
.fwdoc .scene .d8{animation-delay:calc(var(--T)*.32)}
.fwdoc .scene .d9{animation-delay:calc(var(--T)*.36)}
.fwdoc .scene .d10{animation-delay:calc(var(--T)*.40)}
.fwdoc .scene .d11{animation-delay:calc(var(--T)*.44)}
.fwdoc .scene .d12{animation-delay:calc(var(--T)*.48)}
.fwdoc .scene .d13{animation-delay:calc(var(--T)*.52)}
.fwdoc .scene .d14{animation-delay:calc(var(--T)*.56)}
.fwdoc .scene .d15{animation-delay:calc(var(--T)*.60)}
.fwdoc .scene .d16{animation-delay:calc(var(--T)*.64)}
.fwdoc .scene .d17{animation-delay:calc(var(--T)*.68)}
.fwdoc .scene .d18{animation-delay:calc(var(--T)*.72)}
.fwdoc .scene .d19{animation-delay:calc(var(--T)*.76)}
.fwdoc .scene .d20{animation-delay:calc(var(--T)*.80)}
.fwdoc .scene .d21{animation-delay:calc(var(--T)*.84)}
.fwdoc .scene .d22{animation-delay:calc(var(--T)*.88)}
.fwdoc .scene .d23{animation-delay:calc(var(--T)*.92)}
.fwdoc .scene .d24{animation-delay:calc(var(--T)*.96)}
@keyframes fw-k-flow{to{background-position:16px 0}}
@keyframes fw-k-flowv{to{background-position:0 16px}}
@keyframes fw-k-mv{0%{transform:translate(0,0);opacity:0}10%{opacity:1}85%{opacity:1}100%{transform:translate(var(--tx,120px),var(--ty,0));opacity:0}}
@keyframes fw-k-pop{0%,8%{transform:scale(0);opacity:0}20%,82%{transform:scale(1);opacity:1}94%,100%{transform:scale(0);opacity:0}}
@keyframes fw-k-fadein{0%,10%{opacity:0}28%,84%{opacity:1}96%,100%{opacity:0}}
@keyframes fw-k-on{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#22c55e;box-shadow:0 0 12px rgba(34,197,94,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-on-o{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#f59e0b;box-shadow:0 0 12px rgba(245,158,11,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-on-r{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#ef4444;box-shadow:0 0 12px rgba(239,68,68,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-on-b{0%,14%{background:#3a4a63;box-shadow:none}28%,80%{background:#3b82f6;box-shadow:0 0 12px rgba(59,130,246,.55)}92%,100%{background:#3a4a63;box-shadow:none}}
@keyframes fw-k-ok{0%,18%{background:#3a4a63;transform:scale(1);box-shadow:none}34%,86%{background:#22c55e;transform:scale(1.22);box-shadow:0 0 12px rgba(34,197,94,.6)}100%{background:#22c55e;transform:scale(1)}}
@keyframes fw-k-no{0%,16%{background:#3a4a63;opacity:1;transform:translateX(0)}30%{background:#ef4444}38%{transform:translateX(-4px)}48%{transform:translateX(4px)}62%{opacity:.22;transform:translateY(7px)}100%{opacity:.22;transform:translateY(7px);background:#3a4a63}}
@keyframes fw-k-pulse{0%,100%{transform:scale(1)}50%{transform:scale(1.1)}}
@keyframes fw-k-glow{0%,100%{box-shadow:0 0 0 0 rgba(59,130,246,0)}50%{box-shadow:0 0 18px 2px rgba(59,130,246,.55)}}
@keyframes fw-k-grow{0%,10%{transform:scaleX(.08)}42%,82%{transform:scaleX(1)}94%,100%{transform:scaleX(.08)}}
@keyframes fw-k-dash{to{stroke-dashoffset:-56}}
.fwdoc .scene-bar{position:absolute;top:10px;right:12px;display:flex;gap:5px;z-index:9}
.fwdoc .scene-bar button{background:rgba(13,21,36,.88);color:#9fb4d4;border:1px solid #2c4166;border-radius:7px;
  font-size:12px;padding:3px 10px;cursor:pointer;font-family:inherit}
.fwdoc .scene-bar button:hover{color:#fff;border-color:var(--accent)}
.fwdoc .scene-bar button.on{color:#fff;background:#1f4fd8;border-color:#1f4fd8}
.fwdoc .scene.paused *{animation-play-state:paused !important}
.fwdoc .scene.hold *{animation:none !important}
@media(prefers-reduced-motion:reduce){.fwdoc .scene,.fwdoc .scene *{animation:none !important}}
.fwdoc .sc-cap{font-size:13.5px;color:var(--muted);margin:0 0 26px;padding:0 4px}
.fwdoc .sc-cap strong{color:#fff}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:22px;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 .station{animation:fw-stationGlow 2.4s ease-in-out infinite}
@keyframes fw-stationGlow{0%,100%{opacity:.55}50%{opacity:1}}
.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 .oneline{font-size:13.5px;color:var(--text);margin:10px 0 6px;padding-left:12px;border-left:3px solid var(--accent)}
.fwdoc ul.feat{list-style:none;margin:8px 0}
.fwdoc ul.feat li{padding:6px 0 6px 26px;position:relative;font-size:13px;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-blinkdot 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
.fwdoc .paths{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0 2px}
.fwdoc .paths .filepath{font-size:10.5px}
.fwdoc .full{color:var(--good);font-weight:700}
.fwdoc .half{color:var(--warn);font-weight:700}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-svgflowmove 1.2s linear infinite}
@keyframes fw-svgflowmove{to{stroke-dashoffset:-14}}
.fwdoc .svgpulse{animation:fw-svgpulse 2s ease-in-out infinite;transform-origin:center;transform-box:fill-box}
@keyframes fw-svgpulse{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-tokrun{0%{transform:translateX(-6px);opacity:0}15%{opacity:1}85%{opacity:1}100%{transform:translateX(150px);opacity:0}}
@keyframes fw-growbar{from{width:0}to{width:100%}}
/* ===== 导入面板附加样式 ===== */
.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>

<div class="toc"><div class="toc-title">本页目录 · 先动画建立直觉,再源码落到实地</div><ol><li><a href="#anim">0. 动画速览 · 建立直觉</a></li><li><a href="#sec-1">1. 通信全景:三个平面</a></li><li><a href="#sec-2">2. 通信底座:组管理与通信器装配</a></li><li><a href="#sec-3">3. 竞选机制代码走读:GroupCoordinator 谓词阶梯</a></li><li><a href="#sec-4">4. 跨卡通信行为全清单</a></li><li><a href="#sec-5">5. 底层通信库全解析</a></li><li><a href="#sec-6">6. 行为 × 通信库映射矩阵</a></li><li><a href="#sec-7">7. 性能优化手法专题</a></li><li><a href="#sec-8">8. 配置项与环境变量</a></li><li><a href="#sec-9">9. 小结与系列交叉引用</a></li></ol></div>

  <section>
<h2 class="sec" id="anim"><span class="num">0</span>动画速览 · 建立直觉</h2>
<p class="lede">提到"跨卡通信",你脑中可能只有一根网线;但在 SGLang 的一次推理里,"跨卡"的对话其实无处不在——进程之间用对讲机排队指令,GPU 之间以微秒级握手协作算力,服务器之间则整箱整箱地搬运 KV 笔记。本篇把这三个平面和它们身后的通信库生态,一次铺开。</p>


  <div class="callout c-tip"><strong>一句话理解本特性:</strong>没有万能通道,只有分流——控制面刻意轻装、数据面按"消息画像"自动竞速、传输面交给专业搬家队;性能的秘密不是把通信变没,而是把它藏进计算的影子里。</div>

  

  <p>本篇是通信专题的收官,也是总纲。<a href="/docs/inference-engines/sglang/11-nccl-usage/">第 12 篇</a>站在 NCCL 的视角看它承担了什么,<a href="/docs/inference-engines/sglang/12-nccl-pr-history/">第 13 篇</a>回顾了 SGLang 从"单一依赖"走向"多后端并存"的演进史;这一篇把视野拉到最高处——所有跨卡、跨机的对话,一共分属三个平面,每个平面上又各自生长出一串通信库。全程没有一行代码,只有地图与比喻。</p>

  <h3 class="sub" id="s1">三个平面:对讲机、算力协作与搬家队</h3>
  <p>先建立一个直觉:一次推理里的"跨卡对话"不是一件事,而是三件节奏完全不同的事。想象一家横跨三栋楼的工厂:各楼的班组长靠对讲机喊话——排产、点名、报平安;车间里八台机器高速协作,半成品在机器之间秒级流转;而把成品从一栋楼运到另一栋楼,靠的是专业搬家队整箱托运。SGLang 的通信版图,就是这三层楼的合体:<strong>控制面、数据面、传输面</strong>。三个平面共享同一套底层公路(NVLink、PCIe、高速网络),但参与者、消息量级、时延要求完全不同,所以长出了完全不同的通道。</p>
  <p><strong>控制面是进程之间的对讲机。</strong>谁接单、谁开工、这批活排给谁、某张卡是否还活着——这些"管理对话"全是小纸条:每步不过几 KB 到几 MB,却频率极高,而且必须全员口径一致。它们走的是轻量消息通道:消息信箱(ZMQ)、共享内存里的无锁环形队列、CPU 侧的进程组(gloo)。注意一个刻意的安排:控制面几乎绕开一切 GPU 通信库——哪怕"全员到齐"这样的点名,也不劳驾显卡。原因很实在:GPU 通信库为兆级张量而生,一开口就要在显卡上开缓冲、占设备队列;为了几张小纸条惊动它,不但慢,还可能打乱 GPU 手头正在跑的计算。杀鸡焉用牛刀,何况这把牛刀还会踩进鸡窝。</p>
  <p><strong>数据面是 GPU 之间的高速算力协作</strong>,也是性能的主战场。张量并行(见<a href="/docs/inference-engines/sglang/03-parallelism/">第 4 篇</a>)下,每一层网络的输出都要把各卡的"部分答案"加起来(allreduce 求和);序列并行要把切开的张量重新拼齐(all-gather);专家并行要把 token 按各自的专家投递出去、算完再接回来(dispatch 与 combine)。这些通信每一步都卡在解码的关键路径上——慢一毫秒,每个 token 就晚一毫秒出生。所以数据面养了一整套"多车道高速公路":同一句"把结果加起来",最多有八条通道可选,按消息画像自动竞速(下一节专门讲)。</p>
  <p><strong>传输面是跨服务器的搬家队。</strong>当预填充与解码分开部署(<a href="/docs/inference-engines/sglang/07-pd-disaggregation/">第 8 篇</a>的 PD 分离),预填充机算好的 KV 笔记——动辄几十上百 MB——必须整箱送到解码机,生成才能继续;多模态模型里,图像特征也要跨进程递交。这类"搬家"不追求微秒级响应,追求的是吞吐、稳定、不打扰别人,于是交给专门的搬运引擎(Mooncake、NIXL 等)。有趣的是,搬家队和数据面共用同一套底层公路,只是开车姿势不同——数据面开跑车,传输面开重卡。</p>

  <div class="scene" style="--T:7s;height:378px">
    <div class="sc-title">场景 · 同一次推理,三个平面同时开工</div>

    <div class="zone abs" style="left:2%;top:46px;width:96%;height:94px">
      <span class="lbl">① 控制面 —— 进程之间的"对讲机":排队指令 · 状态同步 · 心跳</span>
      <div class="row">
        <div class="node">调度进程</div>
        <div class="wire" style="width:220px"></div>
        <div class="node">计算进程们</div>
        <span class="lbl">轻量消息通道,刻意绕开重型通信库</span>
      </div>
    </div>

    <div class="zone abs" style="left:2%;top:152px;width:96%;height:97px">
      <span class="lbl">② 数据面 —— GPU 之间的高速算力协作:求和 · 拼齐 · 分发</span>
      <div class="row">
        <div class="trow">
          <div class="gpu">GPU 0</div><div class="wire" style="width:26px"></div><div class="gpu">GPU 1</div><div class="wire" style="width:26px"></div><div class="gpu">GPU 2</div><div class="wire" style="width:26px"></div><div class="gpu">GPU 3</div>
        </div>
        <span class="lbl">八条通道自动竞速,卡在解码的关键路径上</span>
      </div>
    </div>

    <div class="zone abs" style="left:2%;top:261px;width:96%;height:94px">
      <span class="lbl">③ 传输面 —— 跨服务器搬家:整箱运送 KV 笔记</span>
      <div class="row">
        <div class="node">预填充服务器</div>
        <div class="wire" style="width:170px"></div>
        <div class="node">解码服务器</div>
        <span class="lbl">专门搬运引擎,与数据面共享底层网络</span>
      </div>
    </div>

    <span class="tok abs mv d1" style="width:10px;height:10px;left:13%;top:92px;--tx:180px;--T:5s"></span>
    <span class="tok abs mv d6 alt" style="width:8px;height:8px;left:19%;top:93px;--tx:150px;--T:5s"></span>
    <span class="tok abs mv d11" style="width:10px;height:10px;left:25%;top:92px;--tx:200px;--T:5s"></span>
    <span class="tok abs mv d16" style="width:8px;height:8px;left:16%;top:93px;--tx:-140px;--T:5s"></span>
    <span class="tok abs mv d20 alt" style="width:10px;height:10px;left:29%;top:92px;--tx:160px;--T:5s"></span>
    <span class="tok abs mv d14" style="width:8px;height:8px;left:21%;top:93px;--tx:170px;--T:5s"></span>

    <span class="pkt mv d1" style="width:16px;height:16px;left:8%;top:197px;--tx:400px;--T:3s"></span>
    <span class="pkt mv d5" style="width:16px;height:16px;left:10%;top:197px;--tx:430px;--T:3s"></span>
    <span class="pkt g mv d9" style="width:14px;height:14px;left:12%;top:198px;--tx:380px;--T:3s"></span>
    <span class="pkt mv d13" style="width:16px;height:16px;left:9%;top:197px;--tx:460px;--T:3s"></span>
    <span class="pkt v mv d17" style="width:14px;height:14px;left:14%;top:198px;--tx:350px;--T:3s"></span>

    <span class="kv abs mv d1" style="width:34px;height:20px;left:14%;top:302px;--tx:130px;--T:8s"></span>
    <span class="kv abs mv d9" style="width:34px;height:20px;left:15%;top:302px;--tx:130px;--T:8s"></span>
    <span class="kv abs mv d17" style="width:34px;height:20px;left:16%;top:302px;--tx:130px;--T:8s"></span>
    <span class="pkt g mv d20" style="width:10px;height:10px;left:30%;top:307px;--tx:-120px;--T:8s"></span>

    <div class="sc-hint">三个平面同行:控制面最勤,数据面最快,传输面最重</div>
  </div>
  <p class="sc-cap">动画解说:<strong>三条泳道同时开工</strong>——控制面上,灰白的小方块是永不停歇的指令与心跳,又小又密,有些还在往返对讲;数据面上,蓝色大光点更亮也更快,是 GPU 之间的求和、拼齐与分发;传输面上,整块的 <strong>KV 方块被一箱箱</strong>从预填充服务器送往解码服务器,偶尔有个小回执逆行。同一时刻,三个平面各说各的话,互不打扰。</p>

  <h3 class="sub" id="s2">八条通道竞速:消息的画像决定车道</h3>
  <p>把镜头拉近数据面。同样是"把八张卡的结果加起来",SGLang 不只准备一条路,而是多条通道并排开放;每次通信发起之前,先给消息"画像",看三件事:<strong>它有多大</strong>——是几 KB 的小纸条,还是几十上百 MB 的大包裹?<strong>发往哪里</strong>——同一台机器里 NVLink 手拉手的邻居、只有 PCIe 相连的同伴,还是隔着网络的远房亲戚?<strong>是否发生在录制图内</strong>——也就是<a href="/docs/inference-engines/sglang/05-cuda-graph/">第 6 篇</a>讲过的"录音机"(CUDA Graph):把一段计算录下来反复回放,可以省掉 CPU 每步发号施令的开销,但有的库愿意被录音,有的坚决不干,于是"录不录音"本身也成了选路条件。</p>
  <p>画像一画完,竞速就开始了,优先级是一条固定的阶梯。最上面是<strong>自研 allreduce</strong>——同城快递:小消息、同机直递,跳过通用库的一切握手仪式,一跳送达。往下是<strong>PCIe 直递</strong>,给没有 NVLink 的机型准备的备选道;再往下是<strong>快速 AR</strong>,AMD 显卡专属的量化捷径;然后是 <strong>MSCCL++</strong>,一条实验性快线——它要提前把每块内存的地址登记在案,而只有录制图内的缓冲区地址是提前已知的,所以它只肯在录制图里干活;再往下是<strong>对称内存</strong>,吃 NVLink 组播的红利——一份数据写一次、全员立即可见,专治大消息;最底下是 <strong>NCCL</strong>,那句人人都会说的"通用语",大消息与跨机通信的最终兜底。这条阶梯上常同台竞技的是六站,加上若干平台专属的变体与两条 NCCL 接入线,凑成数据面的八条通道。规律一句话:<strong>消息越小,越在上面的快车道解决;消息越大,越往下落,最终落进 NCCL 的怀抱。</strong></p>

  <div class="scene" style="--T:9s;height:488px">
    <div class="sc-title">场景 · 一条消息沿通道阶梯下坠</div>
    <span class="lbl abs" style="right:3%;top:10px">同一条消息,越攒越大</span>
    <div class="bar abs grow d1" style="right:3%;top:32px;width:250px"></div>
    <span class="lbl abs" style="right:3%;top:50px">小 → 大</span>
    <span class="lbl abs" style="left:2%;top:42px">消息越小,越靠上</span>

    <div class="node abs hit b d1" style="left:2%;top:64px;width:30%">① 自研 allreduce<small>小消息 · 同机 NVLink 直递</small></div>
    <div class="node abs hit b d4" style="left:14%;top:132px;width:30%">② PCIe 直递<small>无 NVLink 机型的备选道</small></div>
    <div class="node abs hit b d7" style="left:26%;top:200px;width:30%">③ 快速 AR<small>AMD 显卡 · 量化捷径</small></div>
    <div class="node abs hit b d10" style="left:38%;top:268px;width:30%">④ MSCCL++<small>实验快线 · 只在录制图内</small></div>
    <div class="node abs hit b d13" style="left:50%;top:336px;width:30%">⑤ 对称内存<small>NVLink 组播 · 大消息</small></div>
    <div class="node abs glow" style="left:62%;top:404px;width:30%">⑥ NCCL<small>通用语 · 大消息与多机的兜底</small></div>

    <span class="pkt o mv d3" style="width:8px;height:8px;left:8%;top:90px;--tx:130px;--ty:96px"></span>
    <span class="pkt o mv d11" style="width:14px;height:14px;left:34%;top:298px;--tx:150px;--ty:90px"></span>

    <div class="sc-hint">小件走上层快车道,大件一路下坠,落进底层 NCCL</div>
  </div>
  <p class="sc-cap">动画解说:右上角的蓝色条是<strong>同一条消息</strong>,在一个周期里从小攒到大。阶梯上的通道<strong>依次亮灯、又把灯让给下一条</strong>——自研快递先接小件,灯往下传:PCIe 直递、量化捷径、实验快线、对称内存;消息攒到最大时,灯光稳稳落在 <strong>NCCL</strong> 上不再离开。两个橙色小点就是那条"长大中的消息",沿着阶梯一路下坠——每经过一站,就问一句"这条消息归我吗?"小了不接,大到某站,就被接住。</p>

  <h3 class="sub" id="s3">两种求和姿势:一跳直达与环形接力</h3>
  <p>通道选好了,同一条通道内部还有"姿势"之分。以最常用的 allreduce(把各卡的部分和变成每卡都有的总和)为例,有两种经典姿势。<strong>one-shot(一跳直达)</strong>:每张卡把自己的结果直接发给所有同伴,同时收齐所有人的——一步到位,没有中间商,延迟最低;代价是数据放大:八张卡时,每张卡都要把完整的自己发七遍,大消息时带宽直接爆炸。<strong>环形接力(两圈完成)</strong>:把数据切成小块,沿着一个环依次传递——第一圈边传边加,第二圈把加好的总和送回每个人;每块数据只走一遍,带宽用得最省,但小消息时要白等两圈,启动次数也吃不消。</p>
  <p>所以答案是<strong>动态换挡</strong>:小消息是"延迟问题",谁启动快谁赢,one-shot 完胜;大消息是"带宽问题",谁搬运省谁赢,环形反超。自研快车道的内部,就会按消息大小在这两种姿势及其变体之间自动切换——不需要任何人下指令,尺寸本身就是指令。</p>

  <div class="scene" style="--T:7s;height:322px">
    <div class="sc-title">场景 · 两种求和姿势,同屏计时</div>

    <div class="zone abs" style="left:2%;top:52px;width:46%;height:90px">
      <span class="lbl">one-shot · 一跳直达(小消息利器)</span>
      <div class="trow">
        <div class="gpu">GPU 0</div><div class="gpu">GPU 1</div><div class="gpu">GPU 2</div><div class="gpu">GPU 3</div>
      </div>
    </div>

    <div class="zone abs" style="left:52%;top:52px;width:46%;height:90px">
      <span class="lbl">环形接力 · 绕圈两轮(大消息利器)</span>
      <div class="trow">
        <div class="gpu">GPU 0</div><div class="wire" style="width:22px"></div><div class="gpu">GPU 1</div><div class="wire" style="width:22px"></div><div class="gpu">GPU 2</div><div class="wire" style="width:22px"></div><div class="gpu">GPU 3</div>
      </div>
      <div class="wire" style="width:86%"></div>
    </div>

    <span class="pkt mv d1" style="left:6%;top:99px;--tx:150px;--T:2.8s"></span>
    <span class="pkt g mv d2" style="left:34%;top:99px;--tx:-140px;--T:2.8s"></span>
    <span class="pkt mv d3" style="width:10px;height:10px;left:10%;top:100px;--tx:230px;--ty:14px;--T:2.8s"></span>
    <span class="pkt g mv d2" style="width:10px;height:10px;left:36%;top:100px;--tx:-210px;--ty:-14px;--T:2.8s"></span>
    <span class="pkt mv d4" style="left:20%;top:99px;--tx:170px;--T:2.8s"></span>
    <span class="pkt v mv d5" style="left:24%;top:99px;--tx:-120px;--T:2.8s"></span>

    <span class="pkt o mv d2" style="left:60%;top:99px;--tx:40px"></span>
    <span class="pkt o mv d5" style="left:71%;top:99px;--tx:40px"></span>
    <span class="pkt o mv d8" style="left:82%;top:99px;--tx:40px"></span>
    <span class="pkt v mv d13" style="left:60%;top:99px;--tx:40px"></span>
    <span class="pkt v mv d16" style="left:71%;top:99px;--tx:40px"></span>
    <span class="pkt v mv d19" style="left:82%;top:99px;--tx:40px"></span>

    <span class="lbl abs" style="left:4%;top:158px">总耗时对比 —— 条越长,越慢</span>
    <div class="row abs" style="left:4%;top:184px">
      <span class="lbl">小消息 · one-shot</span><div class="bar g grow d2" style="width:120px"></div><span class="lbl">一跳完成</span>
    </div>
    <div class="row abs" style="left:4%;top:216px">
      <span class="lbl">小消息 · 环形</span><div class="bar o grow d5" style="width:280px"></div><span class="lbl">要绕两圈</span>
    </div>
    <div class="row abs" style="left:4%;top:248px">
      <span class="lbl">大消息 · one-shot</span><div class="bar r grow d11" style="width:300px"></div><span class="lbl">带宽爆炸</span>
    </div>
    <div class="row abs" style="left:4%;top:280px">
      <span class="lbl">大消息 · 环形</span><div class="bar g grow d14" style="width:140px"></div><span class="lbl">带宽最省</span>
    </div>
  </div>
  <p class="sc-cap">动画解说:左边 <strong>one-shot</strong>,四张卡两两全互发,光点一哄而上、一跳完成;右边<strong>环形</strong>,数据切块沿环接力,橙色的第一圈走完,才轮到紫色的第二圈。下面的耗时对比条说明一切:<strong>小消息</strong>时,one-shot 的绿条远短于环形;换到<strong>大消息</strong>,形势完全反转——one-shot 的红条拖到最长,环形的绿条反而最短。没有更好的姿势,只有更匹配的尺寸。</p>

  <h3 class="sub" id="s4">通信库地图:各司其职的生态位</h3>
  <p>最后把整张地图摊开,你会发现每个通信库占据的是一个<strong>生态位</strong>,而不是彼此的替代品。<strong>NCCL</strong> 是通用语——几乎所有框架、所有显卡都会说,大消息与多机通信的兜底,别的通道都不接的活最终都归它;<strong>自研 allreduce</strong> 是同城快递,专送小消息;<strong>对称内存</strong> 吃 NVLink 组播的红利,一写全员可见;<strong>MSCCL++</strong> 是实验性快线,新算法先在这里试跑;<strong>DeepEP</strong> 是专家并行的邮差——把 token 按专家归属精准投递,微秒级往返,技术底座站在 NVSHMEM 的肩膀上;<strong>Mooncake</strong> 与 <strong>NIXL</strong> 是搬家队,负责传输面的整箱搬运;而 <strong>ZMQ、共享内存广播和 gloo</strong>,是控制面那部从不关机的对讲机。</p>
  <p>为什么这么多库能和平共存?因为它们压根不在抢同一件事:控制面要的是"别惊动 GPU";数据面的小消息要的是"跳过一切仪式";大消息要的是"带宽打满";专家并行要的是"按地址精准投递";传输面要的是"整箱搬运、一箱不撒"。同一套底层公路被不同的库以不同姿势使用,甚至互借劳动力——NIXL 白天在数据面帮忙投递专家包裹,晚上在传输面开车搬家;Mooncake 既送 KV,也管缓存的落盘周转。生态的丰富不是堆砌,而是分工。</p>

  <div class="scene" style="--T:8s">
    <div class="sc-title">场景 · 通信库地图:按平面各就各位</div>
    <div class="col mt">
      <div class="zone">
        <span class="lbl">① 控制面 · 对讲机通道(小纸条:指令 / 状态 / 心跳)</span>
        <div class="row">
          <div class="node pop d1">ZMQ<small>消息信箱</small></div>
          <div class="node pop d2">共享内存广播<small>无锁环形队列</small></div>
          <div class="node pop d3">gloo<small>CPU 进程组 · 对象广播与点名</small></div>
        </div>
      </div>
      <div class="zone">
        <span class="lbl">② 数据面 · GPU 高速协作(按消息画像竞速的八条通道)</span>
        <div class="row">
          <div class="node pop d4">自研 allreduce<small>小消息 · 同城快递</small></div>
          <div class="node pop d5">对称内存<small>NVLink 组播 · 一写全员可见</small></div>
          <div class="node pop d6">MSCCL++<small>实验快线 · 仅录制图内</small></div>
          <div class="node pop d7">DeepEP<small>专家邮差 · NVSHMEM 底座</small></div>
        </div>
      </div>
      <div class="zone">
        <span class="lbl">③ 传输面 · 跨服务器搬家(整箱 KV,不求微秒求吞吐)</span>
        <div class="row">
          <div class="node pop d8">Mooncake<small>搬家队主力</small></div>
          <div class="node pop d9">NIXL<small>搬运引擎 · 也在数据面兼职</small></div>
        </div>
      </div>
      <div class="node pop d11" style="width:100%">NCCL · 通用底座<small>大消息与多机的兜底 —— 横跨各平面的"通用语",人人都借过它的力</small></div>
    </div>
    <div class="sc-hint">库不在多,各司其职则灵</div>
  </div>
  <p class="sc-cap">动画解说:库盒子<strong>按平面依次就位</strong>——控制面的对讲机三件套、数据面的四员干将、传输面的两位司机,最后 <strong>NCCL 作为横跨各平面的通用底座压轴登场</strong>。注意两个细节:DeepEP 的小注脚写着"NVSHMEM 底座"——邮差自己也站在别的库的肩膀上;NIXL 则在两个平面都上岗。地图的分层,就是本篇的骨架。</p>

  <h3 class="sub" id="s5">小结:选路哲学与"藏进影子"的性能观</h3>
  <p>回头看,这一篇真正想讲的不是"有哪些库",而是一种<strong>选路哲学:没有万能通道,只有按消息画像分流</strong>。大小、拓扑、图内外——三个维度一画,路自然就出来了。围绕这个哲学,SGLang 的通信生态收获了四样东西:</p>
  <div class="grid-2">
    <div class="card">
      <div class="card-title">快 · 分流与换挡</div>
      <p>小消息走免仪式的快车道,大消息落进带宽高效的通道与姿势;选路发生在每一次通信之前,全自动、零人工。八条通道不是装饰,是八种"消息画像"各得其所。</p>
    </div>
    <div class="card">
      <div class="card-title">快 · 把通信藏进计算的影子</div>
      <p>通信本身砍不掉,但可以错峰:把一个批次切成两个微批,一个在通信车道上跑时,另一个立刻上机计算;通信时间没变,却在时间轴上被计算的身影盖住了。</p>
    </div>
    <div class="card">
      <div class="card-title">省 · 控制面轻装</div>
      <p>几 KB 的调度指令永远不惊动 GPU 通信库——轻量消息通道在 CPU 侧就把一切办完;显卡的算力与显存,一毫一厘都留给推理本身。</p>
    </div>
    <div class="card">
      <div class="card-title">稳 · 生态有兜底</div>
      <p>竞速阶梯的末端永远站着 NCCL,谁都不接的活它接;新硬件、新算法先以实验快线的身份接入,验证成熟再转正;任何一条通道不适配,都有备选,不至于全盘停摆。</p>
    </div>
  </div>
  <p>一句话收束:通信的极致,不是把网线换成更粗的,而是让每类消息都找到最适合自己的那条路,并且尽量在计算忙着的时候,悄悄走完。</p>

  <h3 class="sub" id="s6">常见误解 FAQ</h3>
  <div class="callout c-info">
    <p><strong>Q:为什么要有这么多通信库?NCCL 一条不好吗?</strong><br>
    A:因为硬件与场景的差异太大,一条通道通吃并不现实。NCCL 为了通用,要照顾所有拓扑、所有尺寸、所有框架,小消息与特定拓扑上必然留有"更快的专属做法"的空间——就像市内闪送、货运卡车与国际航运无法互相替代。SGLang 的思路不是替换 NCCL,而是在它不擅长的地方另开快车道,再在阶梯末端让它稳稳兜底。</p>
  </div>
  <div class="callout c-info">
    <p><strong>Q:控制面"刻意避开"GPU 通信库,是后者不好吗?</strong><br>
    A:不是不好,是不合适。GPU 通信库为兆级张量与集合运算设计,哪怕发一条小消息也要在显卡上建缓冲、走设备队列;用它传几 KB 的调度指令,既慢又占资源,还可能干扰正在跑的计算。轻量通道在 CPU 上就把事办完了,各得其所。</p>
  </div>
  <div class="callout c-info">
    <p><strong>Q:"是否在录制图内"为什么会影响选路?</strong><br>
    A:录制图(第 6 篇的 CUDA Graph)要求一段计算能被原样回放,这对通信库是道门槛:有的库要提前登记每块内存的地址,只肯在图内干活(如 MSCCL++);有的库的调用方式没法被录音,只能在图外使用。于是同一句 allreduce,图内与图外走的可能是两条不同的通道。</p>
  </div>
  <div class="callout c-info">
    <p><strong>Q:传输面和数据面到底共享什么?</strong><br>
    A:共享底层公路——RDMA 网卡、NVLink、高速网络这些硬件与传输技术;有的库(如 NIXL)甚至同时在两个平面上岗。但节奏迥异:数据面追求微秒级低延迟,传输面追求大吞吐、稳搬运,所以各自演化出了不同的引擎与协议。</p>
  </div>

  
</section>

<section>
<h2 class="sec" id="sec-1"><span class="num">1</span>通信全景:三个平面</h2>
  <p>把 SGLang 运行时里所有"从一个进程/GPU 把信息送到另一个进程/GPU"的代码摊开,会自然分层为三个平面。它们的库、参与者、时延量级完全不同:</p>
  <div class="flow-v">
    <div class="node-accent">控制面<small>进程间协调:ZMQ IPC、gloo 进程组、共享内存 MessageQueue、TCPStore、Ray —— 携带请求/调度决策等小对象</small></div>
    <div class="arrow-v">↓</div>
    <div class="node-accent">数据面<small>GPU 集合通信:NCCL(两条接入)、custom AR v1/v2、PCIe-IPC、quick AR、PyTorch/Triton symm mem、MSCCL++、DeepEP/NVSHMEM —— 携带激活值与 KV 张量</small></div>
    <div class="arrow-v">↓</div>
    <div class="node-accent">传输面<small>跨实例迁移:Mooncake transfer engine、NIXL(UCX)、mori IOEngine、CUDA IPC —— PD 分离的 KV 搬运与多模态特征传输</small></div>
  </div>
  <p>三个平面各司其职,一句话概括:</p>
  <ul>
    <li><strong>控制面</strong>:决定"算什么、谁算"——TokenizerManager → DataParallelController → Scheduler 的请求分发、TP 组内 rank0 → 其余 rank 的输入广播、语法/投机解码等需要全组一致性的小对象同步,全部在 CPU 侧完成,量级是每步几 KB~几 MB。</li>
    <li><strong>数据面</strong>:决定"张量怎么合"——TP all-reduce、DP gather/scatter、EP dispatch/combine、lm_head 词表 gather,直接决定解码时延,是第 3 节谓词阶梯与第 7 节优化手法的主战场。</li>
    <li><strong>传输面</strong>:决定"状态怎么搬"——Prefill/Decode 分离部署时的 KV cache 迁移(<span class="filepath">python/sglang/srt/disaggregation/</span>),以及多模态 embedding 的 CUDA IPC 直通(<span class="filepath">positional_embeds_transport.py</span>)。详见<a href="/docs/inference-engines/sglang/07-pd-disaggregation/">第 8 篇</a>。</li>
  </ul>
  <div class="callout c-info"><strong>规模统计:</strong>通信底座目录 <span class="filepath">python/sglang/srt/distributed/</span> 含 <span class="filepath">parallel_state.py</span>(3531 行)与 27 个文件共 12568 行 Python(不含 sgl-kernel/sglang.kernels 中的 CUDA 实现);MoE a2a 另有 11 个 token dispatcher 后端,PD 传输面另有 3 个 conn 后端。第 5 节给出逐文件规模条形图。</div>
  <p>本篇与<a href="/docs/inference-engines/sglang/11-nccl-usage/">第 12 篇(NCCL 视角)</a>的分工:NCCL 在这里只是通信库版图中的一员——custom allreduce、symmetric memory、DeepEP、MSCCL++、Mooncake 与它同等一档;第 12 篇回答"NCCL 怎么用、哪些行为落到 NCCL",本篇回答"所有跨卡行为都有哪些、每条行为可以在哪些库之间选择"。</p>
</section>

<section>
<h2 class="sec" id="sec-2"><span class="num">2</span>通信底座:组管理与通信器装配</h2>
  <p>一切数据面通信的入口是 <span class="filepath">python/sglang/srt/distributed/parallel_state.py</span> 中的 <code>GroupCoordinator</code>(parallel_state.py:254)。它在 <code>initialize_model_parallel()</code>(parallel_state.py:2563)里按派生宽度构建出 10 类并行组,每组一个实例,同一实例上按需装配最多 8 种通信器:</p>
  <table class="tbl">
    <tr><th>并行组</th><th>成员范围</th><th>装配的通信器特点</th></tr>
    <tr><td><code>tp</code></td><td>连续 <code>tp_size</code> 个全局 rank</td><td>最全:pynccl / mscclpp / custom AR / pcie-ipc / quick AR / symm mem / mq 广播</td></tr>
    <tr><td><code>attn_tp</code></td><td>DP attention 下的注意力 TP 子组</td><td><code>use_pynccl=SYNC_TOKEN_IDS_ACROSS_TP or enable_symm_mem</code>(parallel_state.py:2794)</td></tr>
    <tr><td><code>attn_cp</code> / <code>dcp</code></td><td>上下文并行 / 解码上下文并行</td><td>普通组;DCP 的 a2a 走 PyNccl <code>all_to_all_single</code></td></tr>
    <tr><td><code>moe_ep</code> / <code>moe_tp</code> / <code>moe_dp</code></td><td>专家并行三元组</td><td><code>use_pynccl=False, use_custom_allreduce=False</code>(parallel_state.py:2890)——EP 的重活交给 a2a dispatcher</td></tr>
    <tr><td><code>pp</code> / <code>self_pp</code></td><td>跨节点流水线 rank</td><td><code>use_custom_allreduce=False</code>,只有 pynccl + torch.distributed P2P</td></tr>
    <tr><td><code>shared_experts_tp</code></td><td>共享专家 TP 子组</td><td>无 custom AR / symm mem</td></tr>
  </table>
  <p>每个组同时建两个 torch.distributed 进程组(parallel_state.py:394-410):一个绑定设备后端(nccl/hccl/mooncake),一个 <strong>gloo CPU 组</strong>——后者是控制面的关键基建,所有对象级通信(广播 pyobj、send/recv 对象、barrier)都走它;连 <code>barrier()</code> 都刻意避开设备组,因为"NCCL 的 barrier 内部是偷偷建 GPU 张量的 broadcast,容易搞乱当前设备"(parallel_state.py:2067-2074)。</p>
  <p>对外 API 层由 <span class="filepath">communication_op.py</span> 提供语义化封装(<code>tensor_model_parallel_all_reduce</code>、<code>attn_cp_tp_broadcast_pyobj</code>、<code>moe_expert_parallel_all_reduce</code> 等,communication_op.py:21-139),模型代码只面向语义,不感知后端。另有两块小而重要的底座:<span class="filepath">communication_tags.py</span> 定义 P2P 标签(<code>HICACHE_PP_SYNC</code>、<code>GRAMMAR_PP_SYNC</code>、<code>DISAGG_BOOTSTRAP_PP_SYNC</code>,communication_tags.py:13-16),避免 PP 流水线上不同 send/recv 路径互相吞消息;<span class="filepath">comm_cleanup.py</span> 用 <code>atexit</code> 注册通信器的幂等关闭(comm_cleanup.py:8)。<span class="filepath">naive_distributed.py</span> 则提供一个纯文件系统 rendezvous 的玩具实现(NaiveDistributed,naive_distributed.py:12),用于无 torch.distributed 的脚本场景。</p>
  <p>多机 rendezvous 由 <span class="filepath">bootstrap.py</span> 完成:<code>init_distributed_environment()</code>(parallel_state.py:2465)调用 <code>torch.distributed.init_process_group</code>,地址来自 <code>env://</code> 或自动探测的 <code>tcp://host:port</code>(bootstrap.py:231-245);当 MoE a2a 选择 nixl 时,还会额外建一个全局 <code>TCPStore</code>(默认端口 29600,parallel_state.py:2524)供 NIXL agent 交换缓冲区元数据。<span class="filepath">gated_launch.py</span> 提供另一种启动期控制面:rank0 起一个 uvicorn HTTP 端点,各 rank 每秒轮询并用 gloo broadcast 同步"激活位"(gated_launch.py:35-65),实现外部可控的统一放行。</p>
</section>

<section>
<h2 class="sec" id="sec-3"><span class="num">3</span>竞选机制代码走读:GroupCoordinator 谓词阶梯</h2>
  <p>第 4 篇已从并行策略角度给出结论,本节以代码为准重新走读。入口是 <code>GroupCoordinator.all_reduce()</code>(parallel_state.py:689),eager 模式的完整竞选分四段:</p>
  <p><strong>第一段:对称内存快车道</strong>(parallel_state.py:771-780)。若 <code>is_symmetric_memory_enabled()</code>(即 <code>--enable-symm-mem</code> 打开且 NCCL window 注册成功,pynccl_allocator.py:234),且 MSCCL++/custom AR 都不接手,则直接 <code>with pynccl_comm.change_state(enable=True): pynccl_comm.all_reduce(input)</code>——裸 NCCL 调用直通 NCCL 的对称内存 NVLS 通路。</p>
  <p><strong>第二段:FlashInfer AR 融合判定</strong>(parallel_state.py:782,1015)。<code>_fi_workspace_hint</code> 由 <code>_tag_groups_for_flashinfer_allreduce_only()</code>(parallel_state.py:2354)在组初始化后盖戳:MoE 组与 attn_tp 组各有一个 workspace,谁的 peer 上 rendezvous 就允许谁用——盖错组会"reduce 到错误 peer 集合的 workspace 上,悄悄返回错数据"。</p>
  <p><strong>第三段:out-of-place 方法竞选</strong>,即核心谓词阶梯(parallel_state.py:966-1013,摘关键行):</p>
  <pre class="code"><code>if ca_comm and not should_mscclpp and ca_comm.should_custom_ar(inp):
    return "ca"                       # custom AR(v1/v2)
if pcie_ipc_comm and pcie_ipc_comm.should_pcie_ipc_ar(inp):
    return "pcie_ipc"                 # FlashInfer PCIe-IPC(无 NVLink 机型)
if qr_comm and qr_comm.should_quick_allreduce(inp):
    return "qr"                       # ROCm 量化 quick AR
if pymscclpp_comm and should_mscclpp:
    return "pymscclpp"                # MSCCL++(图内优先)
if torch_symm_mem_comm and ...should_torch_symm_mem_allreduce(inp):
    return "torch_symm_mem"           # multimem/two-shot NVLS
if is_in_tc_piecewise_cuda_graph() and pynccl_comm:
    return "pynccl"                   # piecewise CUDA graph 兜底
return None                           # → in-place:pynccl→symm mem→torch.distributed
</code></pre>
  <p>顺序即优先级:custom AR 拿小消息,PCIe-IPC 只在"没有任何 fabric 专属后端适用"的主机上接手(parallel_state.py:983-986 的注释:它不探测 NVLink,排在它前面的就是 NVLink 后端),quick AR 只在 ROCm 上作为 custom AR 的补充,MSCCL++ 因需要提前注册张量只在图内出现,torch symm mem 承接 64/128MiB 级的大消息,最后 in-place 路径退到 <code>torch.distributed.all_reduce</code>(parallel_state.py:1085-1097)。</p>
  <p><strong>第四段:尺寸阈值</strong>。各 <code>should_*</code> 谓词内嵌硬件相关上限:</p>
  <ul>
    <li>custom AR v1:<code>_MAX_CAR_SIZE = 8MiB</code>(ROCm 16MiB、MUSA 128MiB),要求 dtype∈{fp32,fp16,bf16}、字节数 %16==0、弱连续、world_size∈{2,4,6,8} 且全 NVLink 或 ws=2(custom_all_reduce.py:41-50,262-287);</li>
    <li>custom AR v2:三算法两档位——<code>_pick_config</code> 按 <code>nbytes</code> 依次尝试 <code>1shot_push → 2shot_push → 1shot_pull → 2shot_pull(可带 multicast)</code>(custom_all_reduce_v2.py:389-403),阈值来自 <span class="filepath">device_communicators/configs/custom_all_reduce_v2.py</span> 的调优表,默认工作区上限 16MiB(<code>SGLANG_CUSTOM_ALL_REDUCE_V2_MAX_SIZE_KB=16384</code>,environ.py:1601);</li>
    <li>torch symm mem:按 SM 代际×world_size 查表,SM90/SM100 的 ws=2/4 上限 64MiB、ws=6/8 上限 128MiB(all_reduce_utils.py:3-16);</li>
    <li>quick AR:按 (dtype, world_size) 查 <code>_QR_MIN_SIZE</code> 下限表,如 bf16@ws8 的 FP 路径从 16MiB 起步(quick_all_reduce.py:57-64);</li>
    <li>MSCCL++:在 512B~16MiB(<code>1&lt;&lt;9 .. 1&lt;&lt;24</code>)的调优尺寸上扫描(pymscclpp.py:29),world_size∈{4,8,16,32,64}(pymscclpp.py:324)。</li>
  </ul>
  <p><strong>图内/图外差异</strong>是阶梯的第二根轴。<code>graph_capture()</code> 上下文(parallel_state.py:626-687)内的注释表是权威答案:quick AR 与 custom AR 在 eager 和图内都可用;PyNccl、MSCCL++、TorchSymmMem <strong>只在图内启用</strong>(<code>change_state(enable=True)</code>,默认 disabled,pynccl.py:141-144);<code>torch.distributed</code> <strong>只在 eager 可用</strong>——因为 ProcessGroupNCCL 的调用含不可捕获的 CUDA API。这正好解释了第 12 篇的两条 NCCL 接入线:eager/控制面走 torch.distributed 进程组,图内集合通信走 PyNccl ctypes 直绑。此外,custom AR 的 <code>capture()</code> 上下文在捕获结束时把图内用到的缓冲区地址经 IPC 句柄广播并注册(custom_all_reduce.py:236-260);v2 则把图输入指针写进 131072 行的设备侧指针表,捕获后经 cudaIpc 或 VMM(FABRIC/POSIX fd)注册到各 peer(custom_all_reduce_v2.py:518-563)。</p>
  <div class="callout c-tip"><strong>Dynamo 兼容层:</strong>为了让集合通信在 torch.compile 下保持不透明,六个入口注册为 custom op——<code>inplace_all_reduce / outplace_all_reduce / flashinfer_allreduce / reg_all_gather_into_tensor / reg_reduce_scatter_tensor / reg_all_to_all_single</code>(parallel_state.py:184-251),组以名字字符串索引;编译期还会把方法选择推迟到运行期,避免符号维度上 guard 导致的重编译(parallel_state.py:737-760)。</div>
  <p>all-gather 的阶梯类似但更短:<code>_all_gather_into_tensor</code>(parallel_state.py:1305-1359)依次尝试 ROCm aiter 自定义 AG(<code>SGLANG_USE_AITER_AG</code>)→ MSCCL++ AG → PyNccl → <code>torch.distributed.all_gather_into_tensor</code>。变长集合 <code>all_gatherv</code>/<code>reduce_scatterv</code>(parallel_state.py:1457,1273)则<strong>只</strong>由 PyNccl 实现:变长时用 <code>ncclGroupStart/End</code> 把一组 <code>ncclBroadcast</code>/<code>ncclReduce</code> 拼成一次集合调用(pynccl.py:216-278)。</p>
</section>

<section>
<h2 class="sec" id="sec-4"><span class="num">4</span>跨卡通信行为全清单</h2>
  <p>本节按子系统枚举三个平面上的全部跨卡行为。每项给出触发条件、通信原语、参与 rank 范围与代码位置。</p>

  <h3>4.1 初始化、权重与拓扑探测</h3>
  <table class="tbl">
    <tr><th>行为</th><th>触发条件</th><th>原语 / 库</th><th>范围与位置</th></tr>
    <tr><td>分布式环境初始化</td><td>启动必经</td><td>torch.distributed.init_process_group(backend=nccl/hccl/mooncake)</td><td>world 组;parallel_state.py:2465</td></tr>
    <tr><td>P2P 可用性实测</td><td>构建 custom AR 前</td><td>cudaIpcGetMemHandle/OpenMemHandle 双进程写真实验,结果缓存 JSON</td><td>本机所有 GPU 对;custom_all_reduce_utils.py:149-331</td></tr>
    <tr><td>NVLink/XGMI 探测</td><td>同上</td><td>pynvml / amdsmi 查 1-hop 直连;VMM fabric clique 查询 + all_gather_object</td><td>组内;custom_all_reduce_utils.py:354-418</td></tr>
    <tr><td>NCCL 预热</td><td>启动(<code>pre_warm_nccl</code>)</td><td>一次 all_reduce 冷启动 NCCL/RCCL/HCCL 通信器</td><td>TP 组;bootstrap.py:351</td></tr>
    <tr><td>EPLB P2P 预热</td><td>多节点 EPLB</td><td>batch_isend_irecv 每对 peer 4MiB + expert 计数 all_reduce</td><td>默认组;bootstrap.py:369</td></tr>
    <tr><td>TP lm_head a2a 预热</td><td><code>--enable-tp-lm-head-all-to-all</code></td><td>PyNccl all_to_all_single 预热 P2P 资源</td><td>TP 组;bootstrap.py:406</td></tr>
    <tr><td>权重热更新(RL)</td><td><code>update_weights_from_tensor</code></td><td>gloo 对象广播 / DeviceMesh DTensor reduce-scatter;桶化见 <span class="filepath">weight_sync/tensor_bucket.py</span></td><td>world;weight_sync/utils.py:32</td></tr>
    <tr><td>MoE 专家权重 DP(dwdp)</td><td>DeepSeek 类 MoE</td><td>跨 rank 交换 VMM 共享句柄(FABRIC/POSIX fd)导入 peer 视图,cpu_group all_gather_object 对齐 key 数</td><td>节点内/簇;moe/dwdp/transport.py:92-141</td></tr>
  </table>
  <p>权重常规加载(从磁盘)本身不做集合通信,各 rank 各读分片;真正跨卡的是上面的热更新与 dwdp 句柄交换。</p>

  <h3>4.2 TP 前向:线性层与序列并行</h3>
  <table class="tbl">
    <tr><th>行为</th><th>触发条件</th><th>原语 / 库</th><th>范围与位置</th></tr>
    <tr><td>RowParallelLinear 归约</td><td>每个 MLP/attention 输出投影,<code>reduce_results and tp_size&gt;1</code></td><td>all-reduce(tp_group 或 dp-attention 下 attn_tp_group,linear.py:1804-1826);NPU prefill 可走 INT8 量化 AR(<code>quant_all_reduce</code>:先动态量化再 all-gather,parallel_state.py:799)</td><td>TP 组;linear.py:1804</td></tr>
    <tr><td>ColumnParallelLinear 收集</td><td><code>gather_output=True</code>(qkv 等通常关闭)</td><td>all-gather(dim=-1)</td><td>TP 组;linear.py:626-639</td></tr>
    <tr><td>边界归约替代</td><td><code>--boundary-reduction=rs/rsv/rs+rsv</code></td><td>固定/变长 reduce-scatter 替代 all-reduce</td><td>FFN 阶段;exec_.py:756</td></tr>
    <tr><td>Megatron 序列并行</td><td>支持模型开启 SP</td><td>g-bar: reduce_scatter(进 LayerNorm);g: all_gather(出 LayerNorm;layernorm_sp.py:142),fused_matmul_reduce_scatter / fused_all_gather_matmul 对称内存融合算子(layernorm_sp.py:181-182)</td><td>TP 组;layernorm_sp.py:14-21</td></tr>
    <tr><td>AR+RMSNorm 融合(ROCm)</td><td><code>--enable-aiter-allreduce-fusion</code></td><td>1-stage(≤128KiB)/2-stage 融合核;TP=8 且 K∈(4096,7168] 时强切 2-stage</td><td>TP 组;parallel_state.py:828-964</td></tr>
    <tr><td>AR+RMSNorm 融合(MNNVL/K3)</td><td>SM100 且 V2 有 multicast 平面</td><td>&lt;512KiB 走 1shot multicast push,否则 NVLS 2shot(需 symm buffer 输入)</td><td>TP 组;communication/k3_ar_fusion.py</td></tr>
    <tr><td>AR+Residual+RMSNorm(FlashInfer)</td><td><code>--flashinfer-allreduce-fusion-backend=trtllm/mnnvl/cutedsl</code></td><td>allreduce_fusion workspace,trtllm(IPC)/mnnvl(多节点 NVLink)/cutedsl(Blackwell)三后端,可再融合 MoE finalize</td><td>TP/MoE 组;flashinfer_comm_fusion.py;flashinfer_mnnvl_cutedsl.py:310</td></tr>
    <tr><td>分散短卷积</td><td>Inkling <code>--enable-scattered-sconv</code></td><td>hidden 维 reduce-scatter + 卷积分片计算 + all-gather,通信量不变</td><td>TP 组;exec_.py:748</td></tr>
  </table>

  <h3>4.3 Embedding 与 lm_head</h3>
  <p>词表并行 embedding 每个前向都对部分 embedding 求和后做一次 <strong>TP all-reduce</strong>(dp-attention 下收窄为 attn-TP,vocab_parallel_embedding.py:530-533)。lm_head 侧默认 all-gather 词表分片的 logits(<code>do_tensor_parallel_all_gather</code>,logits_processor.py:534-543,经 attn_tp_all_gather);大词表模型(dspark 系)可改走 <span class="filepath">vocab_gather.py</span> 的三档策略:小分片用 custom AR v2 的 <strong>push 核</strong>、大分片用对称内存 <strong>pull 核</strong>(带 multicast 别名)、其余回退 NCCL 环(vocab_gather.py:75-124);<code>--enable-tp-lm-head-all-to-all</code> 则把词表维收集改成 <strong>PyNccl all_to_all_single</strong>(图内安全,pynccl.py:324-376)。</p>

  <h3>4.4 DP Attention 的 gather/scatter</h3>
  <p>DP attention 在 FFN 前把各 DP rank 的局部 token 汇成全局缓冲,FFN 后再拆回去。每个 forward 先按代价模型选定 padding 模式(dp_attention.py:165-204):prefill 多 DP rank 时选 <strong>SUM_LEN</strong>(变长,避免 padding 开销);decode 时若 SUM_LEN 缓冲装得进 custom AR 就选 SUM_LEN,否则比较 <code>sum_len*2</code> 与 <code>max_len*gather_width</code> 取小者,平手时偏向 <strong>MAX_LEN</strong>——因为等长 all-gather 能启用对称内存。落到通信上(dp_attention.py:982-1041):</p>
  <ul>
    <li>MAX_LEN:<code>all_gather_into_tensor</code>(等长);</li>
    <li>SUM_LEN:<code>all_reduce</code>(各 rank 把局部行写进自己的槽,一步求和);</li>
    <li>变长 gatherv(<code>SGLANG_DP_USE_GATHERV</code>):<code>all_gatherv</code> + <code>reduce_scatterv</code> 的 PyNccl broadcast/reduce 组合,输出直接写进预分配全局缓冲省掉两次 DtoD 拷贝(dp_attention.py:943-949);还有一条 fp8 路径:group-128 量化后以 uint8 gather、再反量化(dp_attention.py:860-882)。</li>
  </ul>
  <p>拆回(dp_scatter)是本 rank 槽位的 memcpy,不发生集合通信;归约拆分 <code>dp_reduce_scatter_tensor</code>(dp_attention.py:1105)在 CP 场景做 reduce_scatter 后接 attn-TP all-gather 还原两轴。dspark 模型的 MAX_LEN gather 另有一条 Triton <strong>multimem.st</strong> 单次 NVLink 多播路径(<span class="filepath">triton_symm_mem_ag.py</span>,inline PTX <code>multimem.st.relaxed.sys.global.v4.f32</code>),rendezvous 一次后可图捕获。</p>

  <h3>4.5 EP / MoE dispatch-combine</h3>
  <p>MoE 的 a2a 通信由 <code>--moe-a2a-backend</code> 选择 dispatcher(exec_.py:843,共 12 个枚举值),统一走 <code>dispatch → run_moe_core → combine</code>(ep_moe/layer.py:248-252):</p>
  <table class="tbl">
    <tr><th>后端</th><th>通信实现</th><th>关键代码</th></tr>
    <tr><td><code>none</code>(standard)</td><td>TP 组 all_gatherv 收全 token、combine 用 reduce_scatterv</td><td>token_dispatcher/standard.py:169,208,288-301</td></tr>
    <tr><td><code>deepep</code> / <code>deepep_v2</code></td><td>deep_ep.Buffer:NVSHMEM RDMA,normal(大 batch)/low_latency(纯 NVLink,decode)双模式;v2 用 ElasticBuffer direct/hybrid 拓扑;NVSHMEM_QP_DEPTH 按每 rank token 上限自动抬升</td><td>token_dispatcher/deepep.py:52-88,182;deepep_v2.py</td></tr>
    <tr><td><code>mori</code></td><td>mori.cpp IOEngine(RDMA backend)+ 共享 comm stream,复用 DeepEP 的 dispatch hooks</td><td>token_dispatcher/moriep.py;mori/conn.py</td></tr>
    <tr><td><code>nixl</code></td><td>nixl_ep.Buffer(UCX,后端由 <code>SGLANG_DISAGGREGATION_NIXL_BACKEND</code> 定),TCPStore rendezvous</td><td>token_dispatcher/nixl.py:41;parallel_state.py:2524</td></tr>
    <tr><td><code>mooncake</code></td><td>复用 PD 的 MooncakeTransferEngine 做两段式 dispatch_a/b、combine_a/b</td><td>token_dispatcher/mooncake.py:169-396</td></tr>
    <tr><td><code>flashinfer</code> / <code>flashinfer_megamoe</code></td><td>FlashInfer trtllm_allreduce_fusion workspace 上的 a2a;NVFP4 载荷先量化再 all_gatherv</td><td>token_dispatcher/flashinfer.py;standard.py:160-215</td></tr>
    <tr><td><code>ascend_ops</code> / <code>ascend_fuseep</code></td><td>NPU AllGather / AllToAllV / MC2(torch_npu)</td><td>token_dispatcher/ascend_ops.py</td></tr>
    <tr><td><code>megamoe</code></td><td>aiter MegaMoEV2(ROCm flydsl),MoE 输入 gather 走 DP gather 管道</td><td>moe/mega_moe_flydsl.py</td></tr>
    <tr><td><code>pplx</code></td><td>pplx-kernels 对称 a2a;因此 DP padding 被强制 MAX_LEN(dp_attention.py:172-175)</td><td>token_dispatcher/pplx.py</td></tr>
  </table>
  <p>另有 <span class="filepath">kt_ep_wrapper.py</span> 做 CPU-GPU 异构专家划分(KTransformers),GPU 专家走上述 dispatcher、CPU 专家走 AMX/AVX 本地计算,不引入新的集合通信。EPLB 重平衡本身通过默认组的 NCCL P2P + all_reduce 搬运 expert 统计(bootstrap.py:369 预热)。</p>

  <h3>4.6 采样、logits 与一致性同步</h3>
  <table class="tbl">
    <tr><th>行为</th><th>触发条件</th><th>原语 / 库</th><th>位置</th></tr>
    <tr><td>采样 token id 对齐</td><td><code>SYNC_TOKEN_IDS_ACROSS_TP=1</code> 或存在 grammar 约束(默认关,省一次 all-reduce;采样重归一化已做到 TP 确定性)</td><td>all-reduce MIN(直接 <code>torch.distributed</code>,NCCL 设备组)</td><td>sampler.py:718-735</td></tr>
    <tr><td>采样状态聚合</td><td>每步</td><td>all-reduce MAX(attn-TP 组,CP 开时追加 CP 组)</td><td>sampler.py:598-607</td></tr>
    <tr><td>投机解码 TP 同步</td><td>spec decode + <code>SGLANG_SPEC_TP_SYNC</code>(默认 all)</td><td>tp_group.broadcast(src=0) 按站点(DSPARK/DFLASH 的 mem/plan/accept/target 等 13 个站点)从 rank0 广播决策;可用内存 all-reduce 取组最小值</td><td>speculative/spec_tp_sync.py:120-155</td></tr>
    <tr><td>语法就绪同步</td><td>结构化输出(第 9 篇)</td><td>DP 组 all_gather_object(补全/失败请求交集);PP 两侧 send/recv_object + GRAMMAR_PP_SYNC tag</td><td>constrained/grammar_manager.py:273-282,99-108</td></tr>
    <tr><td>请求分发到 TP 组</td><td>每步调度输入</td><td>rank0 从 ZMQ 收请求后,attn-CP 0→CP 组广播,再 attn-TP 组 broadcast_pyobj(gloo);或共享内存 MessageQueue(<code>SGLANG_USE_MESSAGE_QUEUE_BROADCASTER</code> 默认开,1&lt;&lt;22 B×6 chunk 环形缓冲)</td><td>request_receiver.py:238-271;shm_broadcast.py:174,487</td></tr>
    <tr><td>调度信息 all-gather</td><td>TBO 开启时统一 forward_mode</td><td>调度侧 all-gather 局部 batch 元数据</td><td>two_batch_overlap.py:399</td></tr>
  </table>
  <p>这一组行为的特点是"对象级、小体积、必须全组一致",几乎全部落在控制面的 gloo CPU 组与共享内存上;唯一例外是采样状态与 token id 同步,它们是 GPU 张量,直接走 NCCL。</p>

  <h3>4.7 CUDA Graph 捕获期通信</h3>
  <p>捕获期是通信库行为差异最大的时刻(详见<a href="/docs/inference-engines/sglang/05-cuda-graph/">第 6 篇</a>):<code>graph_capture()</code>(parallel_state.py:2298)同时进入 TP、PP、DCP、ATTN_TP、SHARED_EXPERTS_TP、MOE_EP、MOE_TP 七个组,在独立 stream 上:PyNccl/MSCCL++/symm mem 被显式 enable,custom AR 把图内缓冲地址注册到 peer,v2 把图输入指针表登记;<code>pcie_ipc</code> 的 tactic 调优刻意在 <code>prepare()</code> 阶段完成而非首条 all-reduce 时(pcie_ipc_ar.py:321-333),避免在捕获中触发 autotune;MSCCL++ 则明确拒绝任何 piecewise graph 阶段(pymscclpp.py:1151-1155)。</p>

  <h3>4.8 通信掩盖:TBO / SBO</h3>
  <p>两类"用计算盖住通信"的结构改变通信的<strong>发起方式</strong>而非库选择:<strong>TBO</strong>(two-batch-overlap)把 batch 切成两个微批,微批 A 的 DeepEP dispatch/combine 在通信流上挂起时切到微批 B 的 attention+MoE 计算;非 EP 的 DP TP-MoE 模型同样支持异步 gather/combine——两个微批共享同一条 comm stream(避免对同一 RCCL 通信器并发发起集合调用而死锁),事件对象按 (kind, subbatch) 复用(dp_attention.py:1146-1180)。<strong>SBO</strong>(single_batch-overlap)在单批内用 alt stream 让 combine/dispatch 与 down-GEMM 重叠,靠 CUDA event 传递就绪(single_batch_overlap.py:81-113)。</p>

  <h3>4.9 控制面:进程拓扑与 ZMQ</h3>
  <div class="flow">
    <div class="node">TokenizerManager<small>tokenize / detokenize</small></div><div class="arrow">→</div>
    <div class="node">DataParallelController<small>ZMQ PUSH/PULL 轮询分发</small></div><div class="arrow">→</div>
    <div class="node-accent">Scheduler × dp_size<small>gloo 广播请求到 TP 组</small></div><div class="arrow">→</div>
    <div class="node">Detokenizer<small>ZMQ ipc</small></div>
  </div>
  <p>DataParallelController 为每个 DP rank 持有一条 ZMQ PUSH socket(data_parallel_controller.py:441-443),输入来自 tokenizer 的 PULL socket;每个 Scheduler 进程的通道集合封装在 <span class="filepath">scheduler_components/ipc_channels.py</span>(PULL tokenizer、DEALER RPC、PUSH detokenizer 等)。TP 组内非 0 rank 不连 ZMQ,由 rank0 经 gloo/共享内存转发(4.6 节);PD 分离部署下 bootstrap server 也用 ZMQ REQ/REP + TCP 完成 KV 迁移的握手(第 8 篇)。多机场景可用 <span class="filepath">srt/ray/</span> 的 <code>RaySchedulerActor</code> 编排。</p>

  <h3>4.10 传输面:PD KV 迁移与位置编码传输</h3>
  <p>三个 conn 后端结构对称(bootstrap 握手 + 注册 + 异步传输):Mooncake 转移引擎支持单/批量注册与 batch_transfer_sync(mooncake/conn.py;device_communicators/mooncake_transfer_engine.py:110-288),可按 GPU 映射 IB 设备;NIXL 走 UCX agent;nixl/conn.py 侧同样有 staging 水位管理;mori 用 <code>mori.io.IOEngine</code> + ZMQ 辅助通道(mori/conn.py)。DCP 部署还内置 <code>build_dcp_token_transfer_plan</code> 按页规划迁移。多模态位置编码的跨进程传递(单节点、PP=1)默认走 <strong>CUDA IPC 内存池</strong> 而非按值序列化(positional_embeds_transport.py:22-50)。单节点前缀 KV 分片(<code>--enable-kv-cache-sharding</code>)则把 gather 缓冲注册为 NCCL 对称内存并申请 copy engine(SGLANG_ENABLE_KV_SHARD_ZERO_SM_GATHER,environ.py:644-648)——传输面反过来借用了数据面的库。</p>
</section>

<section>
<h2 class="sec" id="sec-5"><span class="num">5</span>底层通信库全解析</h2>
  <p>先给通信器实现的代码规模实测(<code>wc -l</code>,含空行注释;不含 sgl-kernel / sglang.kernels 的 CUDA 侧):</p>
  <div class="chart">
    <div class="chart-row"><div class="chart-label">parallel_state.py</div><div class="chart-track"><div class="chart-bar bar-blue" style="width:100%"></div></div><div class="chart-value">3531 行</div></div>
    <div class="chart-row"><div class="chart-label">pymscclpp.py</div><div class="chart-track"><div class="chart-bar bar-purple" style="width:36%"></div></div><div class="chart-value">1278 行</div></div>
    <div class="chart-row"><div class="chart-label">pynccl_wrapper.py</div><div class="chart-track"><div class="chart-bar bar-blue" style="width:20%"></div></div><div class="chart-value">690 行</div></div>
    <div class="chart-row"><div class="chart-label">custom_all_reduce_v2.py</div><div class="chart-track"><div class="chart-bar bar-green" style="width:17%"></div></div><div class="chart-value">597 行</div></div>
    <div class="chart-row"><div class="chart-label">triton_symm_mem_ag.py</div><div class="chart-track"><div class="chart-bar bar-orange" style="width:16%"></div></div><div class="chart-value">554 行</div></div>
    <div class="chart-row"><div class="chart-label">custom_all_reduce_utils.py</div><div class="chart-track"><div class="chart-bar bar-green" style="width:15%"></div></div><div class="chart-value">540 行</div></div>
    <div class="chart-row"><div class="chart-label">pynccl_allocator.py</div><div class="chart-track"><div class="chart-bar bar-blue" style="width:15%"></div></div><div class="chart-value">535 行</div></div>
    <div class="chart-row"><div class="chart-label">shm_broadcast.py</div><div class="chart-track"><div class="chart-bar bar-gray" style="width:15%"></div></div><div class="chart-value">520 行</div></div>
    <div class="chart-row"><div class="chart-label">custom_all_reduce.py(v1)</div><div class="chart-track"><div class="chart-bar bar-green" style="width:13%"></div></div><div class="chart-value">454 行</div></div>
    <div class="chart-row"><div class="chart-label">bootstrap.py</div><div class="chart-track"><div class="chart-bar bar-gray" style="width:13%"></div></div><div class="chart-value">451 行</div></div>
    <div class="chart-row"><div class="chart-label">pynccl.py</div><div class="chart-track"><div class="chart-bar bar-blue" style="width:12%"></div></div><div class="chart-value">432 行</div></div>
    <div class="chart-row"><div class="chart-label">pcie_ipc_ar.py</div><div class="chart-track"><div class="chart-bar bar-red" style="width:12%"></div></div><div class="chart-value">426 行</div></div>
    <div class="chart-row"><div class="chart-label">mooncake_transfer_engine.py</div><div class="chart-track"><div class="chart-bar bar-orange" style="width:10%"></div></div><div class="chart-value">366 行</div></div>
    <div class="chart-row"><div class="chart-label">quick_all_reduce.py</div><div class="chart-track"><div class="chart-bar bar-red" style="width:8%"></div></div><div class="chart-value">266 行</div></div>
    <div class="chart-row"><div class="chart-label">vocab_gather.py</div><div class="chart-track"><div class="chart-bar bar-purple" style="width:6%"></div></div><div class="chart-value">226 行</div></div>
  </div>
  <p class="small muted">图为 device_communicators/ 与 distributed/ 根下主要文件的实测行数;另有 custom_all_reduce_v2 调优表 configs/custom_all_reduce_v2.py 357 行、torch_symm_mem.py 185 行、cuda_wrapper.py 196 行、custom_all_reduce_ops.py 166 行、communication_op.py 139 行等,全目录合计 12568 行。</p>

  <h3>5.1 NCCL(两条接入线)</h3>
  <p><strong>定位:</strong>GPU 集合通信默认骨干。<strong>依赖来源:</strong>PyTorch 自带的 <code>libnccl.so.2</code>,或 <code>SGLANG_NCCL_SO_PATH</code> 指定版本。<strong>接入线一</strong>是 torch.distributed ProcessGroupNCCL(设备组后端,parallel_state.py:394),承担 eager all-reduce/all-gather/P2P 与一切 <code>torch.distributed.*</code> 直调;<strong>接入线二</strong>是 PyNccl——<span class="filepath">pynccl_wrapper.py</span> 用 ctypes 纯 Python 绑定 NCCL C API(pynccl_wrapper.py:1-26 的注释解释了为何不用 cupy/C binding:版本切换要免重编译),<span class="filepath">pynccl.py</span> 用 gloo 组广播 ncclUniqueId 后 <code>ncclCommInitRank(Config)</code> 独立建通信器(pynccl.py:96-131),支持 all_reduce/all_gather/reduce_scatter/broadcast/send/recv/all_to_all_single/group_start,并暴露 <code>ncclMemAlloc</code>+<code>ncclCommWindowRegister</code> 对称内存窗口(pynccl.py:404-408)。它默认 disabled,只在图捕获等上下文经 <code>change_state(enable=True)</code> 打开(pynccl.py:141-144)。变长集合(gatherv/scatterv)、DCP a2a、TP lm_head a2a 都只走这条线。NCCL 行为细节与环境变量见<a href="/docs/inference-engines/sglang/11-nccl-usage/">第 12 篇</a>,PR 合入史见<a href="/docs/inference-engines/sglang/12-nccl-pr-history/">第 13 篇</a>。</p>

  <h3>5.2 Gloo</h3>
  <p><strong>定位:</strong>CPU 控制面骨干。每个 GroupCoordinator 都建一个 gloo 组(parallel_state.py:404-410),承担:对象序列化广播(broadcast_pyobj、send/recv_object)、P2PTag 路由的点对点、barrier、PyNccl/MSCCL++ 的 uniqueId 握手、IPC 句柄交换、语法/投机同步。gloo 超时默认 120 分钟(parallel_state.py:308)。</p>

  <h3>5.3 自研 custom allreduce(v1 + v2 + 三个平台变体)</h3>
  <p><strong>定位:</strong>小消息 all-reduce 的主力,免 NCCL 通信器开销与启动时延。<strong>v1</strong>(<span class="filepath">custom_all_reduce.py</span>,sgl-kernel AOT 核):CUDA 侧用 cudaMalloc + cudaIpcGetMemHandle 建跨进程共享缓冲,经 <code>all_gather_object</code> 交换句柄(custom_all_reduce.py:148-173);one/two-shot 核在 <span class="filepath">custom_all_reduce_ops.py</span> 后面;上限 8MiB。<strong>v2</strong>(<span class="filepath">custom_all_reduce_v2.py</span>,JIT,默认开启 <code>SGLANG_OPT_USE_CUSTOM_ALL_REDUCE_V2</code>):把核拆成 PushPlane/PullPlane/Communicator 三个独立件(#35735),存储换成 torch <code>_SymmetricMemory</code>(empty_strided_p2p + rendezvous,custom_all_reduce_v2.py:89-104),四算法(1shot_push/2shot_push/1shot_pull/2shot_pull)+ multicast(NVLS)地址;图输入经 cudaIpc 或 VMM 句柄注册进设备侧指针表;<strong>多节点(MNNVL)只在单一 NVLink fabric clique 内放行</strong>(can_use_custom_all_reduce_v2,custom_all_reduce_v2.py:582-597;clique 判定 is_one_nvlink_clique,custom_all_reduce_utils.py:396-418)。<strong>平台变体:</strong>ROCm 默认用 aiter 的 AiterCustomAllreduce(SGLANG_USE_AITER_AR 默认 true),确定性推理时改用 SGLang 自带的 1-stage deterministic 实现(custom_all_reduce.py:377-445);MUSA 有 128MiB 上限变体;quick AR(quick_all_reduce.py)是 ROCm gfx94x/gfx95x 上带 INT8/6/4 量化的补充通道,源自 quickreduce 项目。</p>

  <h3>5.4 PyTorch symmetric memory 与 Triton symm-mem AG</h3>
  <p><strong>定位:</strong>NVLS 多播与 reduce-scatter/all-gather 融合的官方通道。<strong>TorchSymmMemCommunicator</strong>(torch_symm_mem.py:34)包装 <code>torch.ops.symm_mem.multimem_all_reduce_</code>(SM90/100 的 ws 4/6/8)与 <code>two_shot_all_reduce_</code>,bf16、64/128MiB 查表上限,经 <code>--enable-torch-symm-mem</code> 开启。<strong>NCCL 侧对称内存</strong>由 <span class="filepath">pynccl_allocator.py</span> 提供:自定义 CUDAPluggableAllocator 池 + <code>use_symmetric_memory</code> 上下文(pynccl_allocator.py:423)把张量分配进 ncclMemAlloc 窗口,首选项是 TP/DP 等长 all-gather 的输出缓冲(parallel_state.py:1433-1438);预分配量由 <code>SGLANG_SYMM_MEM_PREALLOC_GB_SIZE</code> 控制。<strong>Triton 路径</strong>(triton_symm_mem_ag.py)用 inline PTX <code>multimem.st</code> 实现 hidden 维 all-gather,服务 dspark 的 MAX_LEN gather。序列并行的 <code>fused_matmul_reduce_scatter</code>/<code>fused_all_gather_matmul</code>(layernorm_sp.py:181-182)也属此族。</p>

  <h3>5.5 MSCCL++</h3>
  <p><strong>定位:</strong>调优算法库,AllReduce 与 AllGather 两类集合,NCCL 兜底。<strong>依赖:</strong><code>mscclpp</code> Python 包。<strong>角色:</strong><span class="filepath">pymscclpp.py</span>(通信器中最大的单文件,1278 行)启动时按消息尺寸 512B~16MiB 调优出算法配置表,运行期按 nbytes 查表;要求张量提前注册,故只在 CUDA graph 内生效,并显式拒绝 piecewise graph 阶段(pymscclpp.py:1139-1155);scratch buffer 固定 128MiB(<code>_DEFAULT_GPU_BUFFER_SIZE = 1&lt;&lt;27</code>)。经 <code>--enable-mscclpp</code> 开启。</p>

  <h3>5.6 DeepEP(NVSHMEM)与 mori / NIXL</h3>
  <p><strong>定位:</strong>EP 的跨卡 token 搬运。<strong>DeepEP</strong>(<code>from deep_ep import Buffer, Config</code>,deepep.py:52)底层是 NVSHMEM RDMA:intranode NVLink / internode RDMA 双路径,low_latency 模式为纯 NVLink 微秒级 decode 设计;SGLang 会按 <code>num_max_dispatch_tokens_per_rank</code> 自动抬高 <code>NVSHMEM_QP_DEPTH</code>(默认 1024,deepep.py:79-88)。v2 的 ElasticBuffer 提供 direct(单节点)/hybrid(多节点)拓扑。<strong>mori</strong> 与 <strong>NIXL(nixl_ep,UCX)</strong>是另外两个 a2a 引擎,同时兼任 PD 传输面后端(4.10 节)——数据面与传输面在这里共享库。</p>

  <h3>5.7 FlashInfer 通信(cutedsl / trtllm / MNNVL)</h3>
  <p><strong>定位:</strong>AR+Residual+RMSNorm 融合与 a2a 的内核提供方。<strong>三个后端</strong>(exec_.py:777-793):<code>trtllm</code>(SM90 单节点 IPC workspace)、<code>mnnvl</code>(SM90/100,多节点 NVLink fabric)、<code>cutedsl</code>(Blackwell 专属,CuTe DSL,可再融合 MoE finalize 与 shared-expert add)。workspace 由 FlashInferMNNVLCuteDSLARFusion 持有(flashinfer_mnnvl_cutedsl.py:310-488),SGLang 侧做了 GB300 预设重定向与 cuMemCreate 预检。另有 K3 融合(communication/k3_ar_fusion.py)直接复用 custom AR v2 的 multicast 平台,不入 FlashInfer workspace。</p>

  <h3>5.8 Mooncake / NIXL / mori(传输面)</h3>
  <p><strong>定位:</strong>PD 分离与 KV offload 的跨实例搬运。MooncakeTransferEngine 封装 mooncake 的 transfer_engine,支持按 GPU 绑 IB 设备、单/批量注册与同步/批量转移(mooncake_transfer_engine.py:110-288),同时被 mooncake a2a dispatcher 与 HiCache offload 复用;<code>MOONCAKE_PROTOCOL/DEVICE/...</code> 等十余个环境变量在 environ.py:929-941。三者共同的上层协议(staging 水位、abort tag、DCP 迁移计划)在 <span class="filepath">disaggregation/common/</span>,细节见<a href="/docs/inference-engines/sglang/07-pd-disaggregation/">第 8 篇</a>。</p>

  <h3>5.9 ZMQ 与 shm_broadcast(控制面)</h3>
  <p><strong>定位:</strong>进程拓扑的消息总线。<strong>ZMQ</strong>:tokenizer↔DPC↔scheduler↔detokenizer 全链路,ipc:// 或 tcp:// 端点;PD bootstrap、mori 辅助通道也是它。<strong>shm_broadcast</strong>:ShmRingBuffer + MessageQueue,一个 writer 多个 reader 的无锁环形队列,元数据每 chunk 1+N 字节标志位(shm_broadcast.py:33-173),句柄经 ZMQ XPUB/SUB 发布;作为 TP 组 <code>mq_broadcaster</code> 时默认 4MiB×6 chunk(parallel_state.py:562-566)。CPU 张量在 TP 组内还有 <code>torch.ops.sgl_kernel.shm_allreduce</code> 这条共享内存捷径(parallel_state.py:711-715)。</p>

  <h3>5.10 Ray 与非 NVIDIA CCL</h3>
  <p><strong>Ray:</strong><span class="filepath">srt/ray/</span> 提供 RaySchedulerActor/RayEngine 的多机编排,进程间消息仍走 ZMQ。<strong>其他硬件的 CCL:</strong>后端映射在 <span class="filepath">platforms/device_mixin.py:88-93</span>——<code>hpu/npu → hccl</code>(NPU zbal 除外),<code>xpu</code> 走 oneCCL 系;RCCL 由 pynccl_wrapper 在 HIP 下自动换装 <code>librccl.so.1</code>(pynccl_wrapper.py:59),MUSA 用 <code>libmccl.so.2</code>。NPU 侧还有专属配置:ProcessGroupHCCL 的 <code>hccl_buffer_size</code>(含 DEEPEP_HCCL_BUFFSIZE 覆盖,parallel_state.py:104-119)、MC2/FuseEP a2a dispatcher、Ascend transfer engine(disaggregation/ascend/transfer_engine.py)。HPU/XPU 的薄包装在 <span class="filepath">hpu_communicator.py</span>(带 <code>mark_step</code> workaround)与 <span class="filepath">xpu_communicator.py</span>(gather 用 all_gather 实现)。bootstrap 日志统一写"NCCL/RCCL/HCCL warmup"(bootstrap.py:351-365),印证三平台共用同一套 GroupCoordinator。</p>
</section>

<section>
<h2 class="sec" id="sec-6"><span class="num">6</span>行为 × 通信库映射矩阵</h2>
  <p>下表每行一个跨卡行为,给出可用后端与实际选择条件("→"为默认落点):</p>
  <table class="tbl">
    <tr><th>通信行为</th><th>可选后端(按优先序)</th><th>选择条件</th></tr>
    <tr><td>TP all-reduce(eager,小消息)</td><td>custom AR v2 → custom AR v1/aiter → PCIe-IPC → quick AR(ROCm)→ MSCCL++(不选)→ torch symm mem → FlashInfer AR → PyNccl/NCCL</td><td>谓词阶梯 + 尺寸/拓扑阈值;eager 下 MSCCL++/symm mem 不参与</td></tr>
    <tr><td>TP all-reduce(CUDA graph 内)</td><td>custom AR → PCIe-IPC → quick AR → MSCCL++ → torch symm mem → PyNccl</td><td>graph_capture 打开各通信器;torch.distributed 被禁</td></tr>
    <tr><td>TP all-reduce(大消息,64/128MiB+)</td><td>→ NCCL(PyNccl 或 torch.distributed)</td><td>超出所有自研阈值</td></tr>
    <tr><td>对称内存 all-reduce</td><td>NCCL window(symm-mem)→ torch symm mem</td><td>--enable-symm-mem;等长分配</td></tr>
    <tr><td>AR + RMSNorm 融合</td><td>aiter fused AR(ROCm)→ K3 multicast push/NVLS 2shot(SM100)→ FlashInfer trtllm/mnnvl/cutedsl</td><td>平台 + 融合开关 + 尺寸(512KiB/128KiB 分界)</td></tr>
    <tr><td>TP all-gather / reduce-scatter</td><td>aiter AG/RS(ROCm)→ MSCCL++ → PyNccl → torch.distributed;序列并行融合算子(symm mem)</td><td>SGLANG_USE_AITER_AG / SGLANG_DP_USE_REDUCE_SCATTER 等</td></tr>
    <tr><td>变长 gather/scatter(gatherv/scatterv)</td><td>→ PyNccl(ncclGroupStart + Broadcast/Reduce)</td><td>唯一实现</td></tr>
    <tr><td>DP attention gather</td><td>MAX_LEN: all-gather(可 Triton multimem)→ SUM_LEN: all-reduce → 变长: all_gatherv</td><td>代价模型 sum_len*2 vs max_len*gather_width</td></tr>
    <tr><td>词表 embedding 求和 / lm_head gather</td><td>all-reduce / all-gather(attn-TP)→ NVLink vocab gather(push/pull)→ PyNccl all_to_all_single</td><td>dspark 类模型与 --enable-tp-lm-head-all-to-all</td></tr>
    <tr><td>EP dispatch/combine</td><td>DeepEP(NVSHMEM)→ mori → NIXL(UCX)→ Mooncake → FlashInfer → NPU MC2/FuseEP → standard all_gatherv</td><td>--moe-a2a-backend;normal/low_latency 按相位</td></tr>
    <tr><td>采样 token 同步</td><td>→ NCCL all-reduce MIN/MAX(torch.distributed 设备组)</td><td>SYNC_TOKEN_IDS_ACROSS_TP 或 grammar</td></tr>
    <tr><td>投机解码决策同步</td><td>→ PyNccl broadcast(src=0)</td><td>SGLANG_SPEC_TP_SYNC 站点表</td></tr>
    <tr><td>语法/请求/控制对象</td><td>→ gloo broadcast_pyobj / shm MessageQueue / ZMQ / PP send_object</td><td>进程内共享(fork)与否、是否跨节点</td></tr>
    <tr><td>PP 激活传递</td><td>torch.distributed send/recv + batch_isend_irecv(张量字典,PyNccl 优先)</td><td>send/recv,parallel_state.py:2076-2102,1912</td></tr>
    <tr><td>CUDA 图捕获期注册</td><td>cudaIpc / VMM-FABRIC 句柄交换(gloo all_gather_object)</td><td>custom AR v1/v2;pcie-ipc 提前 tune</td></tr>
    <tr><td>PD KV 迁移</td><td>Mooncake → NIXL → mori(均可做 a2a)→ Ascend(transfer_engine)</td><td>--disaggregation-transport-backend;握手走 ZMQ/TCPStore</td></tr>
    <tr><td>多模态 embedding 传输</td><td>→ CUDA IPC 内存池(单节点 PP=1);否则按值 msgpack</td><td>positional_embeds_transport.py:31-36</td></tr>
    <tr><td>RL 权重热更新</td><td>gloo 对象/tensor 广播 → DTensor reduce-scatter(DeviceMesh)</td><td>update_weights_from_tensor / from_distributed</td></tr>
  </table>
</section>

<section>
<h2 class="sec" id="sec-7"><span class="num">7</span>性能优化手法专题</h2>
  <ul>
    <li><strong>one-shot AR / 量化 AR:</strong>v2 的 1shot_push 让每 rank 直接把数据写进所有 peer 的对称槽位,配合阶段计数器做 Lamport 式同步;#42811 加入 2shot_push 并重调 SM100 TP4/8 阈值,#46197 又扩展到 SM107;#44642 给 eager 调用加了按 (nbytes, dtype) 的计划缓存。quick AR 则把 INT8/6/4 量化搬进通信,ROCm 上 <code>ROCM_QUICK_REDUCE_QUANTIZATION</code> 可选档位(environ.py:2245)。近期 #46994 把整型 all-reduce 排除出自研核(数值正确性)。</li>
    <li><strong>AR+Norm / AR+Norm+Quant 融合:</strong>一步核内完成归约+归一化(+FP8 分组量化),省 2-3 个核与中间张量;K3 在 512KiB 以下用 multicast push、以上用 NVLS 2shot(k3_ar_fusion.py:40);cutedsl 后端可把 MoE finalize 也吸进同一集合。</li>
    <li><strong>NVLS / 对称内存:</strong>三条路——NCCL window(ncclMemAlloc + graphUsageMode=1 关内部 event 同步,pynccl.py:117-131)、torch symm mem multimem、custom AR v2 的 multicast 指针;DP attention 甚至为"能走对称内存"而偏好 MAX_LEN padding(dp_attention.py:198-204)。KV 分片 gather 亦复用此机制实现"0 SM"搬运(#44029)。</li>
    <li><strong>overlap 掩盖:</strong>TBO 双微批交替(4.8 节)、SBO 单批双流、DP TP-MoE 的共享 comm stream + 持久化事件;本质都是把集合通信挪出关键路径。</li>
    <li><strong>注册与预热:</strong>通信器在启动期统一装配;NCCL 预热消 P99 冷启动;EPLB P2P 预热物化批量传输资源;lm_head a2a 预热确保图内 P2P 资源已建;pcie-ipc 的 tactic 调优结果持久化到 FlashInfer 缓存,只有首台机器付费。</li>
    <li><strong>P2P 实测而非信任驱动:</strong><code>can_actually_p2p</code> 用双进程真实写穿 IPC 缓冲验证驱动报告(custom_all_reduce_utils.py:149-231),结果按 CUDA_VISIBLE_DEVICES 缓存 JSON——曾因驱动误报导致静默错误。</li>
  </ul>

  <h3>7.1 通信子系统近期演进(git log 实录)</h3>
  <p><code>git log -- python/sglang/srt/distributed/</code> 显示这一层仍在高速迭代,主线是把自研 AR 的覆盖面做宽、把平台差异收干净:</p>
  <div class="timeline">
    <div class="timeline-item">
      <div class="timeline-time">#35735</div>
      <div class="timeline-body"><span class="timeline-tag">Refactor</span><strong>custom all-reduce v2 拆分为 push/pull 双平面</strong>
        <p>把单一通信器拆成 <code>PushPlane</code>(零填充对称推送槽 + 阶段计数)与 <code>PullPlane</code>(对称拉取缓冲 + 每块信号量),自此 K3 融合、词表 gather 都能只借信号量而自带输入(<span class="filepath">custom_all_reduce_v2.py:1-28</span> 的模块文档即是这一结构的说明)。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">#42811 / #44642</div>
      <div class="timeline-body"><span class="timeline-tag">Perf</span><strong>2shot_push 算法与 eager 计划缓存</strong>
        <p>新增 two-shot push 并重调 SM100 TP4/8 阈值;随后给 eager 调用按 (nbytes, dtype) 缓存 (module, algo, multicast) 计划(<code>_eager_plans</code>,custom_all_reduce_v2.py:423-439),把阶梯查询从每层两次降到一次。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">#44029</div>
      <div class="timeline-body"><span class="timeline-tag">Perf</span><strong>KVShard:0 SM 的 KV cache all-gather</strong>
        <p>单节点前缀分片把 gather 缓冲注册为 NCCL 对称内存并申请 copy engine,归约搬运不再占用 SM(<code>SGLANG_ENABLE_KV_SHARD_ZERO_SM_GATHER</code>,environ.py:644-648)——传输面借用数据面库的典型样本。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">#45950 / #46592</div>
      <div class="timeline-body"><span class="timeline-tag">Fix</span><strong>NPU 通信器去重与 EPLB 多节点预热</strong>
        <p>移除冗余的 NPU 专属 communicator,统一并入 GroupCoordinator;EPLB 在多节点布局上预热默认组的 NCCL P2P 批量传输,避免运行期冷启动。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">#46853 / #46994</div>
      <div class="timeline-body"><span class="timeline-tag">Fix</span><strong>v2 多节点 VMM 门槛移除与整型 AR 隔离</strong>
        <p>多节点(MNNVL)组不再强制 VMM 分配器(fabric 句柄即可);整型张量的 all-reduce 被排除出自研核(核只支持 fp32/fp16/bf16,整型会静默算错),回落 NCCL。</p>
      </div>
    </div>
    <div class="timeline-item">
      <div class="timeline-time">#47033 / #46197</div>
      <div class="timeline-body"><span class="timeline-tag">Perf</span><strong>NVLink 上原位读 Engram 行 + SM107 阈值</strong>
        <p>DeepSeek v4.1 的 GPU 侧 Engram 表默认经 NVLink 原位读 peer 行,免搬运;2shot_push 启发式扩展到 SM107 的 TP4/TP8/TP16。两笔都说明"通信"与"访存"的边界在 NVLink 一致性域内正被主动抹平。</p>
      </div>
    </div>
  </div>
</section>

<section>
<h2 class="sec" id="sec-8"><span class="num">8</span>配置项与环境变量</h2>
  <table class="tbl">
    <tr><th>ServerArgs / 环境变量</th><th>默认</th><th>说明(实测位置)</th></tr>
    <tr><td><code>--disable-custom-all-reduce</code></td><td>False</td><td>关闭自研 AR,回退 NCCL(exec_.py:732)</td></tr>
    <tr><td><code>--enable-mscclpp</code></td><td>False</td><td>MSCCL++ 调优 AllReduce/AllGather(exec_.py:739)</td></tr>
    <tr><td><code>--enable-torch-symm-mem</code></td><td>False</td><td>SM90+:ws 4/6/8;SM100:ws 6/8(exec_.py:743)</td></tr>
    <tr><td><code>--moe-a2a-backend</code></td><td>none</td><td>none/deepep/deepep_v2/mooncake/nixl/mori/ascend_fuseep/ascend_ops/flashinfer/megamoe/pplx/flashinfer_megamoe(exec_.py:843)</td></tr>
    <tr><td><code>--deepep-mode</code></td><td>auto</td><td>auto=decode 走 low_latency、prefill 走 normal(exec_.py:905)</td></tr>
    <tr><td><code>--flashinfer-allreduce-fusion-backend</code></td><td>None</td><td>auto/trtllm/mnnvl/cutedsl(exec_.py:777)</td></tr>
    <tr><td><code>--enable-symm-mem</code> / <code>--boundary-reduction</code> / <code>--enable-scattered-sconv</code> / <code>--enable-quant-communications</code></td><td>False/auto/False/False</td><td>对称内存、边界 rs/rsv、分散短卷积、NPU INT8 通信(exec_.py:748-770)</td></tr>
    <tr><td><code>SGLANG_OPT_USE_CUSTOM_ALL_REDUCE_V2</code> / <code>..._V2_MAX_SIZE_KB</code></td><td>True / 16384</td><td>v2 开关与工作区上限(environ.py:1598,1601)</td></tr>
    <tr><td><code>SGLANG_ENABLE_PCIE_IPC_ALLREDUCE</code> / <code>SGLANG_PCIE_IPC_MAX_NUMEL</code></td><td>False / 0</td><td>无 NVLink 机型专用 AR(environ.py:1605-1606)</td></tr>
    <tr><td><code>SGLANG_SYMM_MEM_PREALLOC_GB_SIZE</code></td><td>-1</td><td>对称内存池预分配(environ.py:2282)</td></tr>
    <tr><td><code>SGLANG_USE_MESSAGE_QUEUE_BROADCASTER</code></td><td>True</td><td>TP 组 shm 广播(environ.py:377)</td></tr>
    <tr><td><code>SGLANG_SPEC_TP_SYNC</code></td><td>all</td><td>投机解码 TP 同步站点集(environ.py:1690)</td></tr>
    <tr><td><code>SGLANG_TCP_STORE_PORT</code></td><td>29600</td><td>NIXL rendezvous(environ.py:378)</td></tr>
    <tr><td><code>SGLANG_DP_USE_GATHERV</code> / <code>SGLANG_DP_USE_REDUCE_SCATTER</code> / <code>SGLANG_USE_AITER_AG</code></td><td>off / HIP 才 on / True</td><td>DP 变长路径、aiter RS/AG(environ.py:1020-1025)</td></tr>
  </table>
  <p>NCCL_* 与 NCCL_CTA_POLICY、SGLANG_DETERMINISTIC_NCCL_NCHANNELS 等请参阅<a href="/docs/inference-engines/sglang/11-nccl-usage/">第 12 篇</a>的环境治理一节;Mooncake 传输变量见 5.8 节。</p>
</section>

<section>
<h2 class="sec" id="sec-9"><span class="num">9</span>小结与系列交叉引用</h2>
  <p>SGLang 的跨卡通信不是"用一个库做所有事",而是一个三平面、按谓词竞选的体系:控制面把一致性问题全部压在 gloo/ZMQ/共享内存上,避免在 GPU 关键路径上做对象通信;数据面让 8 种通信器在同一 <code>GroupCoordinator.all_reduce</code> 入口后按"尺寸 × 拓扑 × 图模式"竞争,NCCL 是兜底而非默认主角;传输面独立成 disaggregation 子树,却与数据面共享 Mooncake/NIXL/mori 库。理解第 3 节的谓词阶梯,基本就能预测任何一次前向中每条通信会落到哪个库。</p>
  <ul>
    <li><a href="/docs/inference-engines/sglang/03-parallelism/">第 4 篇 · 并行策略</a>——TP/DP/EP/PP/CP/DCP 的组划分与通信量推导,本篇第 2 节的前置;</li>
    <li><a href="/docs/inference-engines/sglang/05-cuda-graph/">第 6 篇 · CUDA Graph</a>——4.7 节捕获期通信的完整图景;</li>
    <li><a href="/docs/inference-engines/sglang/07-pd-disaggregation/">第 8 篇 · PD 分离</a>——4.10 节传输面的调度与迁移协议;</li>
    <li><a href="/docs/inference-engines/sglang/08-structured-output/">第 9 篇 · 结构化输出</a>——4.6 节语法同步为什么必须跨 rank;</li>
    <li><a href="/docs/inference-engines/sglang/11-nccl-usage/">第 12 篇 · NCCL 使用</a>与<a href="/docs/inference-engines/sglang/12-nccl-pr-history/">第 13 篇 · NCCL 合入历史</a>——NCCL 这一个库的纵深视角。</li>
  </ul>
</section>

  <div class="pgnav">
    <span>SGLang 深度解析系列 · ⑬ 跨卡通信行为全景 · 源码级分析基于 main @ b146a8576d · ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/sglang/12-nccl-pr-history/">← NCCL 相关 PR 历史</a> &nbsp;·&nbsp; <a href="/docs/inference-engines/sglang/">返回系列总览 →</a> &nbsp;·&nbsp; <a href="/docs/inference-engines/sglang/">返回总览</a></span>
  </div>
<script>
(function(){
// 滚动显现
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)});
// ===== 动画场景播放控制(暂停/重播/倍速) =====
function mkBtn(t){var b=document.createElement('button');b.type='button';b.textContent=t;return b}
function setRate(sc,rate){
  var els=sc.querySelectorAll('*');
  for(var i=0;i<els.length;i++){
    var el=els[i];
    if(el.classList&&el.classList.contains('scene-bar'))continue;
    var cs=window.getComputedStyle(el);
    if(!cs.animationDuration||cs.animationDuration==='0s')continue;
    if(!el.getAttribute('data-base-dur'))el.setAttribute('data-base-dur',cs.animationDuration);
    if(!el.getAttribute('data-base-del'))el.setAttribute('data-base-del',cs.animationDelay);
    el.style.animationDuration=(parseFloat(el.getAttribute('data-base-dur'))/rate)+'s';
    el.style.animationDelay=(parseFloat(el.getAttribute('data-base-del'))/rate)+'s';
  }
}
function initScene(sc){
  if(sc.getAttribute('data-anim-init'))return;
  sc.setAttribute('data-anim-init','1');
  var bar=document.createElement('div');bar.className='scene-bar';
  var bp=mkBtn('\u23F8 暂停');
  bp.addEventListener('click',function(){
    var p=sc.classList.toggle('paused');
    bp.textContent=p?'\u25B6 播放':'\u23F8 暂停';
    bp.classList.toggle('on',p);
  });
  var br=mkBtn('\u21BA 重播');
  br.addEventListener('click',function(){
    sc.classList.remove('paused');bp.textContent='\u23F8 暂停';bp.classList.remove('on');
    sc.classList.add('hold');void sc.offsetWidth;sc.classList.remove('hold');
  });
  var sps=[];
  [['0.5\u00D7',0.5],['1\u00D7',1],['2\u00D7',2]].forEach(function(s){
    var b=mkBtn(s[0]);b.setAttribute('data-rate',String(s[1]));
    if(s[1]===1)b.classList.add('on');
    b.addEventListener('click',function(){
      for(var k=0;k<sps.length;k++)sps[k].classList.remove('on');
      b.classList.add('on');setRate(sc,s[1]);
    });
    sps.push(b);
  });
  bar.appendChild(bp);bar.appendChild(br);
  for(var j=0;j<sps.length;j++)bar.appendChild(sps[j]);
  sc.appendChild(bar);
}
var ss=document.querySelectorAll('.scene');
for(var i=0;i<ss.length;i++)initScene(ss[i]);
})();
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>NCCL 使用场景全景</title><link>https://hccl.club/docs/inference-engines/vllm/13-nccl-usage/</link><pubDate>Sat, 07 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/vllm/13-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: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 .tag.nccl{border-color:rgba(251,191,36,.45);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 section>h3{font-size:17.5px;color:var(--accent2);margin:30px 0 12px;display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.fwdoc section>h3 .badge{transform:translateY(-1px)}
.fwdoc em{color:var(--good);font-style:normal}
.fwdoc code{font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px;background:rgba(79,140,255,.13);
  color:var(--accent2);padding:1.5px 7px;border-radius:6px}
.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 b{color:#fff}
.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 ul.chain{list-style:none;margin:12px 0;padding:12px 18px;background:var(--code-bg);border:1px solid var(--border);
  border-radius:12px;font-size:13.5px}
.fwdoc ul.chain li{padding:5px 0 5px 26px;position:relative;color:var(--text)}
.fwdoc ul.chain li::before{content:"↳";position:absolute;left:4px;color:var(--accent2)}
.fwdoc ul.chain li.first::before{content:"▶";color:var(--warn)}
.fwdoc ul.chain li code{font-size:12.2px}
.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;color:#c4d0e8}
.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: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{white-space:nowrap;font-size:12px;padding:1px 6px;border-radius:5px}
.fwdoc table.tbl a{color:var(--accent2)}
.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 .klabel{font-size:11px;color:#5a6b92;letter-spacing:1px;text-transform:uppercase;margin-bottom:10px}
.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 .stack{display:flex;flex-direction:column;gap:9px;position:relative;margin:18px 8px 6px}
.fwdoc .layer{border:1px solid var(--border);border-radius:9px;padding:9px 16px;background:#101b31;
  display:flex;justify-content:space-between;align-items:center;gap:10px}
.fwdoc .layer .ln{font-family:"JetBrains Mono",Consolas,monospace;font-size:11px;color:var(--muted);white-space:nowrap}
.fwdoc .layer .nm{font-size:13.5px;color:var(--text)}
.fwdoc .layer .nm code{background:transparent;padding:0;color:#89ddff;font-size:12.5px}
.fwdoc .pkt{position:absolute;left:-6px;width:14px;height:14px;border-radius:50%;
  background:radial-gradient(circle,var(--accent2),var(--accent));
  box-shadow:0 0 14px 3px rgba(34,211,238,.75);animation:fw-drop 14s linear infinite;z-index:5}
@keyframes fw-drop{0%{top:6px;opacity:0}6%{opacity:1}94%{opacity:1}100%{top:calc(100% - 20px);opacity:0}}
.fwdoc .l1{animation:fw-glowB 14s linear infinite;animation-delay:0s}
.fwdoc .l2{animation:fw-glowC 14s linear infinite;animation-delay:2.2s}
.fwdoc .l3{animation:fw-glowY 14s linear infinite;animation-delay:4.4s}
.fwdoc .l4{animation:fw-glowP 14s linear infinite;animation-delay:6.6s}
.fwdoc .l5{animation:fw-glowG 14s linear infinite;animation-delay:8.8s}
.fwdoc .l6{animation:fw-glowR 14s linear infinite;animation-delay:11s}
@keyframes fw-glowB{0%,16%{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent) inset}16.5%,100%{border-color:var(--border);box-shadow:none}}
@keyframes fw-glowC{0%,16%{border-color:var(--border)}20%,36%{border-color:var(--accent2);box-shadow:0 0 0 1px var(--accent2) inset}36.5%,100%{border-color:var(--border);box-shadow:none}}
@keyframes fw-glowY{0%,38%{border-color:var(--border)}42%,58%{border-color:var(--warn);box-shadow:0 0 0 1px var(--warn) inset}58.5%,100%{border-color:var(--border);box-shadow:none}}
@keyframes fw-glowP{0%,60%{border-color:var(--border)}64%,78%{border-color:var(--purple);box-shadow:0 0 0 1px var(--purple) inset}78.5%,100%{border-color:var(--border);box-shadow:none}}
@keyframes fw-glowG{0%,80%{border-color:var(--border)}84%,92%{border-color:var(--good);box-shadow:0 0 0 1px var(--good) inset}92.5%,100%{border-color:var(--border);box-shadow:none}}
@keyframes fw-glowR{0%,93%{border-color:var(--border)}94.5%,100%{border-color:var(--bad);box-shadow:0 0 0 1px var(--bad) inset}}
.fwdoc ul.al{list-style:none;margin:14px 4px 0;font-size:13px;color:var(--muted)}
.fwdoc ul.al li{padding:3px 0 3px 24px;position:relative}
.fwdoc ul.al li::before{content:"◆";position:absolute;left:2px;color:var(--accent2);font-size:10px;top:8px}
.fwdoc ul.al b{color:var(--text);font-weight:600}
.fwdoc .legend{display:flex;flex-wrap:wrap;gap:16px;margin:14px 4px 0;font-size:12.5px;color:var(--muted)}
.fwdoc .legend i{display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:5px;vertical-align:-1px}
.fwdoc .dispatch{margin:14px 4px}
.fwdoc .lanes{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;margin-bottom:16px}
@media(max-width:900px){.fwdoc .lanes{grid-template-columns:1fr}}
.fwdoc .lane{border:1px solid var(--border);border-radius:10px;padding:12px 14px;background:#0e1729;text-align:center}
.fwdoc .lane b{font-size:14px;display:block;margin-bottom:3px}
.fwdoc .lane span{font-size:12px;color:var(--muted);display:block;line-height:1.5}
.fwdoc .laneA{animation:fw-hiA 15s linear infinite}
.fwdoc .laneB{animation:fw-hiB 15s linear infinite}
.fwdoc .laneC{animation:fw-hiC 15s linear infinite}
@keyframes fw-hiA{0%,24%{border-color:var(--border);box-shadow:none;background:#0e1729}26%,44%{border-color:var(--good);box-shadow:0 0 16px rgba(52,211,153,.35);background:#10261c}46%,100%{border-color:var(--border);box-shadow:none;background:#0e1729}}
@keyframes fw-hiB{0%,9%{border-color:var(--accent);box-shadow:0 0 16px rgba(79,140,255,.4);background:#0f1e3e}11%,25%{border-color:var(--border);box-shadow:none;background:#0e1729}47%,80%{border-color:var(--accent);box-shadow:0 0 16px rgba(79,140,255,.4);background:#0f1e3e}83%,100%{border-color:var(--border);box-shadow:none;background:#0e1729}}
@keyframes fw-hiC{0%,83%{border-color:var(--border);box-shadow:none}85%,99%{border-color:var(--purple);box-shadow:0 0 16px rgba(167,139,250,.4);background:#1d1a38}100%{border-color:var(--purple)}}
.fwdoc .axis{position:relative;height:34px;margin:6px 6px 0}
.fwdoc .axis-bar{position:absolute;left:0;right:0;top:12px;height:10px;border-radius:6px;
  background:linear-gradient(90deg,var(--good),var(--warn) 40%,var(--accent) 75%,var(--purple));opacity:.55}
.fwdoc .axis i{position:absolute;top:26px;font-style:normal;font-size:11.5px;color:var(--muted);transform:translateX(-50%);white-space:nowrap}
.fwdoc .cursor{position:absolute;top:-8px;left:0;width:3px;height:30px;background:var(--accent2);
  box-shadow:0 0 10px var(--accent2);border-radius:2px;animation:fw-sweep 15s linear infinite}
.fwdoc .cursor::after{content:"▼";position:absolute;top:-16px;left:-6px;color:var(--accent2);font-size:11px}
@keyframes fw-sweep{0%{left:1%}99%{left:99%}100%{left:1%}}
.fwdoc .facts{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:12px;margin:14px 0}
.fwdoc .facts .f{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:12px;padding:13px 16px;font-size:13px}
.fwdoc .facts .f b{color:var(--accent2);display:block;font-size:14px;margin-bottom:3px}
.fwdoc .facts .f span{color:var(--muted);font-size:12.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">NCCL 是 vLLM 多卡/多机推理的通信底座;vLLM 没有把通信全部丢给 torch.distributed,而是自建了一套按消息尺寸 / 世界大小 / 硬件拓扑动态分发的通信网络。</p>
    <p>NCCL(NVIDIA Collective Communications Library)是 vLLM 在 <em>NVIDIA GPU 多卡/多机</em> 场景下的通信底座:张量并行(TP)的 <code>all_reduce</code>、<code>all_gather</code> 与 <code>reduce_scatter</code>、专家并行(EP)的 all-to-all、流水线并行(PP)的隐状态 send/recv、乃至与外部训练器之间的权重热更新,底层都由 NCCL 承载。但 vLLM 并不直接把所有通信丢给 <code>torch.distributed</code>:它在 <code>vllm/distributed/device_communicators/</code> 下自建了一条 <em>纯 Python ctypes 封装</em>(<code>PyNcclCommunicator</code> + <code>NCCLLibrary</code>),配合 <code>custom_all_reduce.py</code>、<code>symm_mem.py</code> 等替代后端,构成一张按 <em>消息尺寸 / 世界大小 / 硬件拓扑</em> 动态分发的通信网络。</p>
    <p>本篇从真实代码出发,穷举 vLLM 中所有使用 NCCL 的场景:封装层的设计动机(stream 级控制、CUDA Graph 捕获安全、独立 world)、<code>CudaCommunicator.all_reduce</code> 的真实分发逻辑、12 类触发场景的调用链,以及 ROCm(RCCL)/XPU(xccl)/CPU(gloo) 多平台差异。所有结论均标注真实文件路径与行号,可直接对照源码验证。</p>
    <div class="card reveal">
      <h3><span class="ico">🧭</span>本篇阅读路线</h3>
      <ul class="feat">
        <li><b>只想知道"我的 all_reduce 走了哪条路"</b>:直读场景 2 + 动画 3,再看启动日志 <code>_log_all_reduce_backend_selection</code></li>
        <li><b>关心 CUDA Graph 里通信为什么不炸</b>:场景 7 + 封装层设计要点 2(流控制)</li>
        <li><b>要做在线权重热更新 / 与 JAX trainer 对接</b>:场景 11 + 封装层设计要点 3(独立 world)</li>
        <li><b>排障与调优</b>:场景 9(环境变量)+ 场景 13(排查速查表)</li>
        <li><b>想快速建立全局感</b>:先看图 13-1 调用栈分层 + 动画 1,再回来按场景精读</li>
        <li><b>关心 ROCm / XPU / CPU 差异</b>:场景 10 一张表讲完,另见第 7 节末尾的平台视角</li>
      </ul>
    </div>
  </section>

  <!-- ============ 2 背景与动机 ============ -->
  <section id="s2">
    <h2 class="sec"><span class="num">2</span>背景与动机:推理引擎为什么需要 NCCL</h2>
    <p class="lede">推理引擎的两个刚性约束——每 token 都在关键路径上、CUDA Graph 里不能有任何"非法调用"——决定了 vLLM 对 NCCL 的使用方式:按尺寸精确分工,而非全盘托付。</p>
    <h3>NCCL 是什么</h3>
    <p>NCCL 是 NVIDIA 提供的集合通信库,实现了 <code>all_reduce / broadcast / reduce_scatter / all_gather / send / recv</code> 等原语,并针对硬件拓扑自动选择算法:单机 NVLink 上用 <em>Ring</em> 环形规约或 <em>NVLS</em>(NVLink SHARP,交换机内归约),跨机走 InfiniBand/RoCE 的 <em>Ring / Tree / CollNet</em>。它的 API 是 C 接口,每个原语都以 <code>cudaStream_t</code> 结尾——即 NCCL 是一个 <em>纯异步、流式</em> 的库:调用立即返回,计算在指定流上排队执行,通信期间 CPU 完全自由。</p>
    <h3>推理引擎的两个刚性约束</h3>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">⏱️</span>约束一:每 token 都在关键路径上</h3>
        <p>训练中一次 all_reduce 对应几百个 token 的梯度;而 vLLM 解码阶段每次 forward 的 TP all_reduce 只搬运<em>当前 step 的激活值</em>——消息小(几 KB 到几百 KB)、频率极高(每个 Transformer 层一次)。此时集合通信的<em>启动延迟</em>比带宽更重要,这正是 <code>CustomAllreduce</code>(IPC + P2P 单跳)与对称内存(NVLS)被引入的原因:小消息根本不必走 NCCL 的通用路径。反过来,大模型 TP&gt;8 或多机时单条消息可达数十 MB,此时 NCCL 的带宽调度又无可替代——所以 vLLM 的选择不是"用不用 NCCL",而是<em>按尺寸精确分工</em>。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🎬</span>约束二:CUDA Graph 里不能有任何"非法调用"</h3>
        <p>vLLM V1 的解码靠 CUDA Graph 消除 CPU 开销,捕获期间所有 GPU 工作必须只提交到捕获流,且<em>禁止同步类 API</em>(cudaStreamSynchronize、事件查询等)。<code>torch.distributed.all_reduce</code> 在 NCCL 之上叠了不少潜在同步 API,历史上无法安全入图——这就是 <code>pynccl_wrapper.py</code> 文件头注释里记录的动机:试过 <code>cupy</code>(初始化易卡死)、试过 <code>torch.distributed</code>(含图捕获禁用的 CUDA API,见 PyTorch 官方论坛讨论),也否决了 C/C++ 绑定(每换一个 NCCL 版本都要重新编译,见 NVIDIA/nccl#1234)。最终方案是 <em>纯 Python ctypes 绑定</em>:换库只需改 <code>VLLM_NCCL_SO_PATH</code> 环境变量,零重编译。</p>
      </div>
    </div>
    <h3>NCCL 的执行模型:vLLM 视角</h3>
    <table class="tbl reveal">
      <tr><th>概念</th><th>含义</th><th>vLLM 中的对应</th></tr>
      <tr><td>communicator(<code>ncclComm_t</code>)</td><td>一次 <code>ncclCommInitRank</code> 的产物,绑定一个 world 与探测好的拓扑(通道、算法)</td><td>c10d 组内嵌一个;每个 TP/DP/EP 组各建一个 <code>PyNcclCommunicator</code>;PP 旁路与权重热更新再建独立若干个</td></tr>
      <tr><td>unique id(<code>ncclUniqueId</code>)</td><td>128 字节会合令牌,rank 0 调 <code>ncclGetUniqueId</code> 生成,经带外通道发给全员</td><td>经 gloo 组 <code>dist.broadcast</code>(pynccl.py:157)或 <code>StatelessProcessGroup.broadcast_obj</code>;跨进程时以 base64 传递(场景 11)</td></tr>
      <tr><td>stream(<code>cudaStream_t</code>)</td><td>每个原语的最后一个参数,决定 kernel 入哪个流——NCCL 自己不创建流</td><td>pynccl 全部原语缺省 <code>current_stream()</code>;图捕获期间即捕获流(场景 7 的全部秘密)</td></tr>
      <tr><td>group(<code>ncclGroupStart/End</code>)</td><td>把多个调用合并为一次拓扑调度,典型用于变长集合与批量 p2p</td><td><code>all_gatherv / reduce_scatterv / all_to_all_single / batch_isend_irecv</code> 以及 EPLB 专家搬运</td></tr>
      <tr><td>window(用户缓冲注册)</td><td><code>ncclCommWindowRegister</code> 把用户显存注册进通信器,启用 NVLS 零拷贝</td><td><code>pynccl_allocator.py</code> 的对称内存池 + <code>register_comm_window_raw</code>(场景 8)</td></tr>
      <tr><td>算法(Ring/Tree/NVLS/GIN)</td><td>NCCL 内部按消息尺寸与拓扑自动选择,可用环境变量干预</td><td><code>pin_nccl_env</code> 精细 pin;BatchInvariant 强制单通道 Tree(场景 9);GIN 用作 DeepEPv2 的能力探针(场景 6)</td></tr>
    </table>
    <h3>为什么还需要"独立 world"</h3>
    <p>PyTorch 的 ProcessGroup 由全局 world 划分而来,而 vLLM 有几类通信需要<em>完全独立的 NCCL communicator</em>:权重热更新要与外部 trainer(JAX/PyTorch)组成一个与推理 TP 无关的 world;EPLB 专家再平衡要按专家粒度收发;Elastic EP 新 worker 通过 128 字节的 <code>ncclUniqueId</code> 带外加入,不经过 TCPStore 握手。这些场景都由 <code>PyNcclCommunicator</code>(必要时用 <code>from_unique_id_bytes</code> 构造)实现,互不干扰——这是自建封装相对 c10d 的核心增量能力之一。</p>
  </section>

  <!-- ============ 3 封装层架构 ============ -->
  <section id="s3">
    <h2 class="sec"><span class="num">3</span>NCCL 封装层架构(调用栈分层)</h2>
    <p class="lede"><span class="filepath">vllm/distributed/</span><span class="filepath">vllm/distributed/device_communicators/</span>整个调用栈自上而下分六层,一次 TP 解码 all_reduce 从模型层一路下探到 NVLink/NVSwitch 与 InfiniBand 硬件。</p>
    <p>整个调用栈自上而下分六层。以 TP 解码一次 <code>all_reduce</code> 为例:<code>RowParallelLinear.forward</code> 调用 <code>communication_op.tensor_model_parallel_all_reduce</code>;由于 CUDA 平台 <code>use_custom_op_collectives()</code> 返回 <code>True</code>(platforms/cuda.py:712),<code>GroupCoordinator.all_reduce</code> 走 <code>torch.ops.vllm.all_reduce(input_, group_name=...)</code> 自定义 op(为了 torch.compile 可追踪、CUDA Graph 可捕获),再按 group name 查回 <code>GroupCoordinator</code>,交给 <code>CudaCommunicator.all_reduce</code> 做<em>按尺寸分发</em>;命中 NCCL 路径时进入 <code>PyNcclCommunicator.all_reduce</code>,由 <code>NCCLLibrary</code> 直接调 <code>libnccl.so.2</code> 的 C 符号,把工作提交到<em>当前流</em>(图捕获时即捕获流),最终由 NVLink/NVSwitch 或 IB 硬件完成传输。</p>

    <div class="figure reveal">
      <div class="klabel">ARCH · NCCL 六层调用栈</div>
      <svg viewBox="0 0 900 470" xmlns="http://www.w3.org/2000/svg" font-family="JetBrains Mono,Consolas,monospace">
        <defs>
          <marker id="ar" 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>
          <marker id="arb" 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>
        <!-- L6 模型层 -->
        <rect x="130" y="12" width="640" height="46" rx="9" fill="#141d33" stroke="#4f8cff"/>
        <text x="450" y="31" fill="#4f8cff" font-size="13" text-anchor="middle" font-weight="bold">⑥ 模型层:RowParallelLinear / LogitsProcessor / FusedMoE / PP 传递</text>
        <text x="450" y="48" fill="#8ea0c2" font-size="11" text-anchor="middle">linear.py:1822 → tensor_model_parallel_all_reduce(output_parallel)</text>
        <line x1="450" y1="58" x2="450" y2="76" stroke="#8ea0c2" stroke-width="1.5" marker-end="url(#ar)"/>
        <!-- L5 -->
        <rect x="130" y="78" width="640" height="46" rx="9" fill="#141d33" stroke="#22d3ee"/>
        <text x="450" y="97" fill="#22d3ee" font-size="13" text-anchor="middle" font-weight="bold">⑤ communication_op.py + parallel_state.py:torch.ops.vllm.all_reduce(group_name)</text>
        <text x="450" y="114" fill="#8ea0c2" font-size="11" text-anchor="middle">GroupCoordinator:custom op → 按 group_name 查组 → device_communicator.all_reduce</text>
        <line x1="450" y1="124" x2="450" y2="142" stroke="#8ea0c2" stroke-width="1.5" marker-end="url(#ar)"/>
        <!-- L4 -->
        <rect x="130" y="144" width="640" height="50" rx="9" fill="#141d33" stroke="#fbbf24"/>
        <text x="450" y="164" fill="#fbbf24" font-size="13" text-anchor="middle" font-weight="bold">④ CudaCommunicator.all_reduce — 分发枢纽(cuda_communicator.py:384)</text>
        <text x="450" y="182" fill="#8ea0c2" font-size="11" text-anchor="middle">按 nbytes / world_size / 平台 / BatchInvariant 依次尝试各后端,全部拒绝才落到 PyNccl</text>
        <!-- 分发到 L3 各后端 -->
        <line x1="220" y1="194" x2="220" y2="228" stroke="#8ea0c2" stroke-width="1.2" marker-end="url(#ar)"/>
        <line x1="385" y1="194" x2="385" y2="228" stroke="#8ea0c2" stroke-width="1.2" marker-end="url(#ar)"/>
        <line x1="550" y1="194" x2="550" y2="228" stroke="#8ea0c2" stroke-width="1.2" marker-end="url(#ar)"/>
        <line x1="705" y1="194" x2="705" y2="228" stroke="#4f8cff" stroke-width="1.8" marker-end="url(#arb)"/>
        <!-- L3 后端行 -->
        <g font-size="11.5">
          <rect x="60" y="230" width="240" height="70" rx="9" fill="#0e1729" stroke="#34d399"/>
          <text x="180" y="251" fill="#34d399" text-anchor="middle" font-weight="bold">custom_all_reduce.py</text>
          <text x="180" y="268" fill="#8ea0c2" text-anchor="middle">CustomAllreduce</text>
          <text x="180" y="286" fill="#8ea0c2" text-anchor="middle">IPC+P2P,单节点小/中消息</text>
          <rect x="320" y="230" width="240" height="70" rx="9" fill="#0e1729" stroke="#a78bfa"/>
          <text x="440" y="251" fill="#a78bfa" text-anchor="middle" font-weight="bold">symm_mem.py / flashinfer / quick</text>
          <text x="440" y="268" fill="#8ea0c2" text-anchor="middle">SymmMemCommunicator 等</text>
          <text x="440" y="286" fill="#8ea0c2" text-anchor="middle">NVLS / MNNVL / quickreduce</text>
          <rect x="580" y="230" width="240" height="70" rx="9" fill="#0e1729" stroke="#f87171"/>
          <text x="700" y="251" fill="#f87171" text-anchor="middle" font-weight="bold">base_device_communicator</text>
          <text x="700" y="268" fill="#8ea0c2" text-anchor="middle">c10d 兜底:torch.distributed.all_reduce</text>
          <text x="700" y="286" fill="#8ea0c2" text-anchor="middle">(device_group = ProcessGroupNCCL)</text>
          <rect x="60" y="320" width="760" height="64" rx="9" fill="#101f3e" stroke="#4f8cff" stroke-width="1.8"/>
          <text x="440" y="341" fill="#4f8cff" text-anchor="middle" font-weight="bold" font-size="13">③ PyNcclCommunicator(pynccl.py)+ pynccl_allocator.py(对称内存 window)</text>
          <text x="440" y="359" fill="#8ea0c2" text-anchor="middle">独立 ncclComm_t · 传入 current_stream() · group_start/end · register_comm_window</text>
          <text x="440" y="375" fill="#8ea0c2" text-anchor="middle">from_unique_id_bytes() 支持带外 unique-id 会合(权重热更新 / elastic EP)</text>
        </g>
        <line x1="705" y1="300" x2="705" y2="318" stroke="#4f8cff" stroke-width="1.8" marker-end="url(#arb)"/>
        <line x1="440" y1="384" x2="440" y2="400" stroke="#4f8cff" stroke-width="1.8" marker-end="url(#arb)"/>
        <!-- L2 -->
        <rect x="60" y="402" width="760" height="26" rx="8" fill="#141d33" stroke="#263352"/>
        <text x="440" y="419" fill="#dbe4f5" font-size="12" text-anchor="middle">② NCCLLibrary(pynccl_wrapper.py)— ctypes.CDLL("libnccl.so.2") + NCCL_CHECK 错误检查</text>
        <!-- L1 -->
        <rect x="60" y="438" width="760" height="26" rx="8" fill="#141d33" stroke="#263352"/>
        <text x="440" y="455" fill="#8ea0c2" font-size="12" text-anchor="middle">① 硬件:NVLink / NVSwitch(NVLS)→ InfiniBand / RoCE(Ring / Tree / CollNet)</text>
        <!-- 侧栏:cpu group -->
        <rect x="836" y="78" width="58" height="306" rx="9" fill="#141d33" stroke="#263352" stroke-dasharray="4 3"/>
        <text x="865" y="130" fill="#8ea0c2" font-size="11" text-anchor="middle" transform="rotate(90 865 232)">cpu_group: gloo(元数据 / unique id 广播 / DP 同步)</text>
      </svg>
      <div class="cap">图 13-1 · NCCL 调用栈分层:蓝色高亮即本篇主角 PyNccl 路径;虚线侧栏是与设备通信并行的 gloo 通道</div>
    </div>

    <h3>封装层三个关键设计</h3>
    <div class="grid">
      <div class="card reveal">
        <h3><span class="ico">🔌</span>1. 纯 ctypes 绑定,而非扩展模块 <span class="filepath">device_communicators/pynccl_wrapper.py</span></h3>
        <p><code>NCCLLibrary</code> 用 <code>ctypes.CDLL(so_file)</code> 加载 <code>find_nccl_library()</code>(<code>vllm/utils/nccl.py</code>)找到的库——CUDA 下 <code>libnccl.so.2</code>、ROCm 下 <code>librccl.so.1</code>、或 <code>VLLM_NCCL_SO_PATH</code> 指定路径;按 <code>exported_functions</code> 表逐个绑定 C 符号并设置 <code>restype/argtypes</code>,调用后统一过 <code>NCCL_CHECK</code>(结合 <code>ncclGetErrorString</code> + <code>ncclGetLastError</code> 抛出可读错误)。可选符号做<em>缺符号容忍</em>:ROCm 上 <code>ncclCommWindowRegister</code>、<code>ncclCommSuspend/Resume</code> 缺失时跳过而不是在图捕获中抛异常(pynccl_wrapper.py:437)。<code>ncclDataTypeEnum</code> 维护 torch dtype → NCCL dtype 的映射,含 <code>fp8_e4m3</code>(<code>ncclFloat8e4m3</code>)。</p>
        <pre class="code"><span class="c"># pynccl_wrapper.py:184 NCCLLibrary.exported_functions(节选,真实签名)</span>
Function(<span class="s">"ncclCommInitRank"</span>, ncclResult_t,
         [ctypes.POINTER(ncclComm_t), ctypes.c_int, ncclUniqueId, ctypes.c_int]),
Function(<span class="s">"ncclAllReduce"</span>, ncclResult_t,
         [buffer_type, buffer_type, ctypes.c_size_t, ncclDataType_t,
          ncclRedOp_t, ncclComm_t, cudaStream_t]),
Function(<span class="s">"ncclGroupStart"</span>, ncclResult_t, []),
Function(<span class="s">"ncclCommWindowRegister"</span>, ncclResult_t,
         [ncclComm_t, buffer_type, ctypes.c_size_t,
          ctypes.POINTER(ncclWindow_t), ctypes.c_int]),
Function(<span class="s">"ncclCommSuspend"</span>, ncclResult_t, [ncclComm_t, ctypes.c_int]),</pre>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🌊</span>2. 流控制与图捕获安全 <span class="filepath">device_communicators/pynccl.py</span></h3>
        <p>每个原语签名都带 <code>stream=None</code> 参数,缺省取 <code>current_stream()</code>——这是全部图安全性的来源:<em>NCCL 只是往调用者给的流上 enqueue kernel,捕获期间它就是往捕获流 enqueue,不产生任何 CPU 侧同步</em>。初始化时(<code>_init_comm</code>)做一次单元素 <code>all_reduce</code> 热身并 <code>stream.synchronize()</code>(pynccl.py:191),把惰性初始化的内部缓冲在图捕获之前分配掉。构造函数强制挂在<em>非 NCCL</em> 的 group 上(pynccl.py:114 的 assert):unique id 由 rank 0 经 gloo 广播,设备通信与元数据通道彻底分离。销毁同样讲究:<code>ncclCommDestroy</code> 是集体调用会自死锁,所以 <code>destroy()</code> 在 daemon 线程里调 <code>ncclCommAbort</code> 并限时 5 秒,让主线程先行释放 CUDA Graph(pynccl.py:250)。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🪟</span>3. NCCL window / 用户缓冲区注册 <span class="filepath">device_communicators/pynccl_allocator.py</span></h3>
        <p>这是 <em>NCCL 对称内存</em> 的基础设施:用 <code>load_inline</code> 现场编译一段调用 <code>ncclMemAlloc/ncclMemFree</code> 的 C 代码,包装成 <code>CUDAPluggableAllocator</code> 插件;<code>get_nccl_mem_pool()</code> 基于它建一个 <code>torch.cuda.MemPool</code>。<code>nccl_symm_mem_context</code> 进入时切到该池分配(得到 NCCL 管理的对齐显存),退出时对<em>新出现的段</em>调用 <code>register_comm_window_raw(segment.address, total_size)</code>——即 <code>ncclCommWindowRegister</code>,把用户缓冲注册进通信器,NCCL 才能启用 NVLS 零拷贝路径;图捕获中还要先暂停 CUDA Graph 内存池(细节见场景 7)。门控:<code>VLLM_USE_NCCL_SYMM_MEM</code>(默认关)+ NCCL ≥ 2.27.3 + world_size &gt; 1 + torch ≥ 2.8 + allocator 编译成功。</p>
      </div>
    </div>

    <h3>三类 NCCL 通信器并存</h3>
    <p>一个生产部署里同时活跃的 NCCL communicator 往往不止一个,它们的关系容易混淆,列表如下:</p>
    <table class="tbl reveal">
      <tr><th>通信器</th><th>建立方式</th><th>world</th><th>典型用途</th><th>销毁</th></tr>
      <tr><td>c10d <code>ProcessGroupNCCL</code>(device_group)</td><td><code>init_distributed_environment</code> → <code>new_group(backend="nccl")</code></td><td>全局 world 的子集</td><td>冷路径 broadcast/gather、兜底 all_reduce、XPU/CPU 之外平台的基类实现</td><td>随进程组生命周期</td></tr>
      <tr><td><code>PyNcclCommunicator</code>(每组一个)</td><td><code>CudaCommunicator.__init__</code> 手工 <code>ncclCommInitRank</code></td><td>与组同员但独立成域</td><td>热路径 TP/EP 集合通信、图捕获、EPLB 搬运</td><td><code>destroy()</code>:daemon 线程 + 5s 超时 <code>ncclCommAbort</code></td></tr>
      <tr><td>旁路/外部通信器</td><td><code>make_sibling_device_group</code>(PP);<code>from_unique_id_bytes</code>(trainer)</td><td>与 PP 组同员;或 trainer+vLLM 混合</td><td>PP 采样 token 广播、权重热更新</td><td>会话式 <code>shutdown()</code> / 随组销毁</td></tr>
    </table>

    <h3>PyNccl 与 c10d-NCCL:什么时候用哪个</h3>
    <table class="tbl reveal">
      <tr><th>维度</th><th>c10d <code>ProcessGroupNCCL</code></th><th><code>PyNcclCommunicator</code></th></tr>
      <tr><td>建立方式</td><td><code>init_process_group</code> / <code>new_group(backend="nccl")</code>,由 torch 管 unique id</td><td>手工 <code>ncclCommInitRank</code>,unique id 自己经 gloo 广播(pynccl.py:145)</td></tr>
      <tr><td>CUDA Graph</td><td>调用栈中含潜在同步 API,不可安全捕获(封装层注释记录的历史问题)</td><td>纯 enqueue,可捕获;全靠 stream 参数</td></tr>
      <tr><td>stream 控制</td><td>内部流,用户不直接控制</td><td>每个原语显式 <code>stream</code> 参数(旁路流场景必需)</td></tr>
      <tr><td>变长原语</td><td>无 reduce_scatterv/all_gatherv</td><td>grouped ncclReduce / ncclBroadcast 组合实现</td></tr>
      <tr><td>错误处理</td><td>torch 层包装,细节常丢失</td><td><code>NCCL_CHECK</code> 直拼 <code>ncclGetErrorString</code> + <code>ncclGetLastError</code></td></tr>
      <tr><td>生命周期</td><td>随 ProcessGroup,不可干预</td><td>suspend/resume/abort 逐阶段管理</td></tr>
      <tr><td>典型用途</td><td>冷路径 broadcast/gather、对象广播、兜底 all_reduce</td><td>热路径 TP/EP 集合通信、图捕获、独立 world</td></tr>
    </table>

    <h3>PyNcclCommunicator 的生命周期</h3>
    <table class="tbl reveal">
      <tr><th>阶段</th><th>动作</th><th>代码位置</th></tr>
      <tr><td>会合</td><td>rank 0 <code>ncclGetUniqueId</code> → 经 gloo 组广播 128 字节 id</td><td>pynccl.py:145-162</td></tr>
      <tr><td>建组</td><td><code>ncclCommInitRank</code>(在目标 device 上下文中)</td><td>pynccl.py:180</td></tr>
      <tr><td>热身</td><td>单元素 all_reduce + <code>stream.synchronize()</code>,预分配惰性缓冲;ROCm 弹性 EP 下可延迟</td><td>pynccl.py:189;pynccl.py:38</td></tr>
      <tr><td>注册(可选)</td><td>对称池分配 + <code>ncclCommWindowRegister</code></td><td>pynccl_allocator.py:134</td></tr>
      <tr><td>服务</td><td>各原语 @<code>current_stream()</code>;grouped 组合批量提交</td><td>pynccl.py:273-676</td></tr>
      <tr><td>挂起(可选)</td><td><code>ncclCommSuspend(comm, 0x01)</code> 释放通信显存、保留拓扑</td><td>pynccl.py:643</td></tr>
      <tr><td>销毁</td><td>daemon 线程限时 5s 调 <code>ncclCommAbort</code>(避免与图销毁互等)</td><td>pynccl.py:250-271</td></tr>
    </table>
  </section>

  <!-- ============ 4 代码地图 ============ -->
  <section id="s4">
    <h2 class="sec"><span class="num">4</span>代码地图</h2>
    <p class="lede">NCCL 相关的 28 个核心文件:从 ctypes 绑定层、分发枢纽、替代后端,到 EPLB / 权重热更新 / sleep 等外围挂钩,一张表定位全部职责。</p>
    <table class="tbl reveal">
      <tr><th style="width:33%">文件</th><th style="width:24%">核心类 / 函数</th><th>职责</th></tr>
      <tr><td><code>device_communicators/pynccl_wrapper.py</code></td><td><code>NCCLLibrary</code>、<code>NCCL_CHECK</code></td><td>ctypes 加载 libnccl/librccl,绑定 20+ C 符号;dtype/算子枚举映射</td></tr>
      <tr><td><code>device_communicators/pynccl.py</code></td><td><code>PyNcclCommunicator</code></td><td>独立通信器:all_reduce/all_gather(+v)/reduce_scatter(+v)/send/recv/broadcast/group_start,window 注册,suspend/resume,<code>from_unique_id_bytes</code></td></tr>
      <tr><td><code>device_communicators/pynccl_allocator.py</code></td><td><code>nccl_symm_mem_context</code>、<code>get_nccl_mem_pool</code></td><td>ncclMemAlloc 内存池 + NCCL window 注册(NVLS 用户缓冲)</td></tr>
      <tr><td><code>device_communicators/cuda_wrapper.py</code></td><td><code>CudaRTLibrary</code></td><td>libcudart ctypes 封装:cudaMalloc、IPC 句柄、P2P 探测(custom AR 依赖)</td></tr>
      <tr><td><code>device_communicators/cuda_communicator.py</code></td><td><code>CudaCommunicator</code></td><td><b>分发枢纽</b>:按尺寸/世界大小选后端;all_gather/reduce_scatter(+v)、send/recv、all2all manager 装配</td></tr>
      <tr><td><code>device_communicators/base_device_communicator.py</code></td><td><code>DeviceCommunicatorBase</code></td><td>c10d 兜底(dist.all_reduce / all_gather_into_tensor / reduce_scatter_tensor)</td></tr>
      <tr><td><code>device_communicators/cpu_communicator.py</code></td><td><code>CpuCommunicator</code></td><td>gloo(+CPUSHM 共享内存)后端,CPU 平台对照</td></tr>
      <tr><td><code>device_communicators/xpu_communicator.py</code></td><td><code>XpuCommunicator</code></td><td>Intel XPU:走 c10d xccl,无 pynccl</td></tr>
      <tr><td><code>device_communicators/custom_all_reduce.py</code></td><td><code>CustomAllreduce</code></td><td>IPC + P2P 单跳 all-reduce,单节点 NVLink 小/中消息(何时不用 NCCL)</td></tr>
      <tr><td><code>device_communicators/symm_mem.py</code></td><td><code>SymmMemCommunicator</code></td><td>torch 对称内存 NVLS 路径,按 capability/world_size 尺寸表</td></tr>
      <tr><td><code>device_communicators/quick_all_reduce.py</code></td><td><code>QuickAllReduce</code></td><td>ROCm MI300 quickreduce,补充 custom AR</td></tr>
      <tr><td><code>device_communicators/flashinfer_all_reduce.py</code></td><td><code>FlashInferAllReduce</code></td><td>MNNVL all-reduce(GB200 NVLink domain),按 tuning 表限尺寸</td></tr>
      <tr><td><code>device_communicators/all2all.py</code></td><td><code>AgRsAll2AllManager</code> 等 11 个 manager</td><td>EP dispatch/combine:naive 路径复用 all_gatherv/reduce_scatterv(→NCCL);DeepEP/MoRI/MoonEP/NIXL 为替代</td></tr>
      <tr><td><code>device_communicators/shm_broadcast.py</code></td><td><code>MessageQueue</code></td><td>同节点对象广播:shm + zmq 通知,替代 gloo/NCCL broadcast_object</td></tr>
      <tr><td><code>device_communicators/all_reduce_utils.py</code></td><td><code>should_nccl_symm_mem_allreduce</code></td><td>尺寸门控配置表 + 真实 P2P 探测缓存</td></tr>
      <tr><td><code>distributed/parallel_state.py</code></td><td><code>GroupCoordinator</code>、<code>init_distributed_environment</code>、<code>suspend_device_comms</code></td><td>分组管理、custom op 注册、graph_capture 上下文、通信器挂起</td></tr>
      <tr><td><code>distributed/communication_op.py</code></td><td><code>tensor_model_parallel_all_reduce</code> 等</td><td>模型层最常用的入口包装</td></tr>
      <tr><td><code>utils/nccl.py</code></td><td><code>find_nccl_library</code>、<code>pin_nccl_env</code>、<code>query_nccl_gin_type</code></td><td>库定位、NCCL 环境变量 pin(NCCL_NO_CACHE)、GIN 能力查询</td></tr>
      <tr><td><code>distributed/weight_transfer/nccl_engine.py</code> 等</td><td><code>NCCLWeightTransferEngine</code></td><td>与外部 trainer 的独立 NCCL world,权重广播(dense/sparse 两引擎)</td></tr>
      <tr><td><code>distributed/eplb/eplb_communicator.py</code></td><td><code>PyNcclEplbCommunicator</code></td><td>EPLB 专家权重搬运:pynccl group send/recv</td></tr>
      <tr><td><code>v1/worker/gpu_worker.py</code></td><td><code>init_device</code>、sleep 流程</td><td>清 Ray 注入的 NCCL 变量、内存快照避让 NCCL 缓冲、suspend/resume 挂钩</td></tr>
      <tr><td><code>v1/worker/gpu/pp_utils.py</code></td><td><code>PPHandler</code></td><td>PP 采样 token 广播:旁路流 + sibling 通信器</td></tr>
      <tr><td><code>v1/worker/gpu/sample/batch_shard.py</code></td><td><code>get_tp_pynccl_comm</code></td><td>采样 logits 分片 all_to_all_single(复用 TP 通信器)</td></tr>
      <tr><td><code>v1/worker/dp_utils.py</code></td><td><code>_run_ar</code></td><td>DP 元数据 all_reduce(NCCL 或降级 gloo)</td></tr>
      <tr><td><code>model_executor/determinism/batch_invariant.py</code></td><td><code>all_reduce_batch_invariant</code> 等</td><td>强制 NCCL 单通道树归约的确定性环境变量组</td></tr>
      <tr><td><code>distributed/elastic_ep/standby_state.py</code></td><td><code>defer_comm_warmup_on_rocm</code> 挂钩</td><td>ROCm 上把新通信器热身推迟到 commit,避免与在役集体死锁</td></tr>
      <tr><td><code>compilation/cudagraph_pool.py</code></td><td><code>set_graph_pool_id</code></td><td>cuMem 图池与 NCCL 对称内存池的互斥切换</td></tr>
      <tr><td><code>collect_env.py</code> / <code>ray/ray_env.py</code> / <code>utils/mem_utils.py</code></td><td>环境收集 / 前缀透传 / 显存预算</td><td>诊断输出列出 nccl 包;NCCL_ 前缀传播给 Ray worker;预算预扣 NCCL 显存</td></tr>
    </table>
  </section>

  <!-- ============ 5 使用场景逐个详解 ============ -->
  <section id="s5">
    <h2 class="sec"><span class="num">5</span>使用场景逐个详解(核心)</h2>
    <p class="lede">触发条件 → 调用链 → 代码位置:穷举 vLLM 中所有真正走到 NCCL 的 12+ 个调用场景,含排查速查表与场景总表。</p>

    <h3><span class="badge nccl">场景 1</span>初始化:后端选择与双通道建组</h3>
    <p><em>触发条件</em>:任意多卡启动。<em>调用链</em>:</p>
    <ul class="chain reveal">
      <li class="first">平台层决定默认后端:<code>platforms/cuda.py:232</code> 与 <code>platforms/rocm.py:659</code> 均为 <code>dist_backend="nccl"</code>,XPU 为 <code>"xccl"</code>(xpu.py:111),CPU 为 <code>"gloo"</code>(cpu.py:113)</li>
      <li><code>init_distributed_environment</code>(parallel_state.py:1843,形参默认 <code>backend="nccl"</code>)→ <code>torch.distributed.init_process_group</code>;NCCL 不可用时打印告警回退 gloo</li>
      <li><code>platforms/cuda.py:615</code> <code>assert is_nccl_available()</code>,其下手工构造 <code>ProcessGroupNCCL</code> 挂到 c10d 组</li>
      <li><code>init_world_group / init_model_parallel_group</code> 为 TP/PP/DP/EP 各建 <code>device_group</code>(nccl)+ <code>cpu_group</code>(gloo)</li>
      <li><code>use_device_communicator=True</code> 时按 <code>get_device_communicator_cls()</code> 实例化 <code>CudaCommunicator</code>(parallel_state.py:554)</li>
      <li><code>CudaCommunicator.__init__</code>(cuda_communicator.py:107)创建 <code>PyNcclCommunicator</code>:rank 0 <code>ncclGetUniqueId</code> → gloo 广播 → <code>ncclCommInitRank</code> → 单元素 all_reduce 热身 + <code>stream.synchronize()</code></li>
    </ul>
    <p>关键结构:每个 <code>GroupCoordinator</code> 同时持有<em>两个</em>组——<code>device_group</code>(backend=nccl,张量通信)与 <code>cpu_group</code>(backend=gloo,元数据/超时控制),见 <code>GroupCoordinator.__init__</code>(parallel_state.py:455)。<em>注意:pynccl 与 c10d-NCCL 是两套并存的通信器</em>——前者服务热路径与图捕获,后者兜底与对象广播,两者 world 相同但拓扑与缓冲完全独立。建组与热身的完整动作:</p>
    <pre class="code"><span class="c"># pynccl.py:165 _init_comm —— 建组与热身(节选)</span>
<span class="k">with</span> torch.accelerator.device_index(device.index):
    self.comm = self.nccl.ncclCommInitRank(
        self.world_size, self.unique_id, self.rank)
    <span class="k">if</span> _warmup_deferred():          <span class="c"># ROCm 弹性 EP:推迟到 commit 时热身</span>
        <span class="k">return</span>
    stream = current_stream()
    data = torch.zeros(1, device=device)
    self.all_reduce(data)              <span class="c"># 触发 NCCL 惰性初始化(缓冲/通道分配)</span>
    stream.synchronize()               <span class="c"># 全链路唯一一次显式同步</span>
    del data</pre>
    <div class="note reveal"><b>日志入口:</b><code>CudaCommunicator._log_all_reduce_backend_selection</code>(cuda_communicator.py:308)启动时打印该组可用后端及分发顺序,是排查"到底走了哪条路"的第一现场。</div>

    <h3><span class="badge nccl">场景 2</span>TP all-reduce:RowParallelLinear 前向(最高频)</h3>
    <p><em>触发条件</em>:TP&gt;1 时每个 Transformer 层的 MLP/Attention 输出投影。<em>调用链</em>:</p>
    <ul class="chain reveal">
      <li class="first"><code>RowParallelLinear.forward</code>(linear.py:1822):<code>output = tensor_model_parallel_all_reduce(output_parallel)</code></li>
      <li><code>tensor_model_parallel_all_reduce</code>(communication_op.py:12)→ <code>get_tp_group().all_reduce</code></li>
      <li><code>GroupCoordinator.all_reduce</code>(parallel_state.py:730):world_size==1 直接旁路;<code>use_custom_op_call=True</code> 时走 <code>torch.ops.vllm.all_reduce(input_, group_name=...)</code></li>
      <li>custom op 按字符串组名查注册表(parallel_state.py:199)→ <code>_all_reduce_out_place</code> → <code>CudaCommunicator.all_reduce</code>(cuda_communicator.py:384)</li>
      <li>按尺寸分发命中后 → <code>PyNcclCommunicator.all_reduce</code>(pynccl.py:273)→ <code>ncclAllReduce</code>@当前流</li>
    </ul>
    <p>真实分发代码(节选、顺序即优先级,注释为笔者所加):</p>
    <pre class="code"><span class="c"># cuda_communicator.py:384 CudaCommunicator.all_reduce —— 尺寸/世界大小分发链</span>
<span class="k">if</span> (self.pynccl_comm <span class="k">is not</span> <span class="k">None</span> <span class="k">and not</span> use_fi_ar
        <span class="k">and</span> should_nccl_symm_mem_allreduce(self.pynccl_comm.world_size, input_)):
    out = torch.ops.vllm.all_reduce_symmetric_with_copy(input_)  <span class="c"># NCCL window / NVLS</span>
<span class="k">if</span> qr_comm <span class="k">is not</span> <span class="k">None</span> <span class="k">and</span> qr_comm.should_quick_allreduce(input_):
    <span class="k">return</span> qr_comm.quick_all_reduce(input_)                  <span class="c"># ROCm quickreduce</span>
<span class="k">if</span> fi_pcie_ipc_ar_comm <span class="k">is not</span> <span class="k">None</span> <span class="k">and</span> fi_pcie_ipc_ar_comm.should_use(input_):
    <span class="k">return</span> fi_pcie_ipc_ar_comm.all_reduce(input_)            <span class="c"># FlashInfer PCIe IPC</span>
<span class="k">if</span> use_fi_ar:
    <span class="k">return</span> fi_ar_comm.all_reduce(input_)                       <span class="c"># FlashInfer MNNVL</span>
<span class="k">if</span> (ca_comm <span class="k">is not</span> <span class="k">None</span> <span class="k">and not</span> ca_comm.disabled
        <span class="k">and</span> ca_comm.should_custom_ar(input_)):
    <span class="k">return</span> ca_comm.custom_all_reduce(input_)                   <span class="c"># IPC+P2P 单跳</span>
<span class="k">if</span> symm_mem_comm <span class="k">is not</span> <span class="k">None</span> <span class="k">and</span> symm_mem_comm.should_use_symm_mem(input_):
    <span class="k">return</span> symm_mem_comm.all_reduce(input_)                   <span class="c"># torch symm mem</span>
pynccl_comm = self.pynccl_comm
<span class="k">if</span> pynccl_comm <span class="k">is</span> <span class="k">None</span> <span class="k">or</span> pynccl_comm.disabled:
    out = input_.clone()
    torch.distributed.all_reduce(out, group=self.device_group)   <span class="c"># c10d-NCCL 兜底</span>
    <span class="k">return</span> out
<span class="k">return</span> pynccl_comm.all_reduce(input_)                            <span class="c"># PyNccl:ncclAllReduce@当前流</span></pre>
    <p>命中 pynccl 时执行的就是一次 C FFI 调用(<code>PyNcclCommunicator.all_reduce</code>,pynccl.py:273):</p>
    <pre class="code">self.nccl.ncclAllReduce(
    buffer_type(in_tensor.data_ptr()), buffer_type(out_tensor.data_ptr()),
    in_tensor.numel(),
    ncclDataTypeEnum.from_torch(in_tensor.dtype),
    ncclRedOpTypeEnum.from_torch(op),
    self.comm,
    cudaStream_t(stream.cuda_stream),   <span class="c"># stream 缺省 = current_stream(),图捕获时即捕获流</span>
)</pre>
    <p>NCCL symm-mem 分支的门控在 <code>all_reduce_utils.py</code>,配置直接来自 H100/GB200 实测(注释中给出 8 卡与 4 卡的分段性能数据):</p>
    <pre class="code"><span class="c"># all_reduce_utils.py:111 —— custom AR 只在"中段尺寸"赢,两端都还给 NCCL symm</span>
NCCL_SYMM_MEM_ALL_REDUCE_CONFIG = {
    <span class="s">"min_world_size"</span>: 4,
    <span class="s">"custom_ar_preferred_ranges"</span>: {4: (16 * KiB, 512 * KiB), 8: (16 * KiB, 128 * KiB)},
    <span class="s">"always_use_above_world_size"</span>: 8,  <span class="c"># world_size &gt; 8 一律 NCCL symm mem</span>
}</pre>
    <div class="note good reveal"><b>解读:</b>8 卡时消息 ≤16KiB 或 ≥128KiB 走 <code>all_reduce_symmetric_with_copy</code>(注册 window 后的 NVLS all-reduce,见场景 8),32K–64K 让给 custom AR;4 卡分界为 16K/512K;<code>min_world_size=4</code> 意味着 2 卡 TP 不启用 NCCL symm,靠 custom AR + pynccl。<code>VLLM_BATCH_INVARIANT</code> 开启时该分支整体关闭(见场景 9)。</div>

    <h3><span class="badge nccl">场景 3</span>all_gather:并行输出汇聚</h3>
    <p><em>触发条件</em>:列并行权重输出需要拼回完整张量,或并行 logits 汇聚。<em>调用链</em>:</p>
    <ul class="chain reveal">
      <li class="first"><code>ColumnParallelLinear.forward</code>(linear.py:631):<code>tensor_model_parallel_all_gather</code>(<code>gather_output=True</code> 时)</li>
      <li><code>LogitsProcessor</code>(logits_processor.py:130):<code>use_all_gather</code> 时对 vocab 分片 logits 汇聚;另有多处 LM head 分支按 dim=-1 gather(logits_processor.py:258/305/315)</li>
      <li><code>GroupCoordinator.all_gather</code> → custom op → <code>CudaCommunicator.all_gather</code>(cuda_communicator.py:482)</li>
      <li>pynccl 路径:手工 <code>torch.empty</code> 输出 → <code>ncclAllGather</code> → reshape/movedim;dim=0 且 symm 开启时改走 <code>_all_gather_symm_mem</code>(NVLS)</li>
    </ul>
    <p>两条旁路值得注意:<b>(a)</b> ROCm 上刻意保留基类 c10d 路径——代码注释明说手工 pynccl 分配在 ROCm 上有每步额外分配与拷贝开销,会造成解码回退(cuda_communicator.py:501);<b>(b)</b> 大模型上 vocab 分片 logits 的 TP all-gather 单条消息可达数十 MB,是典型 NCCL 大消息场景,NVLS/多通道带宽直接决定首 token 延迟。</p>

    <h3><span class="badge nccl">场景 4</span>reduce_scatter / all_gatherv:DP 注意力与 MoE 组合</h3>
    <p><em>触发条件</em>:DP attention 把各 DP rank 的请求拼成统一批次;EP/MoE 的 combine 需要按 rank 归约;序列并行的 gather-before-GEMM。<em>调用链</em>:</p>
    <ul class="chain reveal">
      <li class="first">模型/MoE 层调用 <code>GroupCoordinator.reduce_scatter / reduce_scatterv / reduce_scatterv_into_output</code>(parallel_state.py:789/805/812)</li>
      <li><code>CudaCommunicator.reduce_scatter</code>(cuda_communicator.py:518):均匀切分 → <code>pynccl_comm.reduce_scatter</code>(ncclReduceScatter);symm 开启 → <code>_reduce_scatter_symm_mem</code></li>
      <li>变长 sizes → <code>_reduce_scatterv</code>(cuda_communicator.py:569)→ <code>pynccl_comm.reduce_scatterv</code>(grouped ncclReduce)</li>
      <li>BatchInvariant(ROCm 浮点)→ <code>reduce_scatter_batch_invariant</code>;确定性模式还可 <code>reduce(root=0)+scatter</code> 组合(cuda_communicator.py:664)</li>
    </ul>
    <pre class="code"><span class="c"># pynccl.py:392 reduce_scatterv —— 变长归约 = grouped ncclReduce(每 rank 一个 root)</span>
self.nccl.ncclGroupStart()
<span class="k">for</span> root, split_size <span class="k">in</span> enumerate(sizes):
    chunk = input_tensor[split_offset : split_offset + split_size, ...]
    self.nccl.ncclReduce(
        buffer_type(chunk.data_ptr()), buffer_type(output_tensor.data_ptr()),
        chunk.numel(), ncclDataTypeEnum.from_torch(input_tensor.dtype),
        ncclRedOpTypeEnum.from_torch(op), root, self.comm,
        cudaStream_t(stream.cuda_stream))
    split_offset += split_size
self.nccl.ncclGroupEnd()</pre>
    <p>对偶的 <code>all_gatherv</code>(pynccl.py:329)用 grouped <code>ncclBroadcast</code> 实现。EP 的 naive 后端 <code>AgRsAll2AllManager</code>(all2all.py:57)正是用这对原语模拟 all-to-all:<code>dispatch = all_gatherv</code>(每 rank 收全量 hidden states),<code>combine = reduce_scatterv</code>(各自算完按 sizes 归回)。MoE 热路径还提供 <code>reduce_scatterv_into_output</code>:输出张量由上层预分配,通信直接写入目标缓冲,避免图捕获期分配——对称内存时要求输出本身已注册(或 NCCL ≥ 2.29.2 支持非注册输出,见 <code>NCCL_DIRECT_SYMM_RS_OUTPUT_MIN_VERSION</code>,cuda_communicator.py:32)。</p>
    <p>DP 元数据同步是另一个小而重要的场景:<code>v1/worker/dp_utils.py:_run_ar</code> 把各 DP rank 的 padding 宽度、ubatch 标志等四项打包成一个 int32 张量,在 DP <code>device_group</code>(c10d-NCCL)上 <code>dist.all_reduce</code>;若配置 <code>disable_nccl_for_dp_synchronization</code>(config/vllm.py:1752 起,检测到会 rebuild CPU 组的拓扑时自动置 True)则改在 CPU gloo 组上同步,避免设备组 collective 阻塞异步调度。</p>

    <h3><span class="badge nccl">场景 5</span>broadcast:对象/张量广播的真实走向</h3>
    <p>广播在 vLLM 里被<em>分流</em>成三条路,很少直接用 NCCL:</p>
    <table class="tbl reveal">
      <tr><th>需求</th><th>实现</th><th>位置</th></tr>
      <tr><td>Python 对象广播(配置、采样元数据)</td><td><code>MessageQueue</code>(shm + zmq 通知,4MiB 缓冲);同节点优先,跨节点才 <code>dist.broadcast_object_list</code>(gloo)</td><td><code>shm_broadcast.py</code>;parallel_state.py:860 <code>broadcast_object</code></td></tr>
      <tr><td>张量广播</td><td><code>torch.distributed.broadcast</code> 走 device_group(c10d-NCCL)</td><td>parallel_state.py:845 <code>GroupCoordinator.broadcast</code></td></tr>
      <tr><td>权重热更新广播</td><td><code>PyNcclCommunicator.broadcast</code>(独立 world,发送端 sendbuff=recvbuff 同指针)</td><td>weight_transfer/nccl_engine.py:242;pynccl.py:597</td></tr>
    </table>
    <p>PP 还有一条隐蔽的 broadcast:<code>v1/worker/gpu/pp_utils.py</code> 的 <code>PPHandler</code> 把"最后一个 stage 采样出的 token"广播回所有 PP stage。为了不与层间隐状态 send/recv 在<em>同一条 NCCL 通信线上串行化</em>,它通过 <code>make_sibling_device_group(group_desc="pp_broadcast")</code>(parallel_state.py:595)另建一个与 PP device_group 同成员的<b>独立</b> c10d-NCCL 子组,并在旁路 <code>broadcast_stream</code> 上异步执行;T 步的 recv 在 T+pp_size 步才经 FIFO 队列消费(pp_utils.py:60 注释原文:"Uses a dedicated NCCL communicator (sibling of the PP device_group) ... so it does not serialize on the wire")。</p>

    <h3><span class="badge deepep">场景 6</span>EP all-to-all:与 DeepEP 的边界</h3>
    <p><em>触发条件</em>:启用 EP 的 MoE dispatch/combine。<code>all2all.py</code> 提供 11 个 manager,边界清晰:<code>naive / allgather_reducescatter</code> 后端经 <code>GroupCoordinator.all_gatherv / reduce_scatterv</code> 最终落到 <em>NCCL</em>;其余 <code>deepep_low_latency / deepep_high_throughput / deepep_v2 / mori / moonep / nixl_ep / flashinfer_nvlink 双向与单向 / passthrough</code> 全部走各自 RDMA/NVLink 库,不经 NCCL。但有一个反向依赖值得注意:<code>DeepEPv2All2AllManager</code>(all2all.py:1237)调用 <code>query_nccl_gin_type</code>(utils/nccl.py:88,经 <code>ncclCommQueryProperties</code> 查 c10d 组的 comm 指针)硬性要求 <em>NCCL GIN</em>(GPU-Initiated Networking,GH200/GB200 上由 GPU 发起的网络),否则直接报错——NCCL 在这里扮演"能力探针"而非传输者。</p>
    <p>EP 家族的另两个 NCCL 用户:</p>
    <ul class="chain reveal">
      <li class="first"><b>EPLB 专家再平衡</b>:<code>PyNcclEplbCommunicator</code>(eplb_communicator.py:694)以 group + <code>ncclSend/ncclRecv</code> 在 EP rank 间搬专家权重,可指定独立 stream;再平衡期间经 <code>eplb_utils.py:121</code> 设 <code>NCCL_MAX_CTAS</code> 限制通信 kernel 占用的 SM 数,给搬运留算力</li>
      <li><b>采样 logits 分片交换</b>:<code>batch_shard.py:403</code> 用 <code>pynccl_comm.all_to_all_single</code>(grouped ncclSend/ncclRecv,pynccl.py:489)把各 TP rank 的 logits 分片换回本 rank 的行——注释明确:复用 TP 通信器可避免 c10d all_to_all 令 NCCL 再分配一整套点对点缓冲</li>
    </ul>
    <pre class="code"><span class="c"># eplb_communicator.py:709 PyNcclEplbCommunicator —— 专家权重搬运(节选)</span>
<span class="k">def</span> <span class="f">add_send</span>(self, tensors, dst_rank, expert_id):
    self._ensure_group_started()                      <span class="c"># 惰性 ncclGroupStart</span>
    <span class="k">for</span> tensor <span class="k">in</span> tensors:
        self._pynccl_comm.send(tensor, dst_rank, stream=self._stream)
<span class="k">def</span> <span class="f">execute</span>(self):
    <span class="k">if</span> self._group_started:
        self._pynccl_comm.group_end()                 <span class="c"># 一次性提交整批收发</span></pre>

    <h3><span class="badge nccl">场景 7</span>CUDA Graph 捕获期间的 NCCL(重点)</h3>
    <p><em>触发条件</em>:V1 引擎 FULL/PIECE CUDA Graph 捕获,且模型含 TP 集合通信。<em>机制</em>:捕获开始时 <code>GroupCoordinator.graph_capture</code>(parallel_state.py:678)新建捕获流并 <code>stream.wait_stream(curr_stream)</code> 保证初始化已完成;随后 <code>torch.cuda.stream(stream)</code> 切流。此后所有 pynccl 原语取到的 <code>current_stream()</code> 就是捕获流,<code>ncclAllReduce</code> 等 C 调用<em>只向该流 enqueue kernel</em>,没有任何 CPU 同步,因而天然可捕获——这正是"custom op + pynccl"组合存在的原因(链上每个环节都是普通 kernel 调用)。</p>
    <pre class="code"><span class="c"># parallel_state.py:678 graph_capture —— pynccl 无需任何注册,custom AR 才需要</span>
<span class="k">with</span> (torch.cuda.stream(stream),
      maybe_ca_context,          <span class="c"># CustomAllreduce.capture(): 注册 IPC 图缓冲</span>
      maybe_fi_pcie_ipc_context,
      maybe_aiter_ar_context):
    <span class="k">yield</span> graph_capture_context   <span class="c"># 期间所有 pynccl 调用 enqueue 到捕获流</span></pre>
    <p>四个配套细节:<b>(a)</b> 替代后端在图内同样安全:custom AR 经 <code>ca_comm.capture()</code> 把 IPC buffer 注册为图缓冲(<code>register_graph_buffers</code>;使用 cuMem 图池时跳过注册、改为捕获期拷贝,cuda_communicator.py:124);<b>(b)</b> NCCL symm-mem 路径在图捕获期间分配临时对称缓冲会打破图内存池,<code>nccl_symm_mem_context.__enter__</code> 因此先 <code>torch._C._cuda_endAllocateToPool</code> 暂停图池、<code>__exit__</code> 再恢复(pynccl_allocator.py:170,图池 id 由 <code>compilation/cudagraph_pool.py</code> 经 <code>set_graph_pool_id</code> 注入);<b>(c)</b> <code>CudaCommunicator._get_symm_scratch</code>(cuda_communicator.py:682)把对称缓冲做成按 (role, ubatch, shape, dtype) 缓存的<em>持久高水位 scratch</em>——因为每次 <code>nccl_symm_mem_context</code> 的快照+注册扫描约 0.5ms,远超 NVLS 传输本身;被替换的旧缓冲仍保留引用,因为已捕获的图可能还在用它的指针;<b>(d)</b> 捕获前的 warmup:PyNccl 建组即热身(场景 1),<code>defer_comm_warmup_on_rocm</code>(pynccl.py:38)在 ROCm 上允许 elastic EP 新 worker 把热身推迟到 commit 时,避免与在役引擎的活跃 collective 死锁(standby_state.py 同样挂接)。</p>
    <pre class="code"><span class="c"># pynccl_allocator.py:161 nccl_symm_mem_context —— 图捕获期间的内存池切换(节选)</span>
<span class="k">if</span> self.is_graph_capture:
    <span class="c"># 暂停 CUDA Graph 内存池,让下面的 empty 落入 ncclMemAlloc 对称池</span>
    torch._C._cuda_endAllocateToPool(self.device, _graph_pool_id)
self._mem_pool_ctx.__enter__()
...
<span class="c"># __exit__:对池快照中新增的每个 segment 注册 NCCL window(集体操作)</span>
self.pynccl_comm.register_comm_window_raw(
    segment[<span class="s">"address"</span>], segment[<span class="s">"total_size"</span>])
<span class="k">if</span> self.is_graph_capture:
    torch._C._cuda_beginAllocateCurrentThreadToPool(self.device, _graph_pool_id)</pre>
    <div class="note warn reveal"><b>易踩坑点:</b>NCCL window 注册是<em>集体</em>操作——各 rank 对称池的非对称分配会导致死锁,所以 <code>_reduce_scatterv</code> 只在 uniform sizes 时才走 symm 路径(cuda_communicator.py:638 注释原文)。</div>

    <h3><span class="badge nccl">场景 8</span>NCCL window(对称内存)与 NVLS</h3>
    <p><em>触发条件</em>:<code>VLLM_USE_NCCL_SYMM_MEM=1</code> 且硬件/版本满足。这是"把用户缓冲注册进 NCCL"的完整链路:<code>compile_nccl_allocator</code> 现场编译 <code>ncclMemAlloc/ncclMemFree</code> 插件 → <code>torch.cuda.MemPool</code> → <code>nccl_symm_mem_context</code> 中分配的张量自动落入该池 → 退出上下文时把新 segment 经 <code>ncclCommWindowRegister</code> 注册。注册后 <code>register_nccl_symmetric_ops</code>(pynccl.py:62)注册的 custom op <code>torch.ops.vllm.all_reduce_symmetric_with_copy</code> 即走 NVLS 多播归约(输入先 copy 进对称缓冲,输出再返回)。all_gather/reduce_scatter 侧:<code>should_nccl_symm_mem_ag_rs</code>(all_reduce_utils.py:159)只看开关与 BatchInvariant,dim=0 的 gather 与 uniform reduce_scatter 分别走 <code>_all_gather_symm_mem / _reduce_scatter_symm_mem</code>,且<em>只需单侧</em>是对称内存(AG 只要求输出,RS 按 2.29.2 起允许非注册输出)。</p>

    <h3><span class="badge nccl">场景 9</span>环境变量与运行时控制</h3>
    <p>代码中显式读写的 <code>NCCL_*</code> 变量按用途分四组:</p>
    <table class="tbl reveal">
      <tr><th>变量</th><th>设置点</th><th>含义</th></tr>
      <tr><td><code>NCCL_NO_CACHE</code></td><td><code>utils/nccl.py:156</code> <code>pin_nccl_env</code></td><td>把 vLLM pin 的变量列入 NCCL 重读名单(NCCL ≥ 2.29.7),使"本进程专用"的通信器带这些参数、共享通信器不带(<code>unpinned_nccl_env</code> 上下文);若版本不够则告警"对端必须设相同变量否则挂起"</td></tr>
      <tr><td><code>NCCL_CUMEM_ENABLE / NCCL_SHM_DISABLE / NCCL_IB_DISABLE / NCCL_NVLS_ENABLE / NCCL_CUMEM_HOST_ENABLE</code></td><td><code>v1/executor/cuda_checkpoint_executor.py:107-130</code></td><td>进程 checkpoint(CRIU)环境强制关闭 NCCL 的高阶内存/传输特性,保证可冻结;与 <code>NCCL_DISABLE_MEM_MANAGER</code> 交互决定 NVLS 开关</td></tr>
      <tr><td><code>NCCL_LAUNCH_MODE=GROUP / NCCL_ALGO / NCCL_MIN_NCHANNELS=1 / NCCL_MAX_NCHANNELS=1 / NCCL_PROTO=Simple / NCCL_NTHREADS=1 / NCCL_COLLNET_ENABLE=0 / NCCL_NVLS_ENABLE=0</code></td><td><code>determinism/batch_invariant.py:1405</code></td><td><code>VLLM_BATCH_INVARIANT</code> 下强制 NCCL 单通道树形规约(<code>NCCL_ALGO=ring,tree;allreduce:tree</code>),保证浮点求和顺序确定;同时禁用 symm-mem 分支与 FlashInfer AR(它们无固定归约顺序)</td></tr>
      <tr><td><code>NCCL_GRAPH_REGISTER=0</code></td><td><code>config/vllm.py:2378</code></td><td>cuMem 图池下默认关闭 NCCL 图注册(注册会把 sleep 时卸载的图池钉死),非 0 打印告警</td></tr>
      <tr><td><code>NCCL_MAX_CTAS</code></td><td><code>eplb/eplb_utils.py:121</code></td><td>EPLB 再平衡期间限制 NCCL kernel 占用的 CTAS,给搬运留算力</td></tr>
      <tr><td><code>NCCL_RAS_ENABLE=0</code></td><td><code>platforms/rocm.py:454</code></td><td>ROCm/RCCL 默认关闭 RAS 线程</td></tr>
      <tr><td><code>NCCL_ASYNC_ERROR_HANDLING</code></td><td><code>v1/worker/gpu_worker.py:459</code></td><td>Ray 注入的该变量会导致图构建异常,init_device 时主动 pop</td></tr>
      <tr><td><code>NCCL_IB_DISABLE=1</code></td><td><code>snapshot/runtime.py:261</code></td><td>快照子进程继承的前缀环境;同理 <code>ray/ray_env.py:40</code> 把 NCCL_ 前缀列入透传 Ray worker 的默认集合</td></tr>
    </table>
    <p>vLLM 侧门控变量:<code>VLLM_NCCL_SO_PATH</code>(指定 .so)、<code>VLLM_DISABLE_PYNCCL</code>(整体禁用 pynccl,回落 c10d)、<code>VLLM_USE_NCCL_SYMM_MEM</code>(默认 0,开启 window/NVLS 路径)、<code>VLLM_NCCL_INCLUDE_PATH</code>(allocator 编译时找 nccl.h)。另有 <code>collect_env.py</code> 把 nccl 列入诊断输出、<code>utils/mem_utils.py:258</code> 在显存预算中固定预扣 0.5–1 GiB"NCCL 专用显存"、<code>gpu_worker.py:509-545</code> 的内存快照特意在 NCCL 初始化之后测量。</p>

    <h3><span class="badge hccl">场景 10</span>多平台:RCCL / xccl / gloo</h3>
    <table class="tbl reveal">
      <tr><th>平台</th><th>后端 / 库</th><th>适配要点(代码证据)</th></tr>
      <tr><td>NVIDIA CUDA</td><td>NCCL <code>libnccl.so.2</code></td><td>主线路径;<code>platforms/cuda.py</code> 断言 <code>is_nccl_available()</code>;全部高级特性(window/suspend)按版本探测</td></tr>
      <tr><td>AMD ROCm</td><td>RCCL <code>librccl.so.1</code></td><td><code>find_nccl_library</code>(utils/nccl.py:33)按 <code>torch.version.hip</code> 选库;绑定层对缺失符号(<code>ncclCommSuspend/Resume</code> 等)continue 容忍(pynccl_wrapper.py:437);类名仍叫 NCCL,API 兼容;symm-mem all_gather 在 ROCm 上让位 c10d(场景 3)</td></tr>
      <tr><td>Intel XPU</td><td>xccl(oneCCL,c10d 集成)</td><td><code>XpuCommunicator</code> 只用 <code>torch.distributed</code>(xpu_communicator.py:69),平台 <code>dist_backend="xccl"</code>;无 pynccl、无 IPC 路径;all2all 仅支持 AgRs(xpu_communicator.py:31)</td></tr>
      <tr><td>CPU</td><td>gloo(+ CPUSHM)</td><td><code>CpuCommunicator</code>(cpu_communicator.py:20):x86/ARM/PPC/s390 上 TP/PP 组启用共享内存 SHM 后端替代套接字,与 NCCL 无关——作为"同一套 GroupCoordinator 接口、不同实现"的对照</td></tr>
    </table>

    <h3><span class="badge nccl">扩展场景 11</span>权重热更新:与外部 trainer 的独立 NCCL world</h3>
    <p><em>触发条件</em>:配置 <code>weight_transfer_config</code>(在线学习/金丝雀更新)。vLLM 与 trainer 组成一个<em>与推理 world 完全无关</em>的新 NCCL world:<code>weight_transfer/nccl_common.py</code> 定义两种会合方式——<code>master_address/master_port</code>(TCPStore + StatelessProcessGroup,要求对端有 torch),或 128 字节 <code>ncclUniqueId</code> 的标准 base64(供<em>无 torch 的 JAX trainer</em> 带外广播,数据类字段 <code>nccl_unique_id_b64</code> 明确拒绝 URL-safe 编码)。<code>NCCLWeightTransferEngine.receive_weights</code>(nccl_engine.py:182)随后按参数逐个 <code>model_update_group.broadcast</code>(或打包的 <code>packed_nccl_broadcast_producer/consumer</code>);sparse 引擎(<code>sparse_nccl_engine.py</code>)只传变化的切片。会话管理上还有 <code>unpinned_nccl_env</code>:trainer 侧 pin 的 NCCL 参数只作用于自己的通信器,不影响与 vLLM 共享的那条。</p>
    <pre class="code"><span class="c"># pynccl.py:194 from_unique_id_bytes —— torch-free 对端的会合(节选)</span>
<span class="k">if</span> len(unique_id_bytes) != NCCL_UNIQUE_ID_BYTES:      <span class="c"># 128 字节 ncclUniqueId</span>
    <span class="k">raise</span> ValueError(...)
self.unique_id = self.nccl.unique_id_from_bytes(unique_id_bytes)
self._init_comm(device)
<span class="c"># _init_comm 内:ncclCommInitRank 之后立刻做一次单元素 all_reduce 热身,</span>
<span class="c"># 外部对端必须配合发一次,否则全体死锁(docstring 明文要求)</span></pre>

    <h3><span class="badge nccl">扩展场景 12</span>sleep 模式:ncclCommSuspend 释放通信显存</h3>
    <p><em>触发条件</em>:<code>enable_sleep_mode + enable_nccl_comm_suspend</code>(config/model.py:392,实验特性)。睡眠时 <code>gpu_worker.py:328</code> 调 <code>suspend_device_comms()</code>(parallel_state.py:189,遍历所有设备通信器)→ <code>PyNcclCommunicator.suspend</code> → <code>ncclCommSuspend(comm, 0x01)</code>(要求 NCCL ≥ 2.29.7,按 <code>has_symbol</code> 探测,缺失则 warning_once 跳过),释放通信器内部缓冲显存但保留拓扑;唤醒时 <code>resume_device_comms</code> → <code>ncclCommResume</code>。同族 API 还有 checkpoint 场景的 <code>checkpoint_prepare/restore</code>(FlashInfer 工作区与 NCCL 缓冲先腾后还,cuda_communicator.py:890)。<code>sleep_mode_backend.py</code> 的 docstring 把"是否销毁集体通信器、是否保留含通信 kernel 的图"列为各后端的核心差异维度。</p>

    <h3><span class="badge nccl">场景 13</span>排查速查表</h3>
    <div class="note reveal"><b>使用姿势:</b>该表把"现象 → 机制 → 代码位置"压缩成一行一题,适合出问题时倒查;配合 <code>NCCL_DEBUG=INFO</code>(NCCL 自身日志,由库读取而非 vLLM 设置)与上文启动日志,基本可以定位绝大多数 TP 通信异常。</div>
    <table class="tbl reveal">
      <tr><th>问题 / 症状</th><th>背后的机制</th><th>定位</th></tr>
      <tr><td>想确认本次部署启用了哪些 all-reduce 后端</td><td>启动日志打印分发顺序与启用集合(潜在后端全集 8 个)</td><td>cuda_communicator.py:308</td></tr>
      <tr><td>TP=2 为什么没走 NCCL symm-mem</td><td><code>min_world_size=4</code>,2 卡只可能 custom AR / pynccl</td><td>all_reduce_utils.py:111</td></tr>
      <tr><td>怀疑两卡 P2P 实际不通、custom AR 静默退化</td><td><code>gpu_p2p_access_check</code> 用子进程做真实 IPC 读写探测并写 JSON 缓存(<code>VLLM_CACHE_ROOT</code>),不信 <code>can_device_access_peer</code></td><td>all_reduce_utils.py:246</td></tr>
      <tr><td>图捕获报 NCCL unhandled cuda error</td><td>常见原因:走了含同步 API 的 c10d 路径(如误设 <code>VLLM_DISABLE_PYNCCL=1</code>);错误字符串经 <code>NCCL_CHECK</code> + <code>ncclGetLastError</code> 抛出</td><td>pynccl_wrapper.py:458</td></tr>
      <tr><td>想换 NCCL 版本做 A/B 实验</td><td><code>VLLM_NCCL_SO_PATH</code> 指定 .so 路径即可,无需重编译;symm-mem 需另外提供 nccl.h</td><td>utils/nccl.py:20;pynccl_allocator.py:104</td></tr>
      <tr><td>通信器销毁阶段卡死</td><td><code>destroy()</code> 故意在 daemon 线程限时 5s 调 <code>ncclCommAbort</code>,因为 abort 要等所有引用它的图先销毁</td><td>pynccl.py:250</td></tr>
      <tr><td>symm-mem 报"requires NCCL 2.27.3"</td><td><code>nccl_symm_mem_context.__enter__</code> 的版本断言;window 符号缺失也会在绑定层 warning</td><td>pynccl_allocator.py:167</td></tr>
      <tr><td>BatchInvariant 下仍不确定</td><td>强制单通道 Tree + 禁用 NVLS/CollNet/symm/FlashInfer;ROCm 浮点还有专用 kernel</td><td>batch_invariant.py:1405</td></tr>
    </table>

    <h3>场景总表</h3>
    <table class="tbl reveal">
      <tr><th>场景</th><th>通信原语</th><th>调用入口</th><th>代码位置</th><th>备注</th></tr>
      <tr><td>1 初始化建组</td><td>—(建 ncclComm_t)</td><td><code>init_distributed_environment</code> → <code>CudaCommunicator.__init__</code></td><td>parallel_state.py:1843;cuda_communicator.py:107</td><td>device_group(nccl)+cpu_group(gloo) 双通道</td></tr>
      <tr><td>2 TP all-reduce</td><td>ncclAllReduce</td><td><code>RowParallelLinear.forward</code></td><td>linear.py:1822 → cuda_communicator.py:384</td><td>按尺寸分发,NCCL symm/custom AR/pynccl 竞争</td></tr>
      <tr><td>3 TP all-gather</td><td>ncclAllGather</td><td><code>ColumnParallelLinear</code> / <code>LogitsProcessor</code></td><td>linear.py:631;logits_processor.py:130</td><td>dim=0 且 symm 开启走 NVLS</td></tr>
      <tr><td>4 DP/EP 归约散布</td><td>ncclReduceScatter / grouped ncclReduce / ncclBroadcast</td><td><code>reduce_scatter(v)</code> / <code>all_gatherv</code> / AgRs</td><td>cuda_communicator.py:518/569;pynccl.py:329/392</td><td>变长 sizes 用 grouped 组合;into_output 免分配</td></tr>
      <tr><td>5 广播</td><td>ncclBroadcast / c10d broadcast</td><td>PPHandler、权重热更新、对象广播</td><td>pp_utils.py:60;nccl_engine.py:242;shm_broadcast.py</td><td>对象广播同节点优先 shm+zmq</td></tr>
      <tr><td>6 EP all-to-all(naive)</td><td>ncclSend/Recv(grouped)</td><td><code>all_to_all_single</code>、AgRs dispatch/combine</td><td>pynccl.py:489;all2all.py:57;batch_shard.py:403</td><td>DeepEP/MoRI/MoonEP 为非 NCCL 替代;DeepEPv2 依赖 NCCL GIN 探测</td></tr>
      <tr><td>7 CUDA Graph 捕获</td><td>任意 pynccl 原语@捕获流</td><td><code>graph_capture</code> 上下文</td><td>parallel_state.py:678;pynccl.py:293</td><td>current_stream 即捕获流,无 CPU 同步</td></tr>
      <tr><td>8 NCCL window(对称内存)</td><td>ncclCommWindowRegister / ncclMemAlloc</td><td><code>nccl_symm_mem_context</code></td><td>pynccl_allocator.py:134;cuda_communicator.py:682</td><td>NVLS 零拷贝,scratch 高水位缓存</td></tr>
      <tr><td>9 DP 元数据同步</td><td>c10d all_reduce(nccl 或 gloo)</td><td><code>_run_ar</code></td><td>dp_utils.py:57;config/vllm.py:1752</td><td>可整体切 CPU gloo</td></tr>
      <tr><td>10 权重热更新</td><td>ncclBroadcast(独立 world)</td><td><code>receive_weights</code></td><td>weight_transfer/nccl_engine.py;pynccl.py:194</td><td>支持 torch-free trainer(unique-id bytes)</td></tr>
      <tr><td>11 EPLB 再平衡</td><td>grouped ncclSend/Recv</td><td><code>PyNcclEplbCommunicator</code></td><td>eplb_communicator.py:694</td><td>配 NCCL_MAX_CTAS 限流</td></tr>
      <tr><td>12 sleep 挂起</td><td>ncclCommSuspend/Resume</td><td><code>suspend_device_comms</code></td><td>parallel_state.py:189;pynccl.py:643</td><td>释放通信显存,保留拓扑</td></tr>
    </table>
  </section>

  <!-- ============ 6 动画演示 ============ -->
  <section id="s6">
    <h2 class="sec"><span class="num">6</span>动画演示</h2>
    <p class="lede">三个动画全部自动循环、无交互依赖:动画 1 建立分层心智模型,动画 2 还原 NCCL 内部最核心的 Ring 两阶段算法,动画 3 把场景 2 的分发代码转成可视路由。</p>
    <table class="tbl reveal">
      <tr><th>动画</th><th>演示内容</th><th>实现技术 / 周期</th></tr>
      <tr><td>1 · 调用栈下沉</td><td>一次 TP all-reduce 从模型层穿过六层直达硬件,逐层高亮</td><td>CSS keyframes(14s 循环)</td></tr>
      <tr><td>2 · Ring AllReduce</td><td>4 卡环形拓扑,Reduce-Scatter 与 All-Gather 两阶段换色</td><td>SVG animate + animateTransform(12s 循环)</td></tr>
      <tr><td>3 · 尺寸→后端分发</td><td>消息从 1KB 增长到 1GB,三条后端通道按门控轮流点亮</td><td>CSS keyframes(15s 循环)</td></tr>
    </table>

    <h3>动画 1 · 一次 TP all-reduce 的调用栈下沉</h3>
    <p>数据包(青色光点)自模型层出发,依次点亮六层:自定义 op 注册层 → 组查找与分发枢纽 → 各 all-reduce 后端 → <code>NCCLLibrary</code> 的 C 符号 → 硬件互连。<em>每次下行都是一次普通函数 / FFI 调用,唯一入队的 GPU 工作在 PyNccl 层产生并绑定当前流</em>。</p>
    <div class="figure reveal">
      <div class="klabel">ANIMATED · 六层调用栈下沉(14s 循环)</div>
      <div class="stack">
        <div class="pkt"></div>
        <div class="layer l1"><span class="nm">⑥ 模型层 <code>RowParallelLinear.forward</code></span><span class="ln">linear.py:1822</span></div>
        <div class="layer l2"><span class="nm">⑤ <code>tensor_model_parallel_all_reduce</code> → <code>torch.ops.vllm.all_reduce</code></span><span class="ln">communication_op.py:12</span></div>
        <div class="layer l3"><span class="nm">④ <code>GroupCoordinator</code> 按 group_name 查组</span><span class="ln">parallel_state.py:730</span></div>
        <div class="layer l4"><span class="nm">③ <code>CudaCommunicator.all_reduce</code> 尺寸分发</span><span class="ln">cuda_communicator.py:384</span></div>
        <div class="layer l5"><span class="nm">② <code>PyNcclCommunicator.all_reduce</code> → <code>ncclAllReduce(..., stream)</code></span><span class="ln">pynccl.py:273</span></div>
        <div class="layer l6"><span class="nm">① libnccl.so.2 → NVLink / NVSwitch / IB 环形规约</span><span class="ln">hardware</span></div>
      </div>
      <ul class="al">
        <li><b>青色光点</b> = 张量指针逐层下沉;每层高亮约 2.2 秒,对应数据到达。</li>
        <li>第⑤层发生的是 <em>Dynamo 友好</em>的 custom op 包装:PyTorch custom op 不允许传入任意对象(<code>self</code>),所以只传字符串组名(parallel_state.py:730 docstring 说明了这一约束)。</li>
        <li>第③层是一次"竞标":多个后端按尺寸门槛依次表态,光点最终只能走一条。</li>
        <li>第②层之后<em>不再有 Python 对象</em>——只剩裸指针、元素数、dtype 枚举和流句柄五个 C 参数。</li>
      </ul>
      <div class="legend"><span><i style="background:var(--accent2)"></i>数据包(张量指针)下行</span><span><i style="background:var(--accent)"></i>高亮 = 当前所在层</span><span>循环 14s,自动播放</span></div>
      <div class="cap">图 13-2 · 一次 TP all-reduce 的调用栈下沉:光点自模型层逐层下探直达硬件</div>
    </div>

    <h3>动画 2 · NCCL Ring AllReduce 两阶段(4 卡)</h3>
    <p>NCCL 对中等消息的经典算法:4 卡各把张量切成 4 块,<em>阶段① Reduce-Scatter</em>(绿色)中每个 chunk 沿环顺时针走一跳、在途经卡上与本卡对应块相加,N-1 步后每卡持有一块<em>完整和</em>;<em>阶段② All-Gather</em>(蓝色)中这些完整块再沿环回流一圈,每卡集齐全部结果。</p>
    <div class="figure reveal">
      <div class="klabel">ANIMATED · Ring AllReduce 两阶段(12s 循环)</div>
      <svg viewBox="0 0 560 420" xmlns="http://www.w3.org/2000/svg" font-family="JetBrains Mono,Consolas,monospace">
        <defs>
          <marker id="arr" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0,0 L10,5 L0,10 z" fill="#263352"/></marker>
        </defs>
        <circle cx="280" cy="215" r="112" fill="none" stroke="#263352" stroke-width="2" stroke-dasharray="6 5"/>
        <g stroke="#263352" stroke-width="1.5" marker-end="url(#arr)">
          <line x1="368" y1="108" x2="382" y2="122"/>
          <line x1="382" y1="308" x2="368" y2="322"/>
          <line x1="192" y1="322" x2="178" y2="308"/>
          <line x1="178" y1="122" x2="192" y2="108"/>
        </g>
        <!-- GPU 节点 -->
        <g font-size="11.5" text-anchor="middle">
          <rect x="228" y="56" width="104" height="40" rx="8" fill="#141d33" stroke="#4f8cff"/>
          <text x="280" y="73" fill="#4f8cff" font-weight="bold">GPU 0</text><text x="280" y="89" fill="#8ea0c2">a0 a1 a2 a3</text>
          <rect x="404" y="195" width="104" height="40" rx="8" fill="#141d33" stroke="#4f8cff"/>
          <text x="456" y="212" fill="#4f8cff" font-weight="bold">GPU 1</text><text x="456" y="228" fill="#8ea0c2">b0 b1 b2 b3</text>
          <rect x="228" y="334" width="104" height="40" rx="8" fill="#141d33" stroke="#4f8cff"/>
          <text x="280" y="351" fill="#4f8cff" font-weight="bold">GPU 2</text><text x="280" y="367" fill="#8ea0c2">c0 c1 c2 c3</text>
          <rect x="12" y="195" width="104" height="40" rx="8" fill="#141d33" stroke="#4f8cff"/>
          <text x="64" y="212" fill="#4f8cff" font-weight="bold">GPU 3</text><text x="64" y="228" fill="#8ea0c2">d0 d1 d2 d3</text>
        </g>
        <!-- 阶段标签 -->
        <g font-size="12" text-anchor="middle" font-weight="bold">
          <text x="280" y="205" fill="#34d399">① Reduce-Scatter:chunk 顺流逐跳求和
            <animate attributeName="opacity" values="1;1;0;0;1" keyTimes="0;0.42;0.5;0.92;1" dur="12s" repeatCount="indefinite"/></text>
          <text x="280" y="205" fill="#4f8cff" opacity="0">② All-Gather:完整块回流广播
            <animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.42;0.5;0.92;1" dur="12s" repeatCount="indefinite"/></text>
          <text x="280" y="232" fill="#8ea0c2" font-weight="normal" font-size="10.5">N-1 步后每卡一块完整和 → 再环传一圈集齐</text>
        </g>
        <!-- 环上数据包:8 个,45° 分布,12s 一圈,前半绿后半蓝 -->
        <g>
          <g transform="rotate(0 280 215)"><g><animateTransform attributeName="transform" type="rotate" from="0 280 215" to="360 280 215" dur="12s" repeatCount="indefinite"/>
            <rect x="274" y="97" width="12" height="12" rx="3" fill="#34d399"><animate attributeName="fill" values="#34d399;#34d399;#4f8cff;#4f8cff;#34d399" keyTimes="0;0.45;0.5;0.95;1" dur="12s" repeatCount="indefinite"/></rect></g></g>
          <g transform="rotate(45 280 215)"><g><animateTransform attributeName="transform" type="rotate" from="0 280 215" to="360 280 215" dur="12s" repeatCount="indefinite"/>
            <rect x="274" y="97" width="12" height="12" rx="3" fill="#34d399"><animate attributeName="fill" values="#34d399;#34d399;#4f8cff;#4f8cff;#34d399" keyTimes="0;0.45;0.5;0.95;1" dur="12s" repeatCount="indefinite"/></rect></g></g>
          <g transform="rotate(90 280 215)"><g><animateTransform attributeName="transform" type="rotate" from="0 280 215" to="360 280 215" dur="12s" repeatCount="indefinite"/>
            <rect x="274" y="97" width="12" height="12" rx="3" fill="#34d399"><animate attributeName="fill" values="#34d399;#34d399;#4f8cff;#4f8cff;#34d399" keyTimes="0;0.45;0.5;0.95;1" dur="12s" repeatCount="indefinite"/></rect></g></g>
          <g transform="rotate(135 280 215)"><g><animateTransform attributeName="transform" type="rotate" from="0 280 215" to="360 280 215" dur="12s" repeatCount="indefinite"/>
            <rect x="274" y="97" width="12" height="12" rx="3" fill="#34d399"><animate attributeName="fill" values="#34d399;#34d399;#4f8cff;#4f8cff;#34d399" keyTimes="0;0.45;0.5;0.95;1" dur="12s" repeatCount="indefinite"/></rect></g></g>
          <g transform="rotate(180 280 215)"><g><animateTransform attributeName="transform" type="rotate" from="0 280 215" to="360 280 215" dur="12s" repeatCount="indefinite"/>
            <rect x="274" y="97" width="12" height="12" rx="3" fill="#34d399"><animate attributeName="fill" values="#34d399;#34d399;#4f8cff;#4f8cff;#34d399" keyTimes="0;0.45;0.5;0.95;1" dur="12s" repeatCount="indefinite"/></rect></g></g>
          <g transform="rotate(225 280 215)"><g><animateTransform attributeName="transform" type="rotate" from="0 280 215" to="360 280 215" dur="12s" repeatCount="indefinite"/>
            <rect x="274" y="97" width="12" height="12" rx="3" fill="#34d399"><animate attributeName="fill" values="#34d399;#34d399;#4f8cff;#4f8cff;#34d399" keyTimes="0;0.45;0.5;0.95;1" dur="12s" repeatCount="indefinite"/></rect></g></g>
          <g transform="rotate(270 280 215)"><g><animateTransform attributeName="transform" type="rotate" from="0 280 215" to="360 280 215" dur="12s" repeatCount="indefinite"/>
            <rect x="274" y="97" width="12" height="12" rx="3" fill="#34d399"><animate attributeName="fill" values="#34d399;#34d399;#4f8cff;#4f8cff;#34d399" keyTimes="0;0.45;0.5;0.95;1" dur="12s" repeatCount="indefinite"/></rect></g></g>
          <g transform="rotate(315 280 215)"><g><animateTransform attributeName="transform" type="rotate" from="0 280 215" to="360 280 215" dur="12s" repeatCount="indefinite"/>
            <rect x="274" y="97" width="12" height="12" rx="3" fill="#34d399"><animate attributeName="fill" values="#34d399;#34d399;#4f8cff;#4f8cff;#34d399" keyTimes="0;0.45;0.5;0.95;1" dur="12s" repeatCount="indefinite"/></rect></g></g>
        </g>
      </svg>
      <div class="cap">图 13-3 · Ring AllReduce:前半圈(绿)做 Reduce-Scatter,后半圈(蓝)做 All-Gather;方块即沿环流动的数据 chunk</div>
    </div>
    <ul class="al reveal">
      <li><b>总传输量</b> = 2×(N-1)/N×张量大小,与卡数近似无关——这就是 Ring 对大消息友好的原因。</li>
      <li><b>每卡的收发带宽对称</b>:每步每卡只发 1/N 的数据,N 卡同时进行,链路无热点。</li>
      <li>vLLM 侧对应 <code>pynccl_comm.all_reduce</code> 提交的 <code>ncclAllReduce</code>;NCCL 内部再按拓扑决定 Ring/Tree/NVLS,动画展示的是 Ring。</li>
      <li>对照:<code>CustomAllreduce</code> 在小消息时直接用 IPC 单跳完成,连环都不建——这是分发链上它排在 NCCL 前面的原因。</li>
    </ul>

    <h3>动画 3 · 消息尺寸 → 后端分发(8 卡 NVLink 集群)</h3>
    <p>光标沿尺寸轴从 1KB 扫到 1GB 循环移动,三条通道按 <code>NCCL_SYMM_MEM_ALL_REDUCE_CONFIG</code> 与 <code>CustomAllreduce</code> 的门控依次点亮,对应 <code>CudaCommunicator.all_reduce</code> 的真实决策(8 卡:≤16KiB → NCCL symm;16–128KiB → custom AR;≥128KiB → NCCL symm;pynccl 作为未启用 symm 时的承接与兜底)。</p>
    <div class="figure reveal">
      <div class="klabel">ANIMATED · 尺寸 → 后端分发路由(15s 循环)</div>
      <div class="dispatch">
        <div class="lanes">
          <div class="lane laneA"><b style="color:var(--good)">Custom AllReduce / QuickReduce</b><span>IPC + P2P 单跳 kernel<br>中段尺寸 16KiB–128KiB(ws=8)<br>custom_all_reduce.py / quick_all_reduce.py</span></div>
          <div class="lane laneB"><b style="color:var(--accent)">NCCL Symm Mem(NVLS)</b><span>≤16KiB 小消息与 ≥128KiB 大消息<br>ws ≥ 4 且 &gt;8 一律启用<br>pynccl + ncclCommWindowRegister</span></div>
          <div class="lane laneC"><b style="color:var(--purple)">PyNccl / c10d NCCL</b><span>Ring/Tree 通用路径与兜底<br>VLLM_USE_NCCL_SYMM_MEM=0 时承接全部<br>fp8/fp4 大带宽场景</span></div>
        </div>
        <div class="axis">
          <div class="axis-bar"></div>
          <i style="left:1%">1KB</i><i style="left:18%">16KiB</i><i style="left:42%">128KiB</i><i style="left:72%">1MiB</i><i style="left:99%">1GiB</i>
          <div class="cursor"></div>
        </div>
      </div>
      <ul class="al">
        <li><b>小消息段(≤16KiB)</b>:NVLS 多播一次入网,延迟低于任何 P2P 拼接;all_reduce_utils.py 注释实测 1.21x–1.48x 优势。</li>
        <li><b>中段(16–128KiB)</b>:custom AR 的"一次 kernel + 零拷贝读对端"胜出,NCCL symm 的 copy-in/copy-out 反而吃亏。</li>
        <li><b>大消息(≥128KiB 到 GB 级)</b>:带宽为王,NVLS/Ring 重新接管,实测最高 6.14x 优势。</li>
        <li><b>前提条件动画未画</b>:custom AR 还要求单节点 + full-mesh P2P + TP 组;多节点部署中段消息会直接落到 PyNccl。</li>
      </ul>
      <div class="legend"><span><i style="background:var(--accent2)"></i>消息尺寸扫描(15s 循环)</span><span><i style="background:var(--good)"></i>custom AR 窗口</span><span><i style="background:var(--accent)"></i>NCCL symm 窗口</span><span><i style="background:var(--purple)"></i>通用 NCCL</span></div>
      <div class="cap">图 13-4 · 消息尺寸 → 后端分发路由:三条通道按尺寸门控轮流点亮</div>
    </div>
    <p>三个动画合起来读:<em>动画 1 是"软件栈怎么走",动画 2 是"数据在硬件上怎么流",动画 3 是"每一次调用由谁承接"</em>。三者叠加,即为 vLLM 中一次 NCCL 通信的完整画像。</p>
  </section>

  <!-- ============ 7 与其他通信后端的关系 ============ -->
  <section id="s7">
    <h2 class="sec"><span class="num">7</span>与其他通信后端的关系</h2>
    <p class="lede">vLLM 的通信层是一条逐级竞争、逐级回退的链,NCCL 是兜底而非唯一;分发链的"宽度"本身就是硬件能力的函数。</p>
    <p>vLLM 的通信层是一条<em>逐级竞争、逐级回退</em>的链,NCCL 是兜底而非唯一。<code>CudaCommunicator.all_reduce</code> 的尝试顺序即优先级,把它画成决策树(对应场景 2 的代码,箭头后为命中的实现):</p>
    <pre class="code">CudaCommunicator.all_reduce(input_)
├─ FlashInfer MNNVL 预判(should_use_fi_ar)────── 命中则压制 NCCL symm 分支
├─ NCCL symm mem:ws≥4 且 (≤16KiB 或 ≥128KiB/512KiB)
│    └─▶ torch.ops.vllm.all_reduce_symmetric_with_copy(pynccl + window)
├─ QuickReduce(ROCm MI300)命中 ──────────────────▶ quickreduce kernel
├─ FlashInfer PCIe IPC 拓扑命中 ──────────────────▶ PCIe IPC kernel
├─ AITER custom / CustomAllreduce:
│    单节点 full-mesh P2P + 中段尺寸 + TP 组 ─────▶ IPC 单跳 all-reduce
├─ BatchInvariant(ROCm 浮点)───────────────────▶ batch_invariant kernel
├─ torch symm_mem(尺寸表命中)───────────────────▶ one/two-shot 对称内存
└─ 其余一切 ─────────────────────────────────────▶ PyNcclCommunicator.all_reduce
     ├─ pynccl 可用 ──▶ ncclAllReduce @ current_stream(可图捕获)
     └─ 不可用/禁用 ──▶ torch.distributed.all_reduce(device_group, c10d-NCCL)</pre>
    <p>各后端"何时不用 NCCL"的分工:</p>
    <table class="tbl reveal">
      <tr><th>后端</th><th>何时胜过 NCCL</th><th>何时让位 / 失效</th></tr>
      <tr><td><code>CustomAllreduce</code>(custom_all_reduce.py)</td><td>单节点、full-mesh P2P(NVLink)、TP 组、中小消息(8 卡约 16–128KiB 窗口);一次 kernel 完成,无 NCCL 启动开销</td><td>多节点、P2P 探测失败(<code>gpu_p2p_access_check</code> 真实探测而非仅 API)、ws&gt;8、超大消息;图缓冲需 <code>register_graph_buffers</code></td></tr>
      <tr><td><code>SymmMemCommunicator</code>(symm_mem.py)</td><td>启用 <code>VLLM_ALLREDUCE_USE_SYMM_MEM</code>(默认开)且尺寸在按 capability 的 <code>SYMM_MEM_ALL_REDUCE_MAX_SIZES</code> 表内</td><td>H100/GB200 之外无 NVLS、超表、BatchInvariant</td></tr>
      <tr><td><code>FlashInferAllReduce / PcieIpc</code></td><td>GB200 NVLink domain(MNNVL)按 tuning 表;PCIe IPC 拓扑</td><td>无对应硬件;<code>VLLM_BATCH_INVARIANT</code>(非固定归约顺序)</td></tr>
      <tr><td><code>QuickAllReduce</code></td><td>ROCm MI300 补充中段窗口</td><td>非 MI300;与 custom AR 互补而非互斥(cuda_communicator.py:191 注释)</td></tr>
      <tr><td><code>gloo / CPUSHM</code></td><td>CPU 组元数据、DP 同步降级、CPU 平台推理</td><td>张量热路径完全不用(带宽低一个量级)</td></tr>
      <tr><td><code>shm_broadcast.MessageQueue</code></td><td>同节点对象广播(4MiB 缓冲),免去 pickle+NCCL 往返</td><td>跨节点自动退回 <code>dist.broadcast_object_list</code></td></tr>
      <tr><td>DeepEP / MoRI / MoonEP / NIXL</td><td>EP 大规模 token 交换,占用专用 RDMA/NVLink 通道</td><td>naive 后端(小规模 EP)反而用回 NCCL 的 ag/rs 组合</td></tr>
    </table>
    <p>反过来,NCCL 也有别人替代不了的时刻:<em>超大消息带宽场景</em>(TP&gt;8、多机、大 logits)、<em>变长聚合</em>(grouped ncclReduce/Broadcast 组合出 reduce_scatterv/all_gatherv)、<em>独立 world 需求</em>(权重热更新、PP 旁路组、elastic EP)、<em>确定性模式</em>(BatchInvariant 通过 NCCL 环境变量强制单通道树归约,而非禁用 NCCL),以及<em>能力探针</em>(DeepEPv2 的 GIN 检查)。系列第 15 篇将展开各替代 kernel 的内部实现。</p>
    <p>最后补一张视角:这张竞争网络在<em>平台层</em>还有一层退化——同样的 <code>GroupCoordinator</code> 接口,XPU 上只有 xccl 一条路(无 IPC、无对称内存),CPU 上换成 gloo+SHM,ROCm 上则是 RCCL + AITER + QuickReduce 的组合。也就是说,分发链的"宽度"本身就是硬件能力的函数;阅读任何一段通信代码时,先确认平台分支,再看尺寸分支,最后才是世界大小分支——三层过滤之后剩下的那条路径,才是这次通信真正的归宿。</p>
  </section>

  <!-- ============ 8 小结 ============ -->
  <section id="s8">
    <h2 class="sec"><span class="num">8</span>小结</h2>
    <p class="lede">三句话浓缩:自建一层薄而可控的封装、NCCL 是分发链上的重要一环而非默认、运行时治理齐全。</p>
    <p>vLLM 对 NCCL 的使用可以浓缩为三句话。<em>第一,自建一层薄而可控的封装</em>:<code>NCCLLibrary</code> 用 ctypes 直连 C 符号换取版本自由,<code>PyNcclCommunicator</code> 用"一切原语接受 stream 参数"换取 CUDA Graph 安全,用独立 communicator 换取与 c10d 组解耦的 world(权重热更新、elastic EP、EPLB 都受益)。<em>第二,NCCL 是分发链上的重要一环而非默认</em>:小消息让给 IPC 单跳、NVLS 窗口让给对称内存、EP 大交换让给专用 RDMA 库,尺寸门控表直接来自 H100/GB200 实测(<code>NCCL_SYMM_MEM_ALL_REDUCE_CONFIG</code>),并有 <code>_log_all_reduce_backend_selection</code> 把决策过程写进日志。<em>第三,运行时治理齐全</em>:从 <code>pin_nccl_env</code> 的 NCCL_NO_CACHE 机制、BatchInvariant 的强制树归约,到 sleep 模式的 <code>ncclCommSuspend</code>、checkpoint 进程的 NCCL_CUMEM 系列关闭,NCCL 的每个生命周期阶段都被显式管理。</p>
    <h3>八个速查事实</h3>
    <p>以下事实全部可在源码中一键定位,面试、评审与排障时可直接引用:</p>
    <div class="facts reveal">
      <div class="f"><b>1 · PyNccl 从不自己同步流</b><span>唯一一次 <code>stream.synchronize()</code> 在建组热身(pynccl.py:191),之后全部异步</span></div>
      <div class="f"><b>2 · all_reduce 入口是字符串</b><span>custom op 只收 <code>group_name</code>,经 parallel_state.py:199 的注册表查回组对象</span></div>
      <div class="f"><b>3 · pynccl 必须挂 gloo 组</b><span>pynccl.py:114 assert 拒绝 NCCL 组——元数据与数据永远分通道</span></div>
      <div class="f"><b>4 · window 注册是集体操作</b><span>非均匀对称池分配会死锁,故变长 reduce_scatterv 不走 symm(cuda_communicator.py:638)</span></div>
      <div class="f"><b>5 · 销毁用 Abort 不用 Destroy</b><span><code>ncclCommDestroy</code> 是集体调用;abort 放 daemon 线程限时 5s(pynccl.py:250)</span></div>
      <div class="f"><b>6 · fp8 走两条路</b><span>集合用原生 <code>ncclFloat8e4m3</code>,p2p send/recv 一律转 uint8 传字节(pynccl.py:552)</span></div>
      <div class="f"><b>7 · ROCm 全链路复用同一套类</b><span>只是库名换成 <code>librccl.so.1</code>,缺符号容忍而非报错(utils/nccl.py:33)</span></div>
      <div class="f"><b>8 · 图捕获不用注册任何东西</b><span>pynccl 无 capture 钩子;需要注册的是 custom AR 的 IPC 缓冲与对称内存池切换</span></div>
      <div class="f"><b>9 · abort 线程不得引用 self</b><span>若线程活到解释器关闭,释放 <code>self.group</code> 会在 C++ 析构里放 GIL 导致崩溃,故先取出裸引用(pynccl.py:258 注释)</span></div>
      <div class="f"><b>10 · 图池 id 由外部注入</b><span><code>set_graph_pool_id</code>(compilation/cudagraph_pool.py)供对称内存上下文暂停/恢复 CUDA Graph 池使用</span></div>
    </div>
    <p>理解这张网的关键,是记住 <code>CudaCommunicator.all_reduce</code>(cuda_communicator.py:384)这一个函数——它是所有 TP 通信的<em>分岔口</em>;其余场景(EPLB、权重热更新、PP 旁路组)则是 <code>PyNcclCommunicator</code> 独立建组能力的延伸。下一篇(第 14 篇)我们将从 Git 历史看这套封装如何一步步演化成今天的形态。</p>
  </section>

  <div class="pgnav">
    <span>vLLM 深度解析系列 · 第 13 篇 · 由 ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/vllm/12-pd-disagg/">← 上一篇:⑫ PD 分离</a> · <a href="/docs/inference-engines/vllm/">返回总览</a> · <a href="/docs/inference-engines/vllm/14-nccl-pr-history/">下一篇:⑭ NCCL 合入历史 →</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>NCCL 相关合入历史全景图</title><link>https://hccl.club/docs/inference-engines/vllm/14-nccl-pr-history/</link><pubDate>Sat, 07 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/vllm/14-nccl-pr-history/</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: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 .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;flex-wrap:wrap}
.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 .card p b{color:#fff}
.fwdoc .card.lane{border-left:4px solid var(--pc,var(--accent))}
.fwdoc .card h3 .badge{margin-left:auto;flex-shrink:0}
.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 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:2px 4px 2px 0}
.fwdoc .paths{margin:10px 0 4px;line-height:2.1}
.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 .figure .klabel{font-size:11px;color:#5a6b92;letter-spacing:1px;text-transform:uppercase;margin-bottom:10px}
.fwdoc .figsub{text-align:center;color:var(--muted);font-size:12.5px;margin:2px 0 4px}
.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)}}
.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(--tlc,var(--accent));box-shadow:0 0 0 4px var(--tlring,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 .tl-item .tl-body code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;font-family:Consolas,monospace;font-size:12px}
.fwdoc .tl-item.v0{--tlc:#8ea0c2;--tlring:rgba(142,160,194,.20)}
.fwdoc .tl-item.v1{--tlc:#4f8cff;--tlring:rgba(79,140,255,.20)}
.fwdoc .tl-item.v2{--tlc:#34d399;--tlring:rgba(52,211,153,.20)}
.fwdoc .tl-item.v3{--tlc:#a78bfa;--tlring:rgba(167,139,250,.20)}
.fwdoc .tl-item.v4{--tlc:#f87171;--tlring:rgba(248,113,113,.20)}
.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 .subh{font-size:15.5px;color:#fff;margin:24px 0 8px;font-weight:700;display:flex;align-items:center;gap:8px}
.fwdoc .subh::before{content:"";width:8px;height:8px;border-radius:2px;background:linear-gradient(135deg,var(--accent),var(--accent2));flex-shrink:0}
.fwdoc .statrow{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px;margin:18px 0}
.fwdoc .stat{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);border-radius:12px;
  padding:16px 18px;text-align:center;position:relative;overflow:hidden}
.fwdoc .stat::after{content:"";position:absolute;left:0;right:0;bottom:0;height:3px;
  background:linear-gradient(90deg,var(--accent),var(--accent2));transform:scaleX(0);transform-origin:left;transition:transform 1s .3s}
.fwdoc .reveal.on .stat::after{transform:scaleX(1)}
.fwdoc .stat .v{font-size:30px;font-weight:800;color:#fff;font-family:Consolas,Menlo,monospace}
.fwdoc .stat .k{font-size:11.5px;color:var(--muted);margin-top:2px;letter-spacing:.3px}
.fwdoc .stat.c .v{color:var(--accent2)}
.fwdoc .stat.g .v{color:var(--good)}
.fwdoc .stat.p .v{color:var(--purple)}
.fwdoc .stat.w .v{color:var(--warn)}
.fwdoc .panoWrap{position:relative;overflow-x:auto;border:1px solid var(--border);border-radius:10px;
  padding:12px 10px 8px;background:rgba(11,16,32,.55)}
.fwdoc #panoSvg{display:block;min-width:1000px;width:100%;height:auto}
.fwdoc #panoSvg text{font-family:"PingFang SC","Microsoft YaHei","Segoe UI",system-ui,sans-serif}
.fwdoc #panoSvg .mono-t{font-family:Consolas,Menlo,monospace}
.fwdoc .lband{transition:opacity .5s}
.fwdoc .lname{fill:#8ea0c2;font-size:10.5px;font-weight:600;text-anchor:end}
.fwdoc .lname.on{fill:#dbe4f5;font-weight:800}
.fwdoc .lnum{fill:#5a6b92;font-size:9px;text-anchor:end;font-family:Consolas,Menlo,monospace}
.fwdoc .qline{stroke:#1a2440;stroke-width:1}
.fwdoc .qtxt{fill:#8ea0c2;font-size:10.5px;text-anchor:middle}
.fwdoc .qtxt.yr{fill:#4f8cff;font-weight:700}
.fwdoc .era{opacity:.16}
.fwdoc .era-t{font-size:10.5px;text-anchor:middle;font-weight:700}
.fwdoc .nd{fill:#1a2440;stroke:currentColor;stroke-width:1.4;transition:fill .25s,filter .25s;cursor:pointer}
.fwdoc .nd.lit{fill:currentColor;filter:drop-shadow(0 0 4px currentColor)}
.fwdoc .nlab{fill:#8ea0c2;font-size:8.5px;text-anchor:middle;pointer-events:none;font-family:Consolas,Menlo,monospace}
.fwdoc .nlab.lit{fill:#dbe4f5}
.fwdoc .scanline{stroke:#22d3ee;stroke-width:1.6;opacity:.9;filter:drop-shadow(0 0 5px rgba(34,211,238,.8))}
.fwdoc .scanhead{fill:#22d3ee;opacity:.9}
.fwdoc #tt{position:absolute;z-index:50;max-width:330px;pointer-events:none;
  background:rgba(11,16,32,.96);border:1px solid #22d3ee;border-radius:8px;
  padding:8px 11px;font-size:12.5px;line-height:1.55;color:var(--text);
  box-shadow:0 4px 16px rgba(0,0,0,.5);display:none}
.fwdoc #tt .tt-pr{color:#22d3ee;font-weight:800;font-family:Consolas,Menlo,monospace}
.fwdoc #tt .tt-date{color:var(--muted);font-size:11.5px;margin-left:6px}
.fwdoc #tt .tt-lane{font-size:11.5px;color:var(--warn);margin-bottom:2px}
.fwdoc #tt .tt-title{color:var(--text)}
.fwdoc .laneCap{background:#0b1020;border:1px dashed var(--border);border-radius:8px;
  padding:10px 16px;margin:10px 0 0;font-size:14px;min-height:64px}
.fwdoc .laneCap .lc-no{color:var(--muted);font-size:12px;letter-spacing:1px}
.fwdoc .laneCap .lc-name{font-weight:800;font-size:15.5px;margin:0 8px}
.fwdoc .laneCap .lc-desc{color:var(--muted);font-size:13.5px;margin-top:3px}
.fwdoc .legend{display:flex;flex-wrap:wrap;gap:8px 16px;margin-top:12px;padding:10px 14px;
  background:#0b1020;border:1px dashed var(--border);border-radius:8px;font-size:12.5px;color:var(--muted)}
.fwdoc .legend .sw{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:5px;vertical-align:-1px}
.fwdoc .bars{display:flex;align-items:flex-end;justify-content:center;gap:56px;height:300px;
  padding:10px 10px 0;border-bottom:2px solid var(--border);margin:14px 0 0}
.fwdoc .bcol{display:flex;flex-direction:column;align-items:center;justify-content:flex-end;height:100%}
.fwdoc .bval{font-size:19px;font-weight:800;color:var(--bc,#4f8cff);margin-bottom:5px;
  font-family:Consolas,Menlo,monospace;opacity:0;animation:fw-valFade 7.5s var(--bd,0s) infinite}
.fwdoc .bcol .pct{font-size:11.5px;color:var(--muted);margin-bottom:3px;opacity:0;animation:fw-valFade 7.5s var(--bd,0s) infinite}
.fwdoc .bar{width:64px;height:var(--h);background:linear-gradient(180deg,var(--bc),rgba(11,16,32,.35));
  border:1px solid var(--bc);border-bottom:none;border-radius:5px 5px 0 0;
  transform-origin:bottom;transform:scaleY(0);animation:fw-barGrow 7.5s var(--bd,0s) infinite}
.fwdoc .byr-row{display:flex;justify-content:center;gap:56px;padding:0 10px}
.fwdoc .byr{color:var(--text);font-weight:700;font-size:14.5px;margin-top:8px;height:20px;width:64px;text-align:center}
@keyframes fw-barGrow{0%{transform:scaleY(0)}16%{transform:scaleY(1)}82%{transform:scaleY(1);filter:brightness(1.25)}94%,100%{transform:scaleY(0)}}
@keyframes fw-valFade{0%{opacity:0}18%{opacity:1}82%{opacity:1}94%,100%{opacity:0}}
/* ===== 导入面板附加样式 ===== */
.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">通信是多 GPU 推理引擎除算子之外的另一半性能来源——本篇不改代码、不跑模型,只做一件事:把三年半的 PR/commit 合入历史变成可读的地图。</p>
    <p>在多 GPU 推理引擎里,「通信」是除算子之外的另一半性能来源。vLLM 的通信栈并非一夜建成:2023 年 6 月项目诞生时,它只是 <code>torch.distributed</code> 的一个薄封装,进程编排交给 Ray;2024 年 1 月,自研 <code>custom_all_reduce</code> 内核(PR <code>#2192</code>)与 NCCL 控制面(PR <code>#2221</code>)几乎同时落地;两个月后,作者 youkaichao 用 ctypes 手写 <code>pynccl.py</code>(PR <code>#3625</code>)替换掉 cupy 依赖,从此 vLLM 拥有了可直接塞进 CUDA Graph 的集合通信封装。进入 2025 年,V1 引擎的 overlap 调度迫使 pynccl 精简状态机(PR <code>#11744</code> / <code>#11749</code>);2025 下半年,PyTorch 对称内存(PR <code>#20759</code>)、NCCL symmetric memory(PR <code>#24532</code>)、FlashInfer 融合 allreduce(PR <code>#20691</code>)、DeepEP(PR <code>#18434</code>)与 P2P NCCL KV 传输(PR <code>#18242</code>)在四个月内密集合入,通信栈从「一条 TP 总线」扩张成「按消息类型分道的立交桥」。2026 年,演进主战场转向新硬件(NVLS / MNNVL / multimem / Rubin)、弹性与容错 EP、以及 RL 训推一体的 NCCL 权重同步。</p>
    <p>本篇不改代码、不跑模型,只做一件事:<b>把 PR/commit 合入历史变成可读的地图</b>。第 4 章的全景 SVG 将 125 个关键 PR 按 11 条主题泳道铺在 2023-04 → 2026-11 的时间轴上,配合扫描线与泳道轮播两个循环动画,以及年度 commit 数柱状图生长动画,直观呈现「哪些能力何时进入主线、问题在何处被修复」。</p>
    <div class="statrow reveal">
      <div class="stat"><div class="v">24,299</div><div class="k">基线 main @ 5d55ef1590 总 commit 数</div></div>
      <div class="stat c"><div class="v">323</div><div class="k">通信相关 commit(核心口径,去重)</div></div>
      <div class="stat p"><div class="v">125</div><div class="k">全景图 PR 节点(11 条泳道)</div></div>
      <div class="stat g"><div class="v">20</div><div class="k">里程碑 PR(编号+日期+价值)</div></div>
    </div>
  </section>

  <!-- ============ 2 方法论与统计口径 ============ -->
  <section id="s2">
    <h2 class="sec"><span class="num">2</span>方法论与统计口径</h2>
    <p class="lede">数据全部来自本地 git 仓库(main 分支 5d55ef1590,2026-11-01),不依赖网络——检索、并集去重、文件锚定三步可复现,正文统计一律以核心口径 A 为准。</p>
    <p>数据全部来自本地 git 仓库(main 分支 <code>5d55ef1590</code>,2026-11-01),不依赖网络。检索方式为 <code>git log --grep</code>(大小写不敏感)按主题词组合、再对结果取并集去重;同时用 <code>git log --follow</code> 锚定关键文件的历史以校准里程碑。</p>
    <h3 class="subh">2.1 检索命令</h3>
    <pre class="code reveal"><span class="c"># 单主题词(示例):</span>
git log --date=short --pretty=format:"%h|%ad|%s" -i --grep="nccl"

<span class="c"># 核心口径 A:22 组主题词取并集(去重后统计年度分布):</span>
git log --date=short --pretty=format:"%h|%ad|%s" -i \
  --grep="nccl\|pynccl\|allreduce\|all-reduce\|all_gather\|allgather\
\|reduce_scatter\|reduce-scatter\|custom allreduce\|custom_all_reduce\|custom all-reduce\
\|symm_mem\|symmetric memory\|quickreduce\|quick all reduce\|all2all\|all-to-all\
\|deepep\|gloo\|rccl\|multimem\|mnnvl\|nvshmem" | sort -u

<span class="c"># 按年统计:</span>
git log --date=format:%Y --pretty=format:"%ad" -i --grep="..." | sort | uniq -c

<span class="c"># 文件历史锚定(路径随版本迁移,--follow 追踪改名):</span>
git log --follow --date=short --pretty=format:"%h|%ad|%s" \
  -- vllm/distributed/device_communicators/pynccl.py
git log --follow --date=short --pretty=format:"%h|%ad|%s" \
  -- vllm/distributed/device_communicators/custom_all_reduce.py
<span class="c"># 另锚定: symm_mem.py / quick_all_reduce.py / flashinfer_all_reduce.py /
# all2all.py / communication_op.py / parallel_state.py</span></pre>
    <div class="paths reveal"><span class="filepath">vllm/distributed/device_communicators/pynccl.py</span><span class="filepath">vllm/distributed/device_communicators/custom_all_reduce.py</span><span class="filepath">symm_mem.py</span><span class="filepath">quick_all_reduce.py</span><span class="filepath">flashinfer_all_reduce.py</span><span class="filepath">all2all.py</span><span class="filepath">communication_op.py</span><span class="filepath">parallel_state.py</span></div>
    <h3 class="subh">2.2 检索词与单项命中数</h3>
    <p>下表为核心口径 A 的 22 组检索词及其各自命中的 commit 数(词间存在大量重叠,例如 "nccl" 会同时命中 "pynccl",因此并集去重后总数 323 小于各项之和):</p>
    <table class="tbl reveal">
      <tr><th>主题词</th><th>命中</th><th>主题词</th><th>命中</th><th>主题词</th><th>命中</th></tr>
      <tr><td><code>nccl</code></td><td>93</td><td><code>all-reduce</code></td><td>36</td><td><code>reduce_scatter</code></td><td>6</td></tr>
      <tr><td><code>deepep</code></td><td>75</td><td><code>all2all</code></td><td>28</td><td><code>reduce-scatter</code></td><td>6</td></tr>
      <tr><td><code>allreduce</code></td><td>59</td><td><code>mnnvl</code></td><td>16</td><td><code>quickreduce</code></td><td>5</td></tr>
      <tr><td><code>pynccl</code></td><td>17</td><td><code>custom allreduce</code></td><td>13</td><td><code>symm_mem</code> / <code>symmetric memory</code></td><td>5 / 5</td></tr>
      <tr><td><code>allgather</code></td><td>11</td><td><code>custom all-reduce</code></td><td>5</td><td><code>gloo</code></td><td>5</td></tr>
      <tr><td><code>nvshmem</code></td><td>4</td><td><code>all_gather</code></td><td>3</td><td><code>all-to-all</code></td><td>3</td></tr>
      <tr><td><code>multimem</code></td><td>1</td><td><code>rccl</code></td><td>1</td><td><code>quick all reduce</code></td><td>1</td></tr>
    </table>
    <p>辅助宽口径 B 在 A 的基础上追加 <code>collective</code>(27)、<code>communicator</code>(24)、<code>world size</code>(2)、<code>distributed init</code> 等更泛的词,并集为 373 条,用于交叉检验趋势;正文统计一律以口径 A 为准。</p>
    <h3 class="subh">2.3 年度分布(核心口径 A,去重)</h3>
    <table class="tbl reveal">
      <tr><th>年份</th><th>commit 数</th><th>占比</th><th>年度主题速览</th></tr>
      <tr><td>2023(6-12 月)</td><td>1</td><td>0.3%</td><td>仅 <code>#2151</code> all-reduce 显存修复:通信完全依赖 torch.distributed + Ray</td></tr>
      <tr><td>2024</td><td>37</td><td>11.5%</td><td>custom AR、pynccl、vllm/distributed 模块、多 TP 组、torch.compile 兼容、StatelessPG</td></tr>
      <tr><td>2025</td><td>101</td><td>31.3%</td><td>V1 overlap 精简、DP 通信、DeepEP、P/D 分离、symm mem、FI 融合 AR、quick AR</td></tr>
      <tr><td>2026(1-11 月)</td><td>184</td><td>57.0%</td><td>NVLS/MNNVL/multimem、NCCL symm AG/RS、RL 权重同步、弹性/容错 EP、批不变</td></tr>
      <tr><th>合计</th><th>323</th><th>100%</th><th>其中 322 条带 PR 编号(1 条为 Dockerfile 直推)</th></tr>
    </table>
    <div class="note good reveal">
      <b>口径说明:</b>323 / 24,299 ≈ 1.3% 的 commit 显式谈论通信——但通信改动的单个体量(如 <code>#2192</code> 1,453 行、<code>#31943</code> 带四个测试文件)远超平均水平;且 2026 年通信相关 commit 占比升至当年总量的 2%+,呈明显加速曲线(见第 7 章柱状图)。
    </div>
  </section>

  <!-- ============ 3 演进阶段划分 ============ -->
  <section id="s3">
    <h2 class="sec"><span class="num">3</span>演进阶段划分</h2>
    <p class="lede">按「通信能力形态」而非日历硬切,三年半历史划为五个阶段——时间轴节点颜色与全景图阶段色带同族。</p>
    <p>按「通信能力形态」而非日历硬切,三年半历史可划为四个阶段;每阶段末尾给出对应泳道高亮位置。</p>
    <div class="timeline">
      <div class="tl-item v0 reveal">
        <div class="tl-date">2023-06 → 2024-01(约 7 个月)</div>
        <div class="tl-body"><b style="color:#8ea0c2">阶段 0 · 蒙昧期</b> — TP 通信直接走 <code>torch.distributed</code> 的 NCCL 后端,控制面元数据靠 Ray 在 worker 间搬运;全年相关 commit 仅 1 条(<code>#2151</code>,修 all-reduce 显存占用)。通信是「别人家的基础设施」。</div>
      </div>
      <div class="tl-item v1 reveal">
        <div class="tl-date">2024-01 → 2024-06(约 5 个月)</div>
        <div class="tl-body"><b style="color:#4f8cff">阶段 1 · 双轨奠基</b> — 两条主线几乎同时开掘:① <b>custom allreduce</b>(<code>#2192</code>,one/two-shot 内核,专攻小 batch TP 的延迟);② <b>pynccl</b>(<code>#3625</code> 去 cupy、<code>#4591</code> 重构),用 ctypes 直连 <code>libnccl</code>,绕开 PyTorch 进程组的 stream/图捕获约束。<code>#3950</code> 把散落的 <code>parallel_utils</code> 收拢为 <code>vllm/distributed</code> 顶层模块,<code>#4248</code> 用 CPU/gloo 组做初始化避免提前创建 CUDA 上下文——通信正式成为 vLLM 的一等公民。</div>
      </div>
      <div class="tl-item v2 reveal">
        <div class="tl-date">2024-05 → 2024-12(约 8 个月)</div>
        <div class="tl-body"><b style="color:#34d399">阶段 2 · 多组化与图捕获</b> — 服务 EPLB / DP attention 的前夜:多 TP 组(<code>#4512</code> / <code>#4754</code>)、同节点检测(<code>#5369</code>)、PP&gt;1 下的 custom AR(<code>#6117</code>);集合通信注册为 custom op(<code>#8526</code> → <code>#9061</code> → <code>#10121</code>)打通 torch.compile;pynccl 补齐 all_gather / reduce_scatter(<code>#9432</code>)与 broadcast(<code>#10843</code>);<code>#10502</code> StatelessProcessGroup 让「一套 NCCL 组既能算也能传 KV」成为分离式部署的起点。</div>
      </div>
      <div class="tl-item v3 reveal">
        <div class="tl-date">2025-01 → 2025-12(约 12 个月)</div>
        <div class="tl-body"><b style="color:#a78bfa">阶段 3 · V1 与生态爆发</b> — V1 引擎 overlap 调度要求通信原语「无隐式同步」:<code>#11744</code>/<code>#11749</code> 删掉 pynccl 冗余 stream 与 change_state,<code>#29207</code> 保证图捕获/回放同流。生态侧,DP 通信面(<code>#13591</code>)、DeepEP(<code>#18434</code>)、P2P NCCL xPyD(<code>#18242</code>)相继落地;8-9 月是密度峰值:torch symm mem AR(<code>#20759</code> → 默认开启 <code>#24111</code>)与 NCCL symmetric memory(<code>#24532</code>)两周内接连合入,「对称内存」成为 TP 通信新默认。</div>
      </div>
      <div class="tl-item v4 reveal">
        <div class="tl-date">2026-01 → 2026-11(约 11 个月)</div>
        <div class="tl-body"><b style="color:#f87171">阶段 4 · 新硬件与新场景</b> — 三条战线并进:① <b>硬件代际</b>——MNNVL fabric 检测(<code>#33540</code>)、B300/GB300 调优(<code>#37756</code>)、Rubin NVLink AR(<code>#49647</code>)、低 SM multimem reduce-scatter(<code>#55072</code>);② <b>规模与容错</b>——弹性 EP(<code>#34861</code>)、容错 EP 缩容重建(<code>#46370</code>)、NCCL symm 扩展 AG/RS(<code>#46703</code>);③ <b>新负载</b>——RL 原生权重同步(<code>#31943</code> 起 8 连发)、sleep 模式显存治理(<code>#51485</code>)与批不变模式(<code>#58623</code>)。2026 年通信 commit 数(184)超过 2024+2025 之和。</div>
      </div>
    </div>
    <h3 class="subh">里程碑 PR 速查表</h3>
    <table class="tbl reveal">
      <tr><th>PR</th><th>日期</th><th>一句话价值</th></tr>
      <tr><td><code>#2221</code></td><td>2024-01-04</td><td>控制面通信从 Ray 改为 NCCL broadcast,消除序列化开销</td></tr>
      <tr><td><code>#2192</code></td><td>2024-01-28</td><td>自研 one/two-shot custom allreduce 内核(1,453 行),小 batch TP 延迟杀手锏</td></tr>
      <tr><td><code>#3625</code></td><td>2024-03-27</td><td>去除 cupy 依赖,ctypes 手写 <code>pynccl.py</code>(258 行)直连 libnccl</td></tr>
      <tr><td><code>#3950</code></td><td>2024-04-10</td><td><code>parallel_utils</code> 迁入 <code>vllm/distributed</code>,分布式模块定型</td></tr>
      <tr><td><code>#4988</code></td><td>2024-05-23</td><td>PyNCCL 组内 send/recv,支撑 PP 点对点通信</td></tr>
      <tr><td><code>#8526</code> / <code>#10121</code></td><td>2024-09 / 11</td><td>集合通信注册为 custom op 并与 torch.compile 端到端打通</td></tr>
      <tr><td><code>#9432</code> / <code>#10843</code></td><td>2024-11 / 12</td><td>pynccl 补齐 all_gather / reduce_scatter / broadcast 全家桶</td></tr>
      <tr><td><code>#10502</code></td><td>2024-12-01</td><td>StatelessProcessGroup:分离式 prefill(P/D)的 KV 传输基石</td></tr>
      <tr><td><code>#11744</code> / <code>#11749</code></td><td>2025-01-05 / 06</td><td>V1 精简 pynccl 冗余 stream 与状态机,适配 overlap 调度与 CUDA Graph</td></tr>
      <tr><td><code>#13591</code></td><td>2025-02-22</td><td>搭建数据并行(DP)通信面,DP attention 的前置工程</td></tr>
      <tr><td><code>#18434</code></td><td>2025-06-03</td><td>DeepEP dispatch / combine 内核集成,EP MoE 通信成型</td></tr>
      <tr><td><code>#18242</code></td><td>2025-06-18</td><td>基于 P2P NCCL 的原生 xPyD KV 传输(P2pNcclConnector)</td></tr>
      <tr><td><code>#20691</code> / <code>#21069</code></td><td>2025-07</td><td>SM100 FlashInfer 融合 allreduce+RMSNorm(+Quant),通信与计算重叠</td></tr>
      <tr><td><code>#20759</code> / <code>#24111</code> / <code>#24532</code></td><td>2025-08 / 09</td><td>对称内存三连:torch symm mem AR 落地、默认开启、NCCL 原生 symmetric memory</td></tr>
      <tr><td><code>#31943</code></td><td>2026-02-05</td><td>RL 原生权重同步 API(NCCL M2N),训推一体主线开端</td></tr>
      <tr><td><code>#46703</code></td><td>2026-06-30</td><td>NCCL symmetric memory 从 allreduce 扩展到 AllGather / ReduceScatter</td></tr>
      <tr><td><code>#47219</code> / <code>#48064</code></td><td>2026-06 / 07</td><td>单机 FlashInfer AR 默认走 MNNVL,并叠加 RMS 量化融合</td></tr>
      <tr><td><code>#53311</code></td><td>2026-08-26</td><td>MoE all2all 默认启用 fi_one_sided 单边通信</td></tr>
      <tr><td><code>#55072</code></td><td>2026-09-24</td><td>SM100/103 低 SM 占用 multimem reduce-scatter,decode 尾延迟优化</td></tr>
      <tr><td><code>#46370</code></td><td>2026-10-31</td><td>容错 EP:scale-down 重建(基线 HEAD 前一天的最新合入)</td></tr>
    </table>
  </section>

  <!-- ============ 4 全景图(核心交付物) ============ -->
  <section id="s4">
    <h2 class="sec"><span class="num">4</span>全景图:特性支持 / 问题解决(核心交付物)</h2>
    <p class="lede">125 个关键 PR 按 11 条主题泳道铺在时间轴上,配合两个循环动画与悬停详情——「哪些能力何时进入主线、问题在何处被修复」一目了然。</p>
    <p>下图为「PR 合入历史全景图」:X 轴为时间(2023-04 → 2026-11,按季度刻度),Y 轴为 11 条主题泳道(在建议的 10 条之上,将 2026 年爆发式增长的 RL 权重同步单列),泳道内每个圆点 = 一个关键 PR(圆点下方/上方标注 PR 编号)。<b>鼠标悬停任意节点</b>可查看日期与完整标题;图内持续运行两个循环动画:青色<b>扫描线</b>从 2023 推进到 2026,沿途节点依次点亮;<b>泳道轮播</b>则周期性高亮一条泳道,并在图下方同步显示该泳道简介(鼠标移入图内时轮播暂停,便于细看)。</p>
    <div class="figure reveal">
      <div class="klabel">ANIMATED · 时间轴扫描线 + 泳道轮播(移入暂停)· 悬停节点查看 PR 详情</div>
      <div class="panoWrap" id="panoWrap">
        <svg id="panoSvg" viewBox="0 0 1240 736" xmlns="http://www.w3.org/2000/svg" role="img"
             aria-label="vLLM NCCL 与分布式通信 PR 合入历史全景图"></svg>
        <div id="tt"></div>
      </div>
      <div class="laneCap" id="laneCap"></div>
      <div class="legend">
        <span><span class="sw" style="background:#4f8cff"></span>基础/初始化</span>
        <span><span class="sw" style="background:#22d3ee"></span>TP/PP 集合通信</span>
        <span><span class="sw" style="background:#fbbf24"></span>Custom AllReduce</span>
        <span><span class="sw" style="background:#a78bfa"></span>PyNccl/图捕获</span>
        <span><span class="sw" style="background:#34d399"></span>对称内存/NVLS</span>
        <span><span class="sw" style="background:#f87171"></span>融合通信</span>
        <span><span class="sw" style="background:#7fb1ff"></span>EP/MoE</span>
        <span><span class="sw" style="background:#c5a8ff"></span>KV 传输</span>
        <span><span class="sw" style="background:#6ee7a0"></span>RL 权重同步</span>
        <span><span class="sw" style="background:#fcd34d"></span>平台扩展</span>
        <span><span class="sw" style="background:#fca5a5"></span>问题修复</span>
        <span style="margin-left:auto">节点共 125 个 · 由 323 条相关 commit 人工策展 · 悬停查看详情</span>
      </div>
      <div class="cap">图 14-1 · PR 合入历史全景:11 条主题泳道 × 125 个节点(2023-04 → 2026-11,季度刻度)</div>
    </div>
    <div class="note good reveal">
      <b>读图要点:</b>① 2023 年的空白与 2025H2-2026 的密集形成鲜明对比——通信从「无 commits」到「每两周一个能力」;② 「对称内存/NVLS」泳道 2025-08 之后才出现,但两年内节点数追平了运行三年的 custom AR 泳道;③ 「问题修复」泳道与特性泳道几乎平行生长——每个新能力落地后 3-6 个月都会迎来一波修复潮(详见第 6 章)。
    </div>
  </section>

  <!-- ============ 5 主题泳道深度解读 ============ -->
  <section id="s5">
    <h2 class="sec"><span class="num">5</span>主题泳道深度解读</h2>
    <p class="lede">10 条特性泳道逐条精读(第 11 条「问题修复」泳道的编年详见第 6 章);卡片左侧色条与全景图泳道颜色一一对应。</p>
    <div class="grid c2">
      <div class="card lane reveal" style="--pc:#4f8cff">
        <h3><span class="ico">🧭</span>5.1 分布式基础与初始化<span class="badge open">10 节点</span></h3>
        <p>这条泳道回答「通信发生之前发生了什么」。<code>#2221</code>(2024-01)把控制面从 Ray 换成 NCCL broadcast,动机是 Ray 的序列化开销;<code>#3625</code> 砍掉 cupy 后,<code>pynccl_utils.py</code> 负责在 <code>worker.py</code> 里完成设备组的惰性建立。<code>#4248</code> 是一条容易被忽略的关键决策:用 CPU/gloo 进程组初始化 pynccl,避免 fork 后重复创建 CUDA 上下文——这个坑后来在 ROCm CI 上反复出现(<code>#29119</code>、<code>#32891</code>)。<code>#5399</code> 引入 <code>shm_broadcast</code>,把元数据广播从 TCP 搬进共享内存,并于 2026 年进化为 <code>shm_tensor_arena</code>(<code>#51207</code>)与零拷贝 pickle(<code>#48442</code>)。<code>#19641</code>(2025-06)补上了「NCCL 不可用回退 gloo」的韧性路径。</p>
      </div>
      <div class="card lane reveal d1" style="--pc:#22d3ee">
        <h3><span class="ico">🔗</span>5.2 TP/PP 集合通信<span class="badge deepep">10 节点</span></h3>
        <p>2024 年 5 月的「多 TP 组三部曲」(<code>#4512</code> → <code>#4566</code> → <code>#4754</code>)是为 EPLB 与专家并行预留的通信分组能力;6 月 <code>#5369</code> 引入同节点检测,决定 allreduce 走 IPC 还是跨网。之后泳道进入「补原语」阶段:AG/RS(<code>#9432</code>)、broadcast(<code>#10843</code>)、变长版本 all-gatherv / reducescatterv(<code>#20154</code>,为 MoE 的变长 token 分布而设)。2025-02 <code>#13591</code> 搭起 DP 通信面,9 月 <code>#24105</code> 把 <code>num_tokens_across_dp</code> 元数据从 gloo 切到 NCCL——小消息也要走 GPU 以免 CPU 集合通信阻塞 async scheduler(<code>#32197</code> 最终放行)。</p>
      </div>
      <div class="card lane reveal" style="--pc:#fbbf24">
        <h3><span class="ico">⚡</span>5.3 Custom AllReduce<span class="badge nccl">11 节点</span></h3>
        <p><code>#2192</code> 的设计(见系列第 13 篇)在单机 NVLink 全互联拓扑下用 one-shot / two-shot 算子把小消息 AR 延迟压到 NCCL 之下;随后一年的工作全是「让它活着」:拓扑探测修复(<code>#3974</code>)、PyTorch 2.5 兼容(<code>#9815</code>)、IPC buffer 重构(<code>#10030</code>)。2024-09 起的 custom op 化(<code>#8526</code> → <code>#10121</code>)让它与 torch.compile 共存。2025-04 <code>#14125</code> 完成向 ROCm(AITER)的移植;2026 年泳道重心转向「门控与合规」:跨节点 MNNVL custom AR 按组能力门控(<code>#53253</code>)、批不变模式下重新启用(<code>#58623</code>)。</p>
      </div>
      <div class="card lane reveal d1" style="--pc:#a78bfa">
        <h3><span class="ico">🎬</span>5.4 PyNccl 封装与图捕获<span class="badge hccl">11 节点</span></h3>
        <p>pynccl 的价值在于<b>把 NCCL 调用从 PyTorch 进程组语义中解放出来</b>:显式 stream、可注册 buffer、可被 CUDA Graph 捕获。<code>#3805</code> 曾短暂用 <code>vllm-nccl</code> PyPI 包分发定制 NCCL,7 周后 <code>#5091</code> 即移除回归官方版本——一次务实的回退。<code>#4988</code> 为 PyNCCL 组增加 send/recv,使 PP 的点对点通信与 TP 的组通信共用同一套封装。V1 时代,<code>#11744</code>/<code>#11749</code> 删除冗余 stream 与 change_state,<code>#29207</code> 修掉「捕获与回放不同 stream」导致的图回放 hang。2026-10 <code>#59898</code> 让报错附带 NCCL last error,排查 IB / 版本问题的第一手信息。</p>
      </div>
      <div class="card lane reveal" style="--pc:#34d399">
        <h3><span class="ico">⚖️</span>5.5 对称内存与 NVLS<span class="badge merged">10 节点</span></h3>
        <p>2025-08-22 <code>#20759</code> 引入 PyTorch <code>torch.distributed._symmetric_memory</code> AR,20 天后 <code>#24111</code> 直接设为默认——替代 custom AR 成为小消息主力;次月 <code>#24532</code> 又叠加 NCCL 2.27+ 原生 symmetric memory 路径,三者(custom AR / torch symm / NCCL symm)按消息大小与拓扑自动选择(阈值调优见 <code>#33839</code>)。2026 年泳道跟随硬件代际走:GB 系列 fabric 检测(<code>#33540</code>)、B300/GB300 调优(<code>#37756</code>)、Rubin SM107(<code>#49647</code>)、multimem 指令的 reduce-scatter(<code>#55072</code>),以及把 symm RS 的 staging 拷贝干掉(<code>#49194</code>)。</p>
      </div>
      <div class="card lane reveal d1" style="--pc:#f87171">
        <h3><span class="ico">🔥</span>5.6 融合通信:FlashInfer AR / quick AR<span class="badge closed">14 节点</span></h3>
        <p>融合的收益来自「通信与计算重叠」:SM100 上 FlashInfer trtllm 融合 AR+RMSNorm(<code>#20691</code>)先行,随后升级为 AR+RMSNorm+Quant 三融合(<code>#21069</code>),阈值可配(<code>#23639</code>)。ROCm 侧的对应物是 QuickReduce(<code>#19744</code>,csrc 内核),2026 年继续加码 INT3/INT4 量化(<code>#45666</code> / <code>#59478</code>)。MNNVL 时代,单机默认走 NVLink 域(<code>#47219</code>)并叠加 RMS 量化融合(<code>#48064</code>);SM103 上的后端选择调优(<code>#53318</code>)与多机融合修复(<code>#38136</code>)说明该路径已成为生产主线。</p>
      </div>
      <div class="card lane reveal" style="--pc:#7fb1ff">
        <h3><span class="ico">🌐</span>5.7 EP 与 MoE 通信<span class="badge open">14 节点</span></h3>
        <p><code>#18434</code>(2025-06)集成 DeepEP 的 dispatch/combine,使 EP MoE 的 all-to-all 有了低延迟实现;配套的安装指引(<code>#17964</code>)与 pplx 初始化模块化(<code>#18200</code>)是铺路工程。9 月 <code>#21003</code> 引入 FlashInfer 的 MNNVL all2allv,开启「单边通信」路线,2026-08 <code>#53311</code> 将 fi_one_sided 设为默认,随后支持 fp8 combine(<code>#57995</code>)。与此并行,NCCL all2all 后端与 EPLB 的约束被逐一澄清(<code>#35212</code> / <code>#44978</code>)。2026 年的增量是「弹性与容错」:Elastic EP 里程碑 2(<code>#34861</code>)、CUDA 图复用(<code>#54985</code>)、scale-down 容错重建(<code>#46370</code>),以及 MoonEP 均衡后端(<code>#52101</code>)——all-to-all 从「一次建好」走向「运行时可变」。</p>
      </div>
      <div class="card lane reveal d1" style="--pc:#c5a8ff">
        <h3><span class="ico">🚚</span>5.8 KV 传输通信生态<span class="badge hccl">11 节点</span></h3>
        <p>P/D 分离部署需要把 KV 块从 prefill 实例搬到 decode 实例。<code>#10502</code> 用 StatelessProcessGroup(手搓的跨进程组协调器)打通第一条链路;<code>#10884</code> 接入 Mooncake,<code>#11481</code> 建立 connector 注册表,生态开始多引擎并存(NIXL / LMCache / Mooncake)。2025-06 <code>#18242</code> 上线 P2pNcclConnector(xPyD):直接用 NCCL 点对点传 KV,示例与性能增强接连合入(<code>#20246</code> / <code>#20906</code> / <code>#23536</code>)。2026-06 <code>#44854</code> 将其移除——由更通用的 MoRI 连接器接棒(<code>#39565</code> 对齐消息格式),体现了「专用方案 → 平台化方案」的收敛规律。</p>
      </div>
      <div class="card lane reveal" style="--pc:#6ee7a0">
        <h3><span class="ico">🏋️</span>5.9 RL 权重同步<span class="badge merged">8 节点</span></h3>
        <p>RL 训推一体要求把训练侧新权重持续推给多个推理副本(vLLM M2N)。<code>#31943</code>(2026-02)定义原生 API:NCCL 广播 + 打包传输;随后一年里能力滚雪球——稀疏原地更新(<code>#40096</code>)、引擎重构(<code>#44353</code>)、有状态 Trainer Send(<code>#50902</code>)、预共享 <code>ncclUniqueId</code> rendezvous(<code>#53784</code>)、分片感知 M2N(<code>#51520</code>)、共享 rendezvous 初始化(<code>#63460</code>),以及更新后释放缓存显存(<code>#64691</code>)。2026 年该主题相关 commit 达 33 条,是增速最快的通信场景。</p>
      </div>
      <div class="card lane reveal d1" style="--pc:#fcd34d">
        <h3><span class="ico">🖥️</span>5.10 平台扩展:ROCm / XPU / CPU<span class="badge nccl">11 节点</span></h3>
        <p>通信是平台差异最先暴露的地方:AMD 侧从「不用 cupy NCCL」(<code>#2855</code>)到 RCCL 路径修复(<code>#3699</code>),再到 2025-04 custom AR 的 ROCm 移植(<code>#14125</code>,见 5.3)与 fp8_e4m3fnuz dtype(<code>#33713</code>);Intel XPU 侧以 <code>XpuCommunicator</code>(<code>#10144</code>)起步,2026 年 custom op 化(<code>#41354</code>)并对齐 oneCCL 预热行为(<code>#52389</code>)。CI 治理同样算贡献:<code>TORCH_NCCL_BLOCKING_WAIT</code> 的设与撤(<code>#31259</code> → <code>#41840</code>)记录了与 ROCm 7.2 修复同步的排查过程。</p>
      </div>
    </div>
  </section>

  <!-- ============ 6 问题修复史 ============ -->
  <section id="s6">
    <h2 class="sec"><span class="num">6</span>问题修复史:典型 bug 编年</h2>
    <p class="lede">通信 bug 的特殊之处在于症状远离根因——按挂起/死锁、正确性、内存、版本兼容四类整理 16 个代表性修复。</p>
    <p>通信 bug 的特殊之处在于症状远离根因:一个 stream 误用可能在十万步之后才表现为 hang,一个缓冲复用错误只在高并发重复请求时吐乱码。下表按四类整理 16 个代表性修复。</p>
    <table class="tbl reveal">
      <tr><th>类别</th><th>PR</th><th>日期</th><th>问题与修复要点</th></tr>
      <tr><td rowspan="4" style="color:#f87171;font-weight:700">挂起 / 死锁</td>
          <td><code>#13987</code></td><td>2025-02-28</td><td>P/D SimpleBuffer(nccl)在 inflight batching 下挂起:decode 节点打补丁避开</td></tr>
      <tr><td><code>#29207</code></td><td>2025-12-25</td><td>NCCL 图捕获与回放使用不同 stream 导致回放 hang:统一为同一 stream</td></tr>
      <tr><td><code>#37024</code></td><td>2026-03-18</td><td>pause/resume 与 <code>collective_rpc</code> 组合死锁:修复暂停语义下的集合调用时序</td></tr>
      <tr><td><code>#56610</code></td><td>2026-09-12</td><td>弹性 EP 反复扩缩容死锁(ROCm):修复组生命周期</td></tr>
      <tr><td rowspan="4" style="color:#fbbf24;font-weight:700">正确性</td>
          <td><code>#8558</code></td><td>2024-09-24</td><td>custom AR 同步不安全可能读到半写数据:加固栅栏</td></tr>
      <tr><td><code>#20263</code> / <code>#23403</code></td><td>2025-07 / 08</td><td>P2pNcclConnector 偶发乱码 / 重复请求异常输出:修复跨流复用接收缓冲</td></tr>
      <tr><td><code>#23648</code></td><td>2025-08-27</td><td>pynccl reduce_scatter 输出错乱:修复封装参数</td></tr>
      <tr><td><code>#62555</code> / <code>#63833</code></td><td>2026-10</td><td>packed NCCL 接收缓冲跨流复用(及 ROCm per-slot 事件等待)修复</td></tr>
      <tr><td rowspan="4" style="color:#34d399;font-weight:700">内存</td>
          <td><code>#2151</code></td><td>2023-12-17</td><td>史上第一条:all-reduce 显存占用修复</td></tr>
      <tr><td><code>#25359</code></td><td>2025-09-23</td><td>多副本 OOM:统一 NCCL 显存记账口径</td></tr>
      <tr><td><code>#39846</code></td><td>2026-05-11</td><td>NCCL destroy 留下孤儿进程:清理路径修复</td></tr>
      <tr><td><code>#51485</code> / <code>#59360</code></td><td>2026-09 / 10</td><td>sleep 模式释放 NCCL communicator 与 FlashInfer AR workspace 显存</td></tr>
      <tr><td rowspan="4" style="color:#22d3ee;font-weight:700">版本 / 平台兼容</td>
          <td><code>#9815</code></td><td>2024-10-29</td><td>PyTorch 2.5 下 custom AR 失效:适配 IPC API 变化</td></tr>
      <tr><td><code>#53008</code></td><td>2026-08-28</td><td>NCCL ≥ 2.31 <code>ncclCommQueryProperties</code> 堆溢出:防御性探测</td></tr>
      <tr><td><code>#58179</code></td><td>2026-09-22</td><td>批不变模式误禁用非 AllReduce 集合通信(NCCL ≥ 2.31 行为差异)</td></tr>
      <tr><td><code>#25605</code> / <code>#33713</code></td><td>2025-09 / 2026-02</td><td>ROCm:libnccl 符号缺失与 fp8_e4m3fnuz dtype 派发</td></tr>
    </table>
    <div class="note warn reveal">
      <b>规律:</b>修复潮滞后特性潮约一个季度,且集中在三处「缝合面」——CUDA Graph 与 NCCL stream 的缝合(<code>#29207</code>、<code>#62555</code>)、跨流生命周期的缝合(<code>#23403</code>、<code>#63833</code>)、与上游版本(PT 2.5 / NCCL 2.31 / ROCm 7.2)的缝合。这三处也是读者排障时的首选检查点。
    </div>
  </section>

  <!-- ============ 7 动画演示 ============ -->
  <section id="s7">
    <h2 class="sec"><span class="num">7</span>动画演示</h2>
    <p class="lede">全文档共三个自动循环动画,全部以纯 CSS animation / 原生 JS 实现,无任何外部依赖。</p>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📡</span>动画 ① · 时间轴扫描线<span class="badge nccl">位于第 4 章全景图</span></h3>
        <p><b>扫描线从 2023-04 推进到 2026-11。</b>青色扫描线以约 13 秒扫完时间轴,途经的 PR 节点依次点亮并发光,到达终点后保持 2.5 秒再整体熄灭重来——直观复现「通信能力加速合入」的时间分布。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🎠</span>动画 ② · 泳道轮播高亮<span class="badge nccl">位于第 4 章全景图下方</span></h3>
        <p><b>11 条泳道依次高亮并显示简介。</b>每 3.2 秒切换一条泳道:泳道背景着色、左侧名称加亮,同时图下方的简介卡片展示该泳道定位与代表 PR。鼠标移入全景图时轮播暂停。</p>
      </div>
    </div>
    <div class="figure reveal">
      <div class="klabel">ANIMATED · 动画 ③ · 按年相关 commit 数柱状图生长(周期 7.5s,依次错峰)</div>
      <div class="figsub">核心口径 A:22 组检索词并集去重后的年度 commit 数(2026 为 1-11 月)</div>
      <div class="bars">
        <div class="bcol" style="--bc:#8ea0c2;--bd:0s">
          <div class="bval">1</div><div class="pct">0.3%</div><div class="bar" style="--h:4px"></div>
        </div>
        <div class="bcol" style="--bc:#4f8cff;--bd:.35s">
          <div class="bval">37</div><div class="pct">11.5%</div><div class="bar" style="--h:50px"></div>
        </div>
        <div class="bcol" style="--bc:#22d3ee;--bd:.7s">
          <div class="bval">101</div><div class="pct">31.3%</div><div class="bar" style="--h:134px"></div>
        </div>
        <div class="bcol" style="--bc:#34d399;--bd:1.05s">
          <div class="bval">184</div><div class="pct">57.0%</div><div class="bar" style="--h:244px"></div>
        </div>
      </div>
      <div class="byr-row">
        <div class="byr">2023</div>
        <div class="byr">2024</div>
        <div class="byr">2025</div>
        <div class="byr">2026</div>
      </div>
      <div class="legend" style="margin-top:14px">
        <span>柱高与 commit 数成正比 · 动画周期 7.5s,依次错峰生长 · 2026(11 个月)已是 2024 全年的 5 倍</span>
      </div>
      <div class="cap">图 14-2 · 通信相关 commit 年度分布(核心口径 A,去重):1 → 37 → 101 → 184,逐年加速</div>
    </div>
  </section>

  <!-- ============ 8 小结与趋势研判 ============ -->
  <section id="s8">
    <h2 class="sec"><span class="num">8</span>小结与趋势研判</h2>
    <p class="lede">三次跃迁:从依赖到资产、从单车道到立交桥、从性能到运营。</p>
    <p>纵观 323 个 commit,NCCL 及分布式通信在 vLLM 中的角色完成了三次跃迁:</p>
    <ul class="feat reveal">
      <li><b>从依赖到资产(2024)</b>:torch.distributed + Ray 的「借来的」通信,被 custom AR 内核与 ctypes 版 pynccl 替换为可挖潜、可图捕获的自有资产;代价是一整年的兼容性维护(PT 2.5、IPC、多 TP 组)。</li>
      <li><b>从单车道到立交桥(2025)</b>:TP allreduce 不再是唯一流量——DeepEP 的 all-to-all、P/D 的 KV 传输、DP 的元数据同步各自成道;对称内存两个月内三次迭代并成为默认,说明「内核旁路 + 用户态窗口注册」路线在延迟上已明确胜出。</li>
      <li><b>从性能到运营(2026)</b>:NVLS/MNNVL/multimem 跟随硬件节奏,弹性 EP / 容错 EP / sleep 显存治理 / 批不变把通信纳入 SRE 与合规视野;RL 权重同步(33 条 commit)则把 vLLM 从「推理引擎」的通信边界推向「训推一体平台」。</li>
    </ul>
    <p class="reveal"><b>趋势研判:</b>① 泳道还会继续增多——KV 传输与 RL 权重同步正在融合为「跨实例数据面」,MoRI/Mooncake 类平台化连接器将取代专用 connector(P2pNcclConnector 的移除是信号);② NCCL 版本耦合加深(2.27 symm mem、2.30.7 DeepEPv2、2.31 兼容修复),「容器内 NCCL 版本治理」会成为部署文档的一等章节(<code>#45321</code> / <code>#60449</code>);③ 修复史指向的三个缝合面(CUDA Graph、跨流生命周期、上游版本)不会消失,只会随新硬件(SM107/Rubin)与新负载(容错 EP)平移——下一个季度的修复潮,大概率出现在 2026H2 合入的 MNNVL allreduce 与弹性 EP 附近。</p>
    <div class="note reveal">
      与本系列第 13 篇(NCCL 使用机制,静态代码视角)对照阅读:机制篇回答「它怎么工作」,本篇回答「它为何长成这样」。下一篇(15 · 跨 GPU 通信)将把镜头拉远到 TP/PP/EP/DP 全并行形态。
    </div>
    <div class="note good reveal">
      <b>数据与文档口径:</b>基线 main @ <code>5d55ef1590</code>(2026-11-01,共 24,299 commits);数据来源:本地 git(grep 组合检索 + --follow 文件锚定),核心口径 323 条相关 commit,全景图 125 个 PR 节点 / 11 条泳道。本文档为自包含离线 HTML:无 CDN、无外部字体、无网络请求;三个循环动画均为纯 CSS / 原生 JS 实现。
    </div>
  </section>

  <div class="pgnav">
    <span>vLLM 深度解析系列 · 第 14 篇 · 由 ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/vllm/13-nccl-usage/">← 上一篇:⑬ NCCL 使用场景</a> · <a href="/docs/inference-engines/vllm/">返回总览</a> · <a href="/docs/inference-engines/vllm/15-cross-gpu-comm/">下一篇:⑮ 跨卡通信 →</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>
<script>
(function(){
"use strict";
/* ================= 全景图数据:11 泳道 × 125 节点 ================= */
var LANES=[
{n:"分布式基础与初始化",c:"#4f8cff",
 d:"进程组/初始化/控制面广播是所有通信的前提:从 Ray 控制面到 NCCL 广播(#2221),从 cupy 到 ctypes 版 pynccl(#3625),再到 shm_broadcast 与 gloo 兜底,建组成为一等公民。代表:#2221、#3625、#3950。",
 prs:[[2221,"2024-01-04","Use NCCL instead of ray for control-plane communication(控制面改走 NCCL 广播,消除序列化开销)"],
     [3625,"2024-03-27","[Core] remove cupy dependency(去 cupy,ctypes 手写 pynccl.py 直连 libnccl)"],
     [3950,"2024-04-10","[Core][Refactor] move parallel_utils into vllm/distributed(分布式模块定型)"],
     [4248,"2024-04-23","[Core][Distributed] use cpu/gloo to initialize pynccl(CPU/gloo 组初始化,避免提前建 CUDA 上下文)"],
     [5399,"2024-06-20","[Core][Distributed] add shm broadcast(共享内存广播元数据)"],
     [6183,"2024-07-09","[core][distributed] zmq fallback for broadcasting large objects(大对象广播兜底)"],
     [10216,"2024-11-11","[core][distributed] add stateless process group(无状态进程组)"],
     [19641,"2025-06-17","[Fix] Fall back to Gloo when NCCL backend is unavailable(NCCL 不可用回退 gloo)"],
     [27197,"2025-10-21","[Chore] Separate out NCCL utilities from vllm.utils(NCCL 工具独立成模块)"],
     [45159,"2026-07-07","fix(distributed): propagate distributed_timeout_seconds to NCCL device groups(超时传播)"]]},
{n:"TP/PP 集合通信",c:"#22d3ee",
 d:"TP/PP/DP 的集合通信面:多 TP 组、同节点检测、PP>1 下的 custom AR、pynccl 的 AG/RS/broadcast 封装,以及 DP 元数据从 gloo 迁往 NCCL。代表:#4512、#13591、#20154。",
 prs:[[4512,"2024-05-01","[Core][Distributed] enable multiple tp group(多 TP 组)"],
     [4566,"2024-05-02","[Core][Distributed] enable allreduce for multiple tp groups(多组 allreduce)"],
     [5369,"2024-06-11","[Core][Distributed] add same-node detection(同节点检测)"],
     [6117,"2024-07-03","[core][distributed] custom allreduce when pp size > 1(PP>1 启用 custom AR)"],
     [9432,"2024-11-22","[Misc] Add pynccl wrappers for all_gather and reduce_scatter(补 AG/RS 封装)"],
     [10843,"2024-12-02","[core][distributed] add pynccl broadcast(补 broadcast)"],
     [13591,"2025-02-22","[core] set up data parallel communication(搭建 DP 通信面)"],
     [20154,"2025-07-11","Add pynccl all-gatherv and reducescatterv(变长集合通信)"],
     [24105,"2025-09-15","Update num_tokens_across_dp to use nccl instead of gloo(DP 元数据切 NCCL)"],
     [32197,"2026-01-12","[Misc] Allow enabling NCCL for DP sync when async scheduling(异步调度下 DP 同步)"]]},
{n:"Custom AllReduce",c:"#fbbf24",
 d:"自研 custom allreduce(#2192)以 one/two-shot 内核加速小 batch TP,后续完成多 TP 组重构、torch.compile custom op 化与 ROCm 移植,2026 年转向门控与批不变合规。代表:#2192、#10121、#14125。",
 prs:[[2192,"2024-01-28","Implement custom all reduce kernels(自研 one/two-shot AR 内核,1453 行)"],
     [2760,"2024-03-21","[BugFix] Some fixes for custom allreduce kernels(内核修复)"],
     [3974,"2024-04-18","[Bugfix] Fix CustomAllreduce nvlink topology detection(NVLink 拓扑探测修复)"],
     [8526,"2024-09-16","[torch.compile] register allreduce operations as custom ops(注册 custom op)"],
     [9061,"2024-10-04","[torch.compile] improve allreduce registration(注册改进)"],
     [10030,"2024-11-06","[Core][Distributed] Refactor ipc buffer init in CustomAllreduce(IPC buffer 重构)"],
     [10121,"2024-11-26","custom allreduce + torch.compile(与 torch.compile 打通)"],
     [14125,"2025-04-01","[Distributed] Add custom allreduce support for ROCM(ROCm 移植)"],
     [46065,"2026-07-06","[ROCm][AITER] Directly Implement AITER Custom All-reduce in CudaCommunicator(AITER 直连)"],
     [53253,"2026-08-29","[Bugfix][Distributed] Gate cross-node MNNVL custom all-reduce by group capability(按组能力门控)"],
     [58623,"2026-10-01","[Distributed] Enable custom all-reduce under VLLM_BATCH_INVARIANT(批不变启用)"]]},
{n:"PyNccl 封装与图捕获",c:"#a78bfa",
 d:"PyNccl 是对 libnccl 的 ctypes 直连封装,支撑 CUDA Graph 捕获与 V1 overlap 调度;vllm-nccl 包上线又移除,回归官方 NCCL。代表:#3625、#11744、#29207。",
 prs:[[3805,"2024-04-04","[Core] manage nccl via a pypi package & upgrade to pt 2.2.1(vllm-nccl 包)"],
     [3860,"2024-04-04","[Core] improve robustness of pynccl(健壮性)"],
     [4155,"2024-04-17","[Core] nccl integrity check and test(完整性校验)"],
     [4591,"2024-05-09","[Core][Distributed] refactor pynccl(重构)"],
     [4988,"2024-05-23","[Core][1/N] Support send/recv in PyNCCL Groups(组内 send/recv)"],
     [5091,"2024-05-28","[Core][Optimization] remove vllm-nccl(移除专用包,回归官方 NCCL)"],
     [11744,"2025-01-05","[distributed] remove pynccl's redundant stream(V1 去冗余 stream)"],
     [11749,"2025-01-06","[distributed] remove pynccl's redundant change_state(V1 去冗余状态)"],
     [25421,"2025-09-30","[Misc] allow disable pynccl(允许禁用)"],
     [29207,"2025-12-25","use the same stream for cuda graph capture and replay for NCCL(图捕获/回放同流)"],
     [59898,"2026-10-20","[Distributed] Include NCCL's last error in pynccl error messages(报错带 last error)"]]},
{n:"对称内存与 NVLS",c:"#34d399",
 d:"对称内存与 NVLS:torch symm mem AR 默认开启(#24111)、NCCL 原生 symmetric memory(#24532)扩展到 AG/RS,再到 MNNVL/multimem 的 NVLink 域通信与新硬件适配。代表:#20759、#24532、#46703。",
 prs:[[20759,"2025-08-22","[PERF] PyTorch Symmetric Memory All-Reduce(torch symm mem AR)"],
     [24111,"2025-09-11","[Kernels] Enable Torch Symmetric Memory All-Reduce By Default(默认开启)"],
     [24532,"2025-09-23","[core] add nccl symmetric memory for all reduce(NCCL 原生 symm mem AR)"],
     [33540,"2026-02-02","[Feature][Core] Support Fabric detection to adapt the MNNVL protocol for the GB series(GB 系 fabric 检测)"],
     [33839,"2026-02-26","[Kernel][perf] optimize NCCL symm_mem vs custom_AR selection thresholds(后端选择阈值)"],
     [37756,"2026-03-22","[Perf] Add SM 10.3 (B300/GB300) all-reduce communicator tuning(新卡调优)"],
     [46703,"2026-06-30","[PERF] Extend NCCL symmetric memory to AllGather and ReduceScatter(symm 扩展 AG/RS)"],
     [49647,"2026-07-29","[Rubin] Enable NVLink all-reduce paths on SM107(Rubin NVLink AR)"],
     [55072,"2026-09-24","[Perf][Distributed] Add low-SM multimem reduce-scatter for SM100/SM103(低 SM multimem RS)"],
     [49194,"2026-10-06","[Perf][MoE] Eliminate staging from NCCL symmetric reduce-scatter(去 staging 拷贝)"]]},
{n:"融合通信(FI AR/QuickAR)",c:"#f87171",
 d:"融合通信:FlashInfer allreduce+RMSNorm(+Quant)融合、ROCm QuickReduce(INT3/INT4),以及 MNNVL 域内的 AR 融合与后端选择调优。代表:#20691、#21069、#19744。",
 prs:[[19744,"2025-06-27","[Feature] add quick all reduce(ROCm QuickReduce 内核)"],
     [20691,"2025-07-12","Integration SM100 FlashInfer fused allreduce RMSNorm(FI 融合 AR+RMSNorm)"],
     [20918,"2025-07-15","[Misc] Refactor AllReduceFusionPass. Remove parameter(融合 pass 重构)"],
     [21325,"2025-07-22","Fix Flashinfer Allreduce+Norm enable disable calculation(启停计算修复)"],
     [21069,"2025-07-31","Add FlashInfer allreduce RMSNorm Quant fusion(AR+RMSNorm+Quant 三融合)"],
     [23639,"2025-08-26","[Misc] Add override for allreduce fusion thresholds(阈值可覆盖)"],
     [28841,"2025-11-25","[Bugfix] Fix GPT-OSS AR+NORM fusion(GPT-OSS 融合修复)"],
     [34109,"2026-02-25","[Kernel] Refactor FlashInfer allreduce for mnnvl backend(mnnvl 后端重构)"],
     [41675,"2026-05-21","[ROCm] Add QuickReduce min-size override and codec threshold(QuickReduce 阈值)"],
     [45666,"2026-06-25","[ROCM] [Communication] Add INT3 quantization method for quickreduce(INT3 量化)"],
     [47219,"2026-06-30","[Distributed] Default FlashInfer allreduce to mnnvl on single node(单机默认 MNNVL)"],
     [48064,"2026-07-13","[Distributed][Perf] Enable FlashInfer MNNVL allreduce RMS quant fusion(MNNVL 量化融合)"],
     [53318,"2026-08-23","[Perf] Tune FlashInfer all-reduce selection on SM103(SM103 调优)"],
     [59478,"2026-10-26","[ROCm][Perf] Use AITER FlyDSL INT4 QuickReduce when INT4 QuickReduce is selected(FlyDSL INT4)"]]},
{n:"EP 与 MoE 通信",c:"#7fb1ff",
 d:"EP/MoE 通信:DeepEP dispatch/combine(#18434)、FlashInfer 单边 all2all、MoonEP,以及弹性 EP 与容错 EP 的运行时重建。代表:#18434、#53311、#46370。",
 prs:[[17964,"2025-05-12","[misc] add instructions on how to install nvshmem/pplx/deepep(安装指引)"],
     [18200,"2025-05-23","Refactor pplx init logic to make it modular (prepare for deepep)(为 DeepEP 铺路)"],
     [18434,"2025-06-03","[Kernel] DeepEP dispatch-combine kernel integration(DeepEP 集成)"],
     [21311,"2025-07-22","[Misc] DeepEPHighThroughtput - Enable Inductor pass(高吞吐模式)"],
     [21003,"2025-09-24","Support mnnvl all2allv from Flashinfer(FI mnnvl all2allv)"],
     [34861,"2026-02-28","[1/N] Elastic EP Milestone 2(弹性 EP)"],
     [35212,"2026-02-28","[EPLB] Enforce sync eplb for NCCL-based all2all backend(NCCL all2all 约束)"],
     [44978,"2026-06-10","[EPLB] Reject NCCL-based EPLB communicators with async EPLB(异步 EPLB 门控)"],
     [51924,"2026-08-18","[MoE] Refine FlashInfer one-sided All2All integration(单边 All2All)"],
     [53311,"2026-08-26","[MoE] enable all2all fi_one_sided by default(单边默认)"],
     [52101,"2026-09-18","[Distributed][MoonEP] BF16 integration of MoonEP balanced EP backend(MoonEP)"],
     [57991,"2026-09-29","[WideEP] Change DeepEPv2 to auto select hybrid mode by default(DeepEPv2 混合默认)"],
     [57995,"2026-10-03","[Perf][MoE] Support fp8 combine in FlashInfer one-sided MoE all2all(fp8 combine)"],
     [46370,"2026-10-31","[Feature] Initial support for fault tolerant ep using scale-down(容错 EP 缩容)"]]},
{n:"KV 传输通信生态",c:"#c5a8ff",
 d:"P/D 分离的 KV 传输生态:StatelessProcessGroup 起步,Mooncake/NIXL 多引擎并存,P2P NCCL xPyD 一度成为原生方案,后由 MoRI 平台接棒。代表:#10502、#18242、#44854。",
 prs:[[10502,"2024-12-01","[Core] Implement disagg prefill by StatelessProcessGroup(分离式 prefill 起点)"],
     [10884,"2024-12-16","[Core] Support disaggregated prefill with Mooncake Transfer Engine(Mooncake)"],
     [11481,"2024-12-29","[Misc] KV cache transfer connector registry(connector 注册表)"],
     [13987,"2025-02-28","[Bugfix][Disaggregated] patch the inflight batching on the decode node in SimpleConnector to avoid hangs in SimpleBuffer (nccl based)(挂起修复)"],
     [18242,"2025-06-18","[V1][P/D] An native implementation of xPyD based on P2P NCCL(xPyD 原生 P2P NCCL)"],
     [20246,"2025-06-30","[Example] add one-click runnable example for P2P NCCL XpYd(一键示例)"],
     [20906,"2025-07-17","[V1][P/D] Enhance Performance and code readability for P2pNcclConnector(性能增强)"],
     [23536,"2025-08-27","[V1][P/D] P2pNcclConnector supports flashinfer(支持 FlashInfer)"],
     [24151,"2025-09-04","Remove deprecated PyNcclConnector(移除弃用连接器)"],
     [39565,"2026-04-23","[Fix][MoRI] Align MoRI-IO message format with P2pNcclConnector and vllm-router(MoRI 对齐)"],
     [44854,"2026-06-08","[Connector] Remove P2pNcclConnector(移除,由 MoRI 接棒)"]]},
{n:"RL 权重同步",c:"#6ee7a0",
 d:"RL 训推一体的权重同步:NCCL M2N 传输、稀疏原地更新、预共享 ncclUniqueId rendezvous 与有状态 Trainer Send;2026 年 33 条相关 commit,增速最快。代表:#31943、#50902、#51520。",
 prs:[[31943,"2026-02-05","[Feat][RL][1/2] Native Weight Syncing API: NCCL(原生权重同步 API)"],
     [40096,"2026-06-01","[Frontend][Core] Add sparse NCCL weight transfer support for in-place updates(稀疏原地更新)"],
     [44353,"2026-07-01","Weight sync refactor + move sparse nccl engine(同步重构)"],
     [50902,"2026-08-07","[rl] Stateful Trainer Send: NCCL + Sparse NCCL [3/N](有状态发送)"],
     [53784,"2026-09-01","[Distributed] Support pre-shared ncclUniqueId rendezvous for weight transfer(预共享 rendezvous)"],
     [51520,"2026-09-25","[RL] Add sharding-aware NCCL M2N weight transfer(分片感知 M2N)"],
     [63460,"2026-10-25","[Refactor][RL] Share NCCL trainer rendezvous initialization(共享初始化)"],
     [64691,"2026-10-30","[RL] NCCL weight transfer: release cached memory after a weight update(释放缓存)"]]},
{n:"平台扩展(ROCm/XPU)",c:"#fcd34d",
 d:"平台扩展:ROCm(RCCL)、Intel XPU(oneCCL)、CPU 的通信后端适配与 CI 治理;TORCH_NCCL_BLOCKING_WAIT 的设与撤记录了与 ROCm 7.2 同步的排查。代表:#14125、#10144、#33713。",
 prs:[[2855,"2024-02-14","Don't use cupy NCCL for AMD backends(AMD 不走 cupy NCCL)"],
     [3699,"2024-03-29","[ROCm][Bugfix] Fixed several bugs related to rccl path(RCCL 路径修复)"],
     [10144,"2024-11-08","[Bugfix][XPU] Fix xpu tp by introducing XpuCommunicator(XPU 通信器)"],
     [13368,"2025-02-17","[Bugfix] fix xpu communicator(XPU 修复)"],
     [13586,"2025-02-21","[Bugfix][CPU] Fix cpu all-reduce using native pytorch implementation(CPU 原生 AR)"],
     [25605,"2025-09-29","[Bugfix][ROCm] Fixing trying to import non-existent symbols from libnccl.so(符号导入修复)"],
     [31259,"2025-12-24","[ROCm][CI] Set TORCH_NCCL_BLOCKING_WAIT Distributed Tests On ROCm(CI 治理)"],
     [33713,"2026-02-04","[Bugfix][ROCm] Include float8_e4m3fnuz in NCCL Dtype Dispatching(ROCm fp8 dtype)"],
     [41354,"2026-05-19","[XPU] Use custom op collective behavior(XPU custom op 化)"],
     [46851,"2026-06-26","[ROCm][CI] Fix rlhf_nccl.py on ROCm(RLHF NCCL 示例修复)"],
     [52389,"2026-08-24","[Bugfix][XPU] Skip oneCCL warm-up all_reduce when world_size == 1(oneCCL 预热)"]]},
{n:"问题修复",c:"#fca5a5",
 d:"问题修复:挂起/死锁、乱码输出、显存记账 OOM、NCCL 版本兼容(ncclCommQueryProperties 堆溢出)等;修复潮滞后特性潮约一个季度,集中在 CUDA Graph、跨流生命周期与上游版本三个缝合面。代表:#8558、#25359、#53008。",
 prs:[[2151,"2023-12-17","Fix all-reduce memory usage(史上第一条:AR 显存修复)"],
     [4508,"2024-05-01","[Core][Distributed] fix pynccl del error(析构错误)"],
     [8558,"2024-09-24","[Bugfix] Fix potentially unsafe custom allreduce synchronization(不安全同步)"],
     [9815,"2024-10-29","[core][distributed] fix custom allreduce in pytorch 2.5(PT 2.5 兼容)"],
     [20263,"2025-07-01","[Bugfix][V1][P/D] Fix the issue of occasional garbled output for P2pNcclConnector(乱码输出)"],
     [23403,"2025-08-26","[Bugfix][V1][P/D] Fix the issue where repeated requests for the same input produce abnormal outputs(重复请求异常)"],
     [23648,"2025-08-27","fix pynccl reduce_scatter(RS 修复)"],
     [25359,"2025-09-23","[BugFix] Fix OOM in vLLM replicas by ensuring consistent NCCL memory accounting(显存记账 OOM)"],
     [37024,"2026-03-18","[bug] Fix deadlock with pause resume and collective_rpc(暂停死锁)"],
     [39846,"2026-05-11","[BugFix] Prevent orphaned process on NCCL destroy(孤儿进程)"],
     [53008,"2026-08-28","[Bugfix] Fix ncclCommQueryProperties heap overflow with NCCL >= 2.31(堆溢出)"],
     [56610,"2026-09-12","[ROCm][Bugfix] Fix elastic EP scaling deadlock(弹性 EP 死锁)"],
     [58179,"2026-09-22","[Bugfix] batch_invariant: keep non-AllReduce collectives enabled on NCCL >= 2.31(版本行为差异)"],
     [62555,"2026-10-22","[Bugfix][RL] Fix cross-stream reuse of packed NCCL receive buffers(跨流复用)"],
     [63833,"2026-10-26","[Bugfix][ROCm] Wait on per-slot events in packed NCCL consumer(per-slot 事件)"]]}
];

/* ================= 坐标系 ================= */
var NS="http://www.w3.org/2000/svg";
var svg=document.getElementById("panoSvg");
var wrap=document.getElementById("panoWrap");
var tt=document.getElementById("tt");
var X0=152, X1=1206, TOP=66, LH=56, N=LANES.length;
var BOT=TOP+N*LH;                 /* 泳道底 */
var T0=Date.UTC(2013+10,3,1);     /* 2023-04-01 */
var T1=Date.UTC(2026,11,1);       /* 2026-12-01 */
function xOf(ds){var p=ds.split("-");
  return X0+(Date.UTC(+p[0],(+p[1])-1,+p[2])-T0)/(T1-T0)*(X1-X0);}
function el(n,a,p){var e=document.createElementNS(NS,n),k;
  for(k in a){e.setAttribute(k,a[k]);} if(p){p.appendChild(e);} return e;}
function txt(p,x,y,s,cls,a){var e=el("text",a||{x:x,y:y},p);e.textContent=s;
  if(cls){e.setAttribute("class",cls);} return e;}

/* ---- 阶段色带(顶部) ---- */
var ERAS=[[T0,Date.UTC(2024,0,1),"v0 · torch.distributed+Ray","#8ea0c2"],
          [Date.UTC(2024,0,1),Date.UTC(2025,0,1),"奠基 · custom AR + pynccl","#4f8cff"],
          [Date.UTC(2025,0,1),Date.UTC(2026,0,1),"V1 · overlap/图捕获 + 生态爆发","#34d399"],
          [Date.UTC(2026,0,1),T1,"新硬件 · NVLS / EP / RL","#a78bfa"]];
function ex(t){return X0+(t-T0)/(T1-T0)*(X1-X0);}
var i,g;
for(i=0;i<ERAS.length;i++){
  var xA=ex(ERAS[i][0]), xB=ex(ERAS[i][1]);
  el("rect",{x:xA,y:20,width:xB-xA,height:14,fill:ERAS[i][3],rx:2,class:"era"},svg);
  txt(svg,(xA+xB)/2,31,ERAS[i][2],"era-t",{fill:ERAS[i][3]});
  if(i>0){el("line",{x1:xA,y1:36,x2:xA,y2:BOT,stroke:ERAS[i][3],
    "stroke-width":1,"stroke-dasharray":"3 5",opacity:.35},svg);}
}
txt(svg,X0,52,"(阶段色带仅供参考,精确里程碑见第 3 章)",null,
  {fill:"#5a6b92","font-size":"10px"}).setAttribute("text-anchor","start");

/* ---- 季度网格 ---- */
var yq=2023,qm=1;  /* 从 2023Q2 开始 */
var qd=[[2023,3],[2023,6],[2023,9],[2024,0],[2024,3],[2024,6],[2024,9],
        [2025,0],[2025,3],[2025,6],[2025,9],[2026,0],[2026,3],[2026,6],[2026,9]];
var qn=["Q2","Q3","Q4","Q1","Q2","Q3","Q4","Q1","Q2","Q3","Q4","Q1","Q2","Q3","Q4"];
for(i=0;i<qd.length;i++){
  var gx=ex(Date.UTC(qd[i][0],qd[i][1],1));
  el("line",{x1:gx,y1:TOP,x2:gx,y2:BOT,class:"qline"},svg);
  var yr=(qn[i]==="Q1");
  txt(svg,gx,BOT+20,(yr?String(qd[i][0])+" ":"")+qn[i],
    "qtxt"+(yr?" yr":""),{x:gx,y:BOT+20});
}
el("line",{x1:X1,y1:TOP,x2:X1,y2:BOT,class:"qline"},svg);
txt(svg,(X0+X1)/2,BOT+38,"时间(季度刻度,2023-04 → 2026-11)",null,
  {fill:"#8ea0c2","font-size":"11px","text-anchor":"middle"});

/* ---- 泳道与节点 ---- */
var nodes=[];   /* {cx,cy,c,node(lane),lit:false} */
var laneBands=[],laneNames=[];
for(i=0;i<N;i++){
  var L=LANES[i], y0=TOP+i*LH, cy=y0+LH/2;
  laneBands[i]=el("rect",{x:X0,y:y0,width:X1-X0,height:LH,fill:L.c,
    class:"lband",opacity:0,rx:3},svg);
  el("line",{x1:X0,y1:y0,x2:X1,y2:y0,stroke:"#1a2440","stroke-width":1},svg);
  txt(svg,142,cy-6,String(i+1<10?"0":"")+(i+1),"lnum",{x:142,y:cy-6});
  laneNames[i]=txt(svg,142,cy+13,L.n,"lname",{x:142,y:cy+13});
  for(var j=0;j<L.prs.length;j++){
    var pr=L.prs[j], cx=xOf(pr[1]);
    var dy=[-13,14,26][j%3];
    var lab=txt(svg,cx,cy+dy,"#"+pr[0],"nlab",{x:cx,y:cy+dy});
    var c=el("circle",{cx:cx,cy:cy,r:4,class:"nd"},svg);
    c.style.color=L.c;
    var tEl=el("title",{},c);
    tEl.textContent="#"+pr[0]+" · "+pr[1]+" · "+pr[2];
    (function(node,lab,pr,L,idx){
      node.addEventListener("mouseenter",function(e){showTT(e,pr,L,idx);});
      node.addEventListener("mousemove",moveTT);
      node.addEventListener("mouseleave",hideTT);
    })(c,lab,pr,L,i);
    nodes.push({el:c,lab:lab,cx:cx,cy:cy});
  }
}
el("line",{x1:X0,y1:BOT,x2:X1,y2:BOT,stroke:"#263352","stroke-width":1.5},svg);

/* ---- Tooltip ---- */
function showTT(e,pr,L,idx){
  tt.innerHTML="<div><span class='tt-pr'>#"+pr[0]+"</span>"+
    "<span class='tt-date'>"+pr[1]+" · "+L.n+"</span></div>"+
    "<div class='tt-title'>"+pr[2]+"</div>";
  tt.style.display="block"; moveTT(e);
}
function moveTT(e){
  var r=wrap.getBoundingClientRect();
  var x=e.clientX-r.left+14, y=e.clientY-r.top+12;
  if(x+340>r.width){x=e.clientX-r.left-350;}
  if(y+90>r.height){y=Math.max(4,e.clientY-r.top-70);}
  tt.style.left=x+"px"; tt.style.top=y+"px";
}
function hideTT(){tt.style.display="none";}

/* ---- 动画 ①:时间轴扫描线 ---- */
var scan=el("line",{x1:X0,y1:TOP-8,x2:X0,y2:BOT+8,class:"scanline"},svg);
var head=el("circle",{cx:X0,cy:TOP-8,r:3.5,class:"scanhead"},svg);
var SWEEP=13000, HOLD=2600, GAP=800, start=null, running=false;
function raf(ts){
  if(start===null){start=ts;}
  var t=ts-start, x;
  if(t<=SWEEP){
    x=X0+(X1-X0)*(t/SWEEP);
  } else if(t<=SWEEP+HOLD){
    x=X1;
  } else {
    for(var k=0;k<nodes.length;k++){nodes[k].el.classList.remove("lit");
      nodes[k].lab.classList.remove("lit");}
    scan.setAttribute("x1",X0);scan.setAttribute("x2",X0);
    head.setAttribute("cx",X0);
    start=null; running=false;
    setTimeout(function(){if(!running){running=true;requestAnimationFrame(raf);}},GAP);
    return;
  }
  scan.setAttribute("x1",x);scan.setAttribute("x2",x);
  head.setAttribute("cx",x);
  for(var k2=0;k2<nodes.length;k2++){
    var on=nodes[k2].cx<=x;
    nodes[k2].el.classList.toggle("lit",on);
    nodes[k2].lab.classList.toggle("lit",on);
  }
  if(running){requestAnimationFrame(raf);}
}
running=true; requestAnimationFrame(raf);

/* ---- 动画 ②:泳道轮播 ---- */
var cap=document.getElementById("laneCap");
var cur=-1, capTimer=null;
function showLane(i){
  if(cur>=0){laneBands[cur].setAttribute("opacity",0);
    laneNames[cur].setAttribute("class","lname");}
  cur=i;
  laneBands[i].setAttribute("opacity",.10);
  laneNames[i].setAttribute("class","lname on");
  var L=LANES[i], top=[];
  for(var j=0;j<Math.min(3,L.prs.length);j++){top.push("#"+L.prs[j][0]);}
  cap.innerHTML="<span class='lc-no'>LANE "+String(i+1<10?"0":"")+(i+1)+
    " / "+N+"</span><span class='lc-name' style='color:"+L.c+"'>"+L.n+
    "</span><span class='lc-no'>"+L.prs.length+" 个节点 · 代表 "+top.join(" / ")+
    "</span><div class='lc-desc'>"+L.d+"</div>";
}
function startCap(){if(capTimer===null){
  capTimer=setInterval(function(){showLane((cur+1)%N);},3200);}}
function stopCap(){if(capTimer!==null){clearInterval(capTimer);capTimer=null;}}
showLane(0); startCap();
svg.addEventListener("mouseenter",stopCap);
svg.addEventListener("mouseleave",startCap);
})();
</script>
<noscript><style>.fwdoc .reveal{opacity:1;transform:none}</style></noscript>
</div>]]></description></item><item><title>跨卡通信行为与底层通信库</title><link>https://hccl.club/docs/inference-engines/vllm/15-cross-gpu-comm/</link><pubDate>Sat, 07 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/vllm/15-cross-gpu-comm/</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 code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:.88em;word-break:break-all}
.fwdoc b{color:#cfe0ff}
.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 .tag.nccl{border-color:rgba(251,191,36,.4);color:var(--warn);background:rgba(251,191,36,.08)}
.fwdoc .tag.deepep{border-color:rgba(34,211,238,.4);color:var(--accent2);background:rgba(34,211,238,.08)}
.fwdoc .tag.purple{border-color:rgba(167,139,250,.4);color:var(--purple);background:rgba(167,139,250,.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;margin:14px 0}
.fwdoc .grid .card{margin:0}
.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 section>p{font-size:14px;color:var(--text);margin-bottom:12px}
.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 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 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 .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 .cap b{color:var(--accent2)}
.fwdoc .figure .klabel{font-size:11px;color:#5a6b92;letter-spacing:1px;text-transform:uppercase;margin-bottom: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)}}
.fwdoc .legend{display:flex;flex-wrap:wrap;justify-content:center;gap:8px 18px;font-size:12.5px;color:var(--muted);margin-top:10px}
.fwdoc .legend i{display:inline-block;width:14px;height:3px;border-radius:2px;margin-right:5px;vertical-align:middle}
.fwdoc .scene-chip{display:inline-block;border-radius:12px;padding:2px 14px;font-size:13px;font-weight:700;margin-left:8px}
.fwdoc #topo{display:block;margin:0 auto;max-width:100%}
.fwdoc #topo .gpu{fill:#1c2333;stroke:#3d5a80;stroke-width:1.2}
.fwdoc #topo .gpu-txt{fill:#c4d0e8;font:600 13px monospace}
.fwdoc #topo .node-box{fill:#10161f;stroke:var(--border);stroke-width:1.4;rx:10}
.fwdoc #topo .nvlink{stroke:#3d5a80;stroke-width:1.6;fill:none;opacity:.55}
.fwdoc #topo .ib{stroke:#5a4a3d;stroke-width:2;fill:none;stroke-dasharray:7 5;opacity:.5}
.fwdoc #topo .switch{fill:#1b1526;stroke:#6e40c9}
.fwdoc #topo .sw-txt{fill:#d2a8ff;font:600 12px monospace}
.fwdoc #topo .nic{fill:#15242b;stroke:#2f7a85}
.fwdoc #topo .lbl{fill:#8ea0c2;font:11px monospace}
.fwdoc #topo .scn{opacity:0;transition:opacity .7s}
.fwdoc #topo.scene-tp .scn-tp{opacity:1}
.fwdoc #topo.scene-ep .scn-ep{opacity:1}
.fwdoc #topo.scene-kv .scn-kv{opacity:1}
.fwdoc #topo .hot{stroke-width:3;stroke-dasharray:10 7;animation:fw-dashflow 1.1s linear infinite}
@keyframes fw-dashflow{to{stroke-dashoffset:-34}}
.fwdoc #topo .pkt{fill:#4f8cff;opacity:.95}
.fwdoc #topo .pkt.g{fill:#34d399}
.fwdoc #topo .pkt.p{fill:#a78bfa}
.fwdoc #topo .pkt.y{fill:#fbbf24}
.fwdoc .dt-wrap{display:flex;flex-direction:column;gap:0;align-items:center}
.fwdoc .dt-msg{border:2px solid var(--purple);border-radius:10px;padding:8px 20px;font-family:monospace;font-size:14px;background:#1b1526;margin-bottom:6px;text-align:center}
.fwdoc .dt-msg .sz{color:var(--purple);font-weight:700;font-size:16px}
.fwdoc .dt-msg .env{color:var(--muted);font-size:11.5px;display:block}
.fwdoc .dt-line{width:2px;height:14px;background:var(--border)}
.fwdoc .dt-row{display:flex;flex-wrap:wrap;justify-content:center;gap:10px;margin:8px 0}
.fwdoc .gate{border:1px solid var(--border);border-radius:8px;padding:7px 13px;font-size:12.8px;background:#141d33;color:var(--muted);min-width:130px;text-align:center;transition:all .45s;border-left:4px solid var(--border)}
.fwdoc .gate small{display:block;color:#6e7681;font-size:11px}
.fwdoc .gate.pass{border-color:var(--good);color:var(--text);background:#12261a;border-left-color:var(--good);box-shadow:0 0 12px rgba(52,211,153,.35)}
.fwdoc .gate.miss{border-color:#4a3333;color:#7a6f6f;background:#1a1214;border-left-color:var(--bad);opacity:.6}
.fwdoc .gate.hit{border-color:var(--accent2);color:#fff;background:#0e2b30;border-left-color:var(--accent2);box-shadow:0 0 18px rgba(34,211,238,.5);font-weight:700}
.fwdoc .dt-arrow{color:var(--muted);font-size:14px}
.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">「跨卡」在 vLLM 里不是一件事,而是至少 14 类独立行为——要讲清楚「底层实际用了哪个库、哪条硬件路径」,必须把模型层意图、分布式运行时分发、库与硬件落点三层分开。</p>
    <p>「跨卡通信」在 vLLM 里不是一件事,而是至少 <b>14 类独立行为</b>:有的发生在前向计算的热路径上(每个 Transformer 层两次),有的发生在调度协调(每步一次),有的发生在权重热更新或 PD 分离的 KV 搬运上。要讲清楚「底层实际用了哪个库、哪条硬件路径」,必须把三层分开:</p>
    <div class="grid c3">
      <div class="card reveal">
        <h3><span class="ico">🧠</span>模型层行为</h3>
        <p>代码「想做什么」:allreduce / all_gather / reduce_scatter / all-to-all / send-recv / KV 搬运。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🎛️</span>分布式运行时</h3>
        <p><code>GroupCoordinator</code>(<span class="filepath">vllm/distributed/parallel_state.py:427</span>)把请求按 <b>通信组</b>(tp / dp / ep / pcp / dcp / pp / world)与 <b>尺寸门控</b> 分发给某个 device communicator。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🔌</span>库与硬件</h3>
        <p>NCCL(PyNccl 绑定)、自研 Custom AllReduce(C++/CUDA IPC)、torch symmetric memory(NVLS multimem)、DeepEP、NIXL/Mooncake、gloo、ZMQ/共享内存、Ray——分别落在 NVLink/NVSwitch、PCIe P2P、IB/RoCE、主机内存等物理路径上。</p>
      </div>
    </div>
    <div class="note reveal">
      <b>最重要的架构事实是双通道设计</b>:每个 <code>GroupCoordinator</code> 同时持有 <code>device_group</code>(默认 NCCL,传 GPU 张量)与 <code>cpu_group</code>(<b>强制 gloo 后端</b>,见 <span class="filepath">parallel_state.py:511</span> 的 <code>torch.distributed.new_group(ranks, backend="gloo")</code>)。凡是「对象/元数据/控制面」的小消息都走 gloo,凡是「设备张量」才进入 GPU 通信库的分发链。另有一个本机捷径 <code>mq_broadcaster</code>(<span class="filepath">parallel_state.py:570</span>):同节点组直接用 POSIX 共享内存 <code>MessageQueue</code> 广播对象,连 gloo 都省了。
    </div>
    <p class="reveal">本篇的地图是:<a href="#s2">第 2 节</a>按「一个行为一小节」穷举全部跨卡行为并给出代码位置与触发时机;<a href="#s3">第 3 节</a>精读 allreduce 的分发决策(尺寸阈值、拓扑检测);<a href="#s4">第 4 节</a>给每个底层库建档;<a href="#s5">第 5 节</a>是一张覆盖全部行为的「行为 → 库 → 硬件」矩阵表;<a href="#s6">第 6 节</a>用两个自动循环动画演示拓扑流与决策树。</p>
  </section>

  <!-- ================= 2 行为清单 ================= -->
  <section id="s2">
    <h2 class="sec"><span class="num">2</span>通信行为全景清单:每个行为一小节</h2>
    <p class="lede">B1–B14 十四类「数据离开本卡」的行为,逐一给出代码位置、触发时机与硬件路径——从最热的 TP allreduce 到纯 CPU 的拓扑探测。</p>

    <div class="card reveal">
      <h3><span class="ico">⚡</span>B1 · TP 行并行 allreduce(最热路径)</h3>
      <p><code>RowParallelLinear.forward</code>(<span class="filepath">vllm/model_executor/layers/linear.py:1803-1829</span>):每个 TP rank 只算输出矩阵的列分片,随后 <code>if self.reduce_results and self.tp_size &gt; 1: output = tensor_model_parallel_all_reduce(output_parallel)</code>。<code>tensor_model_parallel_all_reduce</code> 只有一行(<span class="filepath">vllm/distributed/communication_op.py:12</span>):<code>get_tp_group().all_reduce(input_)</code>。触发时机:<b>每个 Transformer 层的 MLP 与 attention 输出投影各一次</b>,是单步内出现频次最高的集合通信。变体:Gemma 系列把 allreduce 与 RMSNorm 融合成 <code>torch.ops._C.fused_allreduce_gemmarnorm</code>(<span class="filepath">vllm/model_executor/layers/fused_allreduce_gemma_rms_norm.py</span>),超限尺寸回落到普通路径。</p>
    </div>

    <div class="card reveal d1">
      <h3><span class="ico">🔤</span>B2 · Vocab embedding allreduce(按 owner 稀疏归约)</h3>
      <p><code>VocabParallelEmbedding.forward</code>(<span class="filepath">vllm/model_executor/layers/vocab_parallel_embedding.py:546-569</span>):每个 rank 对自己负责的 vocab 分片查表,非 owner 位置 <code>masked_fill_</code> 为 0,然后 <code>self.parallel_group.all_reduce(...)</code>(或退化到 <code>tensor_model_parallel_all_reduce</code>)。两个细节:FP8 embedding 会 <code>view(torch.int8)</code> 再做整数 SUM(每个 token 只有一个 owner,整数和等价于拼接);<code>ParallelLMHead</code> 继承同一套逻辑。</p>
    </div>

    <div class="card reveal d2">
      <h3><span class="ico">📊</span>B3 · Logits 汇聚:all_gather 或 gather</h3>
      <p><code>LogitsProcessor._get_logits</code>(<span class="filepath">vllm/model_executor/layers/logits_processor.py:124-133</span>):按 <code>current_platform.use_all_gather()</code> 二选一——<code>tensor_model_parallel_all_gather(logits, dim=-1)</code>(每 rank 得到完整 vocab logits,采样并行)或 <code>tensor_model_parallel_gather(logits, dst=0)</code>(只汇聚到 rank 0)。V1 采样器还需要 per-rank logprobs,<span class="filepath">logits_processor.py:258/305</span> 对局部 pair 张量做 <code>dim=-1</code> 的 all_gather。这里的 all_gather 在 CUDA 平台会命中 PyNCCL,且 <code>dim=0</code> 均匀切片时可走 NCCL symmetric memory(NVLS),见第 3 节。</p>
    </div>

    <div class="card reveal">
      <h3><span class="ico">🎛️</span>B4 · DP 秩协调 allreduce(小张量、每步一次)</h3>
      <p>本基线中 DP 注意力已重构为「DP 协调 + MoE 按 DP×TP×PCP 切分」:<span class="filepath">vllm/v1/worker/dp_utils.py</span> 的 <code>coordinate_batch_across_dp</code> → <code>_run_ar</code>(<span class="filepath">dp_utils.py:57-76</span>)把每个 DP rank 的 <code>(orig_tokens, padded_tokens, should_ubatch, cudagraph_mode)</code> 拼成 <code>(4, dp_size)</code> 的 int32 张量——<b>先在 pinned CPU 上构造</b>再 <code>.to(device, non_blocking=True)</code>,然后 <code>dist.all_reduce(tensor, group=group)</code>。group 默认是 DP 的 <code>device_group</code>(NCCL);<code>parallel_config.disable_nccl_for_dp_synchronization=True</code> 时切换到 <code>cpu_group</code>(gloo),避免 GPU 同步点破坏异步调度。触发时机:每个调度步开始、DP rank 间对齐 batch 形状。</p>
    </div>

    <div class="card reveal d1">
      <h3><span class="ico">🔀</span>B5 · MoE 的 DP dispatch/combine:all_gatherv + reduce_scatterv</h3>
      <p>当 <code>all2all_backend="naive"/"allgather_reducescatter"</code> 时,EP 组由 <b>DP 与 TP 组合并</b>而成(<span class="filepath">base_device_communicator.py:49-51</span> 注释明说 "all2all lives in ep group, which is merged from dp and tp group")。<code>AgRsAll2AllManager</code>(<span class="filepath">all2all.py:57</span>)的 dispatch 就是 <code>dist_group.all_gatherv([hidden_states, router_logits], dim=0, sizes=...)</code>(<span class="filepath">all2all.py:99-111</span>),combine 是 reduce_scatterv;通信组按序取 EP/DP/PCP 组(<code>_get_comm_group</code>,<span class="filepath">all2all.py:64-75</span>)。<span class="filepath">naive_dp_ep.py:331</span> 中 MoE 层通过 <code>get_ep_group().dispatch_router_logits(...)</code> 把路由 logits 也一并聚合。这一对 v 型集合通信在 <code>CudaCommunicator._reduce_scatterv</code>(<span class="filepath">cuda_communicator.py:569-680</span>)里会命中 NCCL symm mem / AITER / PyNCCL 三条实现之一。</p>
    </div>

    <div class="card reveal d2">
      <h3><span class="ico">🕸️</span>B6 · EP dispatch/combine 真正的 all-to-all</h3>
      <p><code>CudaCommunicator.__init__</code>(<span class="filepath">cuda_communicator.py:208-295</span>)按 <code>parallel_config.all2all_backend</code> 实例化 11 种 <code>All2AllManagerBase</code> 之一:<code>AgRsAll2AllManager</code>(naive)、<code>DeepEPHTAll2AllManager</code>(deepep_high_throughput)、<code>DeepEPLLAll2AllManager</code>(deepep_low_latency)、<code>DeepEPV2All2AllManager</code>(deepep_v2)、<code>MoonEPAll2AllManager</code>(moonep,基于 NVSHMEM)、<code>MoriAll2AllManager</code>/<code>MoriEPv2All2AllManager</code>(AMD ROCm)、<code>NixlEPAll2AllManager</code>(nixl_ep,UCX)、<code>FlashInferNVLinkTwoSidedManager</code>/<code>FlashInferNVLinkOneSidedManager</code>(flashinfer NVLink 一步/两步 all2allv)、<code>PassThroughAll2AllManager</code>。MoE 层经 <code>get_ep_all2all_manager()</code>(<span class="filepath">vllm/model_executor/layers/fused_moe/all2all_utils.py:137</span>)拿到 manager,在 <code>prepare_finalize/*.py</code> 中调用 <code>buffer.dispatch/combine</code>(如 <span class="filepath">deepep_ht.py:174/402</span>)。触发时机:每个 MoE 层前向各一次 dispatch + combine,DeepEP HT 分支按 <code>self.internode</code>(<span class="filepath">base_device_communicator.py:62-67</span> 用 <code>in_the_same_node_as</code> 判定)自动选 NVLink 域内 / RDMA 跨节点算法。</p>
    </div>

    <div class="card reveal">
      <h3><span class="ico">🧩</span>B7 · CP/PCP/DCP:上下文并行的查询聚合与 LSE 修正</h3>
      <p>本基线把 CP 拆成 <b>PCP(prefill_context_parallel)</b> 与 <b>DCP(decode_context_parallel)</b> 两个组(<span class="filepath">parallel_state.py:1632/1688</span> 的 <code>get_dcp_group()/get_pcp_group()</code>;PCP 还共享 KV cache 分片计数,见 <span class="filepath">config/parallel.py:152-154</span>)。DCP 解码路径(<span class="filepath">vllm/v1/attention/ops/dcp.py</span>):<span class="filepath">flash_attn.py:1517</span> 先 <code>get_dcp_group().all_gather(query, dim=1)</code> 拿到全部 CP 秩的 query 头;随后 <code>cp_lse_ag_out_rs</code>(<span class="filepath">dcp.py:471-500</span>)做 <code>all_gather</code>(LSE)+ <code>reduce_scatter</code>(输出)的 Softmax 合并,而 <code>dcp_a2a_lse_reduce</code>(<span class="filepath">dcp.py:939</span>,<span class="filepath">dcp.py:1000</span> 的 <code>dist.all_to_all_single</code>)用 all-to-all 把修正量直接送到目标秩。<code>cp_lse_ag_out_ar</code>(<span class="filepath">dcp.py:503</span>)则是 all_gather + all_reduce 的备用组合。触发时机:DCP&gt;1 且本步含 decode/context 注意力时逐层执行;是否跳过由 <code>should_skip_dcp_context_attention</code>(<span class="filepath">cp_utils.py:117</span>)在所有 CP 秩上以一致输入判定,避免集合通信死锁。</p>
    </div>

    <div class="card reveal d1">
      <h3><span class="ico">📨</span>B8 · PP 点对点消息传递</h3>
      <p>V1 的 PP 隐藏状态传递在 <code>GPUWorker.execute_model</code>(<span class="filepath">vllm/v1/worker/gpu_worker.py:1353-1399</span>):非首秩 <code>get_pp_group().irecv_tensor_dict(all_gather_group=get_tp_group())</code>,非末秩 <code>isend_tensor_dict</code>。底层 <code>isend_tensor_dict</code>(<span class="filepath">parallel_state.py:1168-1250</span>)把字典拆成 <b>元数据 + 张量</b> 两条通道:元数据经 <code>isend_object</code>(<span class="filepath">parallel_state.py:964</span>)在 <b>gloo cpu_group</b> 上 pickle 后 <code>torch.distributed.isend</code>;CUDA 张量则 <code>torch.distributed.isend(tensor, group=self.device_group)</code>(NCCL)。发送侧还有 all-gather 优化:TP 组内每个秩只发张量的 1/tp_size 切片,接收端用 all_gather 重建(<span class="filepath">parallel_state.py:1224-1227</span> 的 <code>_should_use_all_gather</code>)。已发句柄被 <code>_pending_isends</code> FIFO 自保留并由 <code>_reap_completed_isends</code> 惰性回收(<span class="filepath">parallel_state.py:1131</span>)。另外末秩的采样 token 通过 <code>PPHandler</code>(<span class="filepath">vllm/v1/worker/gpu/pp_utils.py:198-266</span>)在 <b>独立旁路 NCCL 组</b> <code>make_sibling_device_group("pp_broadcast")</code> 与专用 CUDA stream 上 <code>torch.distributed.broadcast</code>,与主 p2p 不抢同一通信线。</p>
    </div>

    <div class="card reveal d2">
      <h3><span class="ico">⚖️</span>B9 · EPLB 专家统计同步与权重迁移</h3>
      <p>负载统计:<code>EplbState._allreduce_list</code>(<span class="filepath">vllm/distributed/eplb/eplb_state.py:1105-1128</span>)把逐层物理专家计数拼接后 <code>all_reduce(concat_tensor, group=get_ep_group().device_group)</code>(NCCL,GPU);就绪握手 <code>_all_ranks_result_ready</code>(<span class="filepath">eplb_state.py:1087</span>)用 <code>get_ep_group().cpu_all_reduce_</code>(gloo)。权重迁移(重平衡执行时)按 <code>EplbCommunicator</code> 工厂四选一(<span class="filepath">vllm/distributed/eplb/eplb_communicator.py</span>):<code>TorchDistNcclEplbCommunicator</code>(EP 组上 <code>batch_isend_irecv</code>,<span class="filepath">eplb_communicator.py:169-175</span>)、<code>TorchDistGlooStagedEplbCommunicator</code>(CPU staging + pinned buffer,gloo,<span class="filepath">eplb_communicator.py:180-250</span>)、<code>TorchDistXCCLStagedEplbCommunicator</code>(XPU)、<code>NixlEplbCommunicator</code>(NIXL <b>READ</b> 单边拉取,VRAM 注册,agent 元数据经两次 <code>all_gather_object</code> 交换,<span class="filepath">eplb_communicator.py:325-410</span>)。触发时机:EPLB 统计窗口每 N 步;迁移仅在 <code>rearrange</code> 决策产出新物理映射时。</p>
    </div>

    <div class="card reveal">
      <h3><span class="ico">🏋️</span>B10 · 权重传输 weight_transfer(训练→推理热同步)</h3>
      <p><span class="filepath">vllm/distributed/weight_transfer/</span> 是训练侧与推理 worker 之间的整模型/增量同步层,工厂注册 6 个引擎(<span class="filepath">factory.py:222-259</span>):<code>nccl</code>(训练 rank 0 与 worker 建 NCCL 组,<span class="filepath">nccl_engine.py:183</span> broadcast 权重)、<code>sparse_nccl</code>(只传变化部分)、<code>ipc</code>(<span class="filepath">ipc_engine.py:120</span>,训练器把 GPU 张量经 <b>CUDA IPC</b> handle(Base64 pickle 走 HTTP 元数据面)直接映射给同机推理进程,免拷贝)、<code>sharded_rdt</code>(Ray Direct Transport,消费端 <code>ray.get</code> 分层拉取,见 <span class="filepath">sharded_rdt_engine.py:3</span>)、<code>nccl_m2n</code>(多对多)、<code>modelexpress</code>。<code>layerwise_groups</code>(<span class="filepath">base.py:43</span>)按参数名最外层数字段把权重切成逐层分组,使 sharded_rdt 的缓冲上限是「一层」而非「一个模型」。触发时机:在线训练-推理权重同步(ILoRA/持续预训练),非推理热路径。</p>
    </div>

    <div class="card reveal d1">
      <h3><span class="ico">🚚</span>B11 · KV 传输(PD 分离)——不走 NCCL 的网络栈</h3>
      <p>PD 分离的 KV 搬运全部位于 <span class="filepath">vllm/distributed/kv_transfer/kv_connector/v1/</span>,是 <b>RDMA/存储网络栈</b>,与 NCCL 无关:<code>nixl/</code>(push/pull 双模式,NIXL agent 默认 UCX 后端,<span class="filepath">base_worker.py:814-821</span> 传 <code>engine_config: "RCACHE_ENABLE=n,TLS=^cuda_ipc"</code>;模块加载即设 <code>UCX_RCACHE_MAX_UNRELEASED=1024</code> 防 UCX 内存泄漏,<span class="filepath">vllm/distributed/nixl_utils.py:21-37</span>)、<code>mooncake/</code>(Mooncake <code>TransferEngine</code>,默认 <code>mooncake_protocol="rdma"</code>,<span class="filepath">mooncake_connector.py:890</span>)、<code>hf3fs/</code>(DeepSeek 3FS,<span class="filepath">hf3fs_client.py:26</span> 经 <code>hf3fs_fuse.io</code> + 本地 C++ 扩展写共享存储)、<code>moriio/</code>(<code>mori.io</code> 库)、<code>lmcache_connector.py</code>(LMCache 引擎适配器)。另有 <code>offloading_connector.py</code>/<code>simple_cpu_offload_connector.py</code> 走本地 CPU offload,<code>multi_connector.py</code> 可组合。触发时机:prefill 实例完成块计算后异步 push,decode 实例在调度命中前缀时 pull(经各自 <code>LookupRequest/Metadata</code> 在控制面协调)。</p>
    </div>

    <div class="card reveal d2">
      <h3><span class="ico">🔌</span>B12 · 同节点进程间:shm / ZMQ / mmap</h3>
      <p>API server ↔ EngineCore 之间用 <b>ZMQ</b>(<span class="filepath">vllm/v1/engine/core_client.py:518-527</span> 的 input/output socket,<code>make_zmq_socket</code> + <code>ipc://</code> 路径)。同节点 DP/引擎间小对象广播用 <code>MessageQueue</code>(<span class="filepath">shm_broadcast.py:122</span> 的 <code>SpinCondition</code>:读者先自旋读共享内存,空闲后靠 <code>zmq SUB/PUB</code> notify socket 唤醒,<code>CONFLATE</code> 只保留最后一条)。大张量跨进程走 <code>ShmTensorArena</code>(<span class="filepath">shm_tensor_arena.py:74</span>,槽式 arena 免逐张量 pickle)。CPU KV offload 跨 worker 共享用 <code>SharedOffloadRegion</code>(<span class="filepath">vllm/v1/kv_offload/cpu/shared_offload_region.py:87</span>,mmap 共享文件 + <code>MADV_POPULATE_WRITE</code> 预触页)。多模态 GPU 解码预算由 <code>MultiModalGPUMemoryPool</code>(<span class="filepath">vllm/multimodal/gpu_ipc_memory.py:54</span>)在 API 进程内做字节信号量准入,引擎侧 <code>reserve_mm_ipc_gpu_memory</code> 从 KV 预算中预留对应显存,保证前端 CUDA IPC 共享的解码帧不会挤爆引擎。CPU 平台还有 <code>_CPUSHMDistributed</code>(<span class="filepath">cpu_communicator.py:45</span>)在 tp/pp 组内用 SHM 替代 gloo。</p>
    </div>

    <div class="card reveal">
      <h3><span class="ico">🛰️</span>B13 · 控制面 CPU 集合通信:gloo 与 Ray</h3>
      <p>gloo 覆盖所有「对象级」通信:<code>broadcast_object</code>(<span class="filepath">parallel_state.py:860</span>,优先 mq_broadcaster)、<code>isend_object</code>(<span class="filepath">parallel_state.py:964</span>)、Custom AR 初始化时的 handle <code>all_gather_object</code>(<span class="filepath">custom_all_reduce.py:742</span>)与 CUDA graph buffer 的逐秩 <code>broadcast_object_list</code>(<span class="filepath">custom_all_reduce.py:488</span>)、<code>in_the_same_node_as</code>(<span class="filepath">parallel_state.py:2603</span>)的拓扑探测。多节点编排用 Ray:<code>RayExecutorV2</code>(<span class="filepath">vllm/v1/executor/ray_executor_v2.py:239</span>)继承 MultiprocExecutor,actor 化 worker、placement group 排布、<code>runtime_env</code> 注入环境变量,rank 0 侧用 <code>torch.distributed.TCPStore</code> 做 rendezvous,输出经 SHM <code>MessageQueue</code> 回传以免走 Ray object store 的大对象序列化。触发时机:启动/配置广播/健康检查,以及每步的调度握手。</p>
    </div>

    <div class="card reveal d1">
      <h3><span class="ico">🔍</span>B14 · 环境与拓扑检测(决定一切分发的前置)</h3>
      <p>四个关键探测:(1)<b>P2P 实测</b>——<code>gpu_p2p_access_check</code>(<span class="filepath">all_reduce_utils.py:346</span>)起两个子进程用 <code>cudaIpcGetMemHandle/cudaIpcOpenMemHandle</code> 真写一次对端显存,因为 <code>torch.cuda.can_device_access_peer</code> 在坏驱动上会误报(issue #2728);结果按 <code>CUDA_VISIBLE_DEVICES</code> 缓存进 <code>VLLM_CACHE_ROOT/gpu_p2p_access_cache_for_*.json</code>;<code>VLLM_SKIP_P2P_CHECK</code> 跳过实测只信驱动。(2)<b>全连通</b>——Custom AR 用 <code>current_platform.is_fully_connected(physical_device_ids)</code> 判 NVLink。(3)<b>同节点</b>——<code>in_the_same_node_as</code> 基于 gloo 集合通信探测。(4)<b>NIC 映射</b>——<span class="filepath">vllm/v1/executor/vllm_net_devices.py:194</span> 的 <code>set_worker_net_device</code> 按 <code>VLLM_GPU_NIC_PCIE_MAPPING</code>(GPU_BDF=NIC_BDF)为每个 worker 设 <code>UCX_NET_DEVICES</code>/<code>NCCL_IB_HCA</code> 等变量(<code>VLLM_NIC_SELECTION_VARS</code> 指定设哪几个),实现 GPU↔网卡亲和。此外 <code>VLLM_NCCL_SO_PATH</code> 指定 libnccl(<code>find_nccl_library</code>),<span class="filepath">cuda_checkpoint_executor.py:108-110</span> 会在 checkpoint 子进程里强制 <code>NCCL_IB_DISABLE=1, NCCL_CUMEM_ENABLE=0</code>,NCCL symm mem 需要 <code>NCCL 版本 ≥ 2.27.3</code>(<span class="filepath">pynccl_allocator.py:168</span>)。</p>
    </div>
  </section>

  <!-- ================= 3 分发决策 ================= -->
  <section id="s3">
    <h2 class="sec"><span class="num">3</span>分发决策机制精读:一条 allreduce 的九重门</h2>
    <p class="lede">同一条 allreduce,从 FlashInfer 预判定到 PyNCCL 兜底,按消息尺寸 × dtype × 架构 × 拓扑探测结果逐门滑行,任一门命中即返回。</p>
    <p class="reveal">入口 <code>GroupCoordinator.all_reduce</code>(<span class="filepath">parallel_state.py:730-756</span>):<code>world_size==1</code> 直接返回;<code>use_custom_op_call</code>(TPU/CUDA compile 场景,<span class="filepath">parallel_state.py:576</span>)走 <code>torch.ops.vllm.all_reduce(input_, group_name=...)</code> 自定义 op 以兼容 torch.compile;否则 <code>_all_reduce_out_place</code> 落到 <code>CudaCommunicator.all_reduce</code>(<span class="filepath">cuda_communicator.py:384-468</span>)。这个函数就是「分发链」本体,按下述顺序逐个门控,任一门命中即返回:</p>
    <div class="card reveal">
      <h3><span class="ico">🚪</span>CudaCommunicator.all_reduce 分发顺序(逐行精读)</h3>
      <ul class="feat">
        <li><b>门 1 · FlashInfer AR 预判定</b>:<code>fi_ar_comm.should_use_fi_ar(input_)</code>(<span class="filepath">flashinfer_all_reduce.py:468</span>):2D、连续、fp16/bf16/fp32、<code>nbytes ≤ max_workspace_size</code> 且 token 数不超限。若判定通过则暂时「锁定」,防止后面 NCCL symm 抢走。</li>
        <li><b>门 2 · NCCL symmetric memory</b>:<code>should_nccl_symm_mem_allreduce(world_size, input_)</code>(<span class="filepath">all_reduce_utils.py:123-156</span>)——见下方阈值表;命中则 <code>torch.ops.vllm.all_reduce_symmetric_with_copy(input_)</code>(注册于 <span class="filepath">pynccl.py:62</span>),张量被 staging 进 NCCL 注册的对称窗口后由 NCCL 自己选 NVLS/SymK kernel。</li>
        <li><b>门 3 · QuickAllReduce</b>(ROCm MI300,quickreduce 移植):<code>qr_comm.should_quick_allreduce</code>(<span class="filepath">quick_all_reduce.py:349-370</span>):dtype 白名单、16 字节对齐、尺寸在 <code>qr_min_size/qr_max_size</code> 区间(按 dtype×world size 查表,支持量化等级)。</li>
        <li><b>门 4 · FlashInfer PCIe IPC AR</b>:同节点且 world size 受支持(<span class="filepath">flashinfer_pcie_ipc_all_reduce.py:72-80</span>),面向 <b>无 NVLink 的 PCIe 机器</b>,IPC handle 直写。</li>
        <li><b>门 5 · FlashInfer AR</b>(TRT-LLM 风格 oneshot/twoshot workspace)。</li>
        <li><b>门 6 · AITER Custom AR</b>(ROCm)→ <b>自研 CustomAllreduce</b>:<code>ca_comm.should_custom_ar(inp)</code>(<span class="filepath">custom_all_reduce.py:496-511</span>):未禁用、<code>world_size ≤ 8</code>、dtype ∈ {fp32,fp16,bf16}、字节数 %16==0、weak contiguous、且(<code>world_size==2</code> 或 <code>fully_connected</code>)、<code>size &lt; self.max_size</code>。</li>
        <li><b>门 7 · batch-invariant 兜底</b>(ROCm + VLLM_BATCH_INVARIANT,浮点才走确定性树形归约)。</li>
        <li><b>门 8 · torch symm mem</b>:<code>SymmMemCommunicator.should_use_symm_mem</code>(<span class="filepath">symm_mem.py:117-125</span>):仅 <b>bfloat16</b>、%4==0、<code>size ≤ max_size</code>;命中后按 <code>_WORLD_SIZES_MULTIMEM</code>(<span class="filepath">symm_mem.py:26-31</span>)选 <code>torch.ops.symm_mem.multimem_all_reduce_</code>(NVLS 组播)或 <code>two_shot_all_reduce_</code>。</li>
        <li><b>门 9 · PyNCCL 兜底</b>:<code>pynccl_comm.all_reduce</code>;若 communicator 不存在/被禁,最终 <code>torch.distributed.all_reduce(out, group=self.device_group)</code>。</li>
      </ul>
    </div>

    <div class="card reveal d1">
      <h3><span class="ico">📐</span>3.1 尺寸阈值表:同一张卡,不同尺寸各归其主</h3>
      <p>阈值硬编码在 <span class="filepath">all_reduce_utils.py:31-120</span>,按 <b>计算能力 × world size</b> 查表(单位字节):</p>
      <table class="tbl">
        <tr><th>表</th><th>sm 9.0 (H100)</th><th>sm 10.0</th><th>sm 10.3/10.7</th></tr>
        <tr><td><code>CUSTOM_ALL_REDUCE_MAX_SIZES</code><br>(custom AR 上限)</td><td>ws2:64MB / ws4:32MB / ws6:512KB / ws8:<b>256KB</b></td><td>ws2/4:2MB,ws6/8:1MB</td><td>ws2/4:4MB,ws6:8MB,ws8:4MB</td></tr>
        <tr><td><code>SYMM_MEM_ALL_REDUCE_MAX_SIZES</code><br>(torch symm mem 上限)</td><td>ws2:64MB / ws4:32MB / ws6:64MB / ws8:<b>64MB</b></td><td>ws2:8MB / ws4:32MB / ws6,8:128MB</td><td>ws2:4MB / ws4:32MB / ws6:32MB / ws8:64MB</td></tr>
      </table>
      <p>而 <code>NCCL_SYMM_MEM_ALL_REDUCE_CONFIG</code>(<span class="filepath">all_reduce_utils.py:111-120</span>)定义了「custom AR 更优的中段区间」:<code>min_world_size=4</code>;ws4 时 custom AR 在 (16KB, 512KB) 内胜出,ws8 在 (16KB, 128KB) 内胜出;<code>always_use_above_world_size=8</code>——ws&gt;8 一律 NCCL symm。注释里直接给出 H100/GB200 实测依据(ws8:2K-16K NCCL symm 快 1.35-1.48 倍,32K-64K custom AR 胜,128K-1G NCCL symm 快 1.12-6.14 倍)。即:<b>小消息要延迟(NCCL symm / IPC 直写),中消息要 P2P 免拷贝(custom AR),大消息要带宽(NVLS 组播)</b>。</p>
    </div>

    <div class="card reveal d2">
      <h3><span class="ico">🚧</span>3.2 CustomAllreduce 的启用门槛(拓扑判定)</h3>
      <p>构造期(<span class="filepath">custom_all_reduce.py:117-355</span>)依次失败即 <code>disabled=True</code>:C++ <code>vllm::custom_ar</code> 符号缺失 → world_size ∉ <code>[2,4,6,8,16]</code> → <b>跨节点且非 MNNVL</b>(<code>_group_can_attempt_mnnvl</code>:所有秩 capability≥100 且支持 multicast,Blackwell GB NVLink 域才允许 custom 集合通信跨节点)→ 节点内 ws&gt;2 且 <code>not fully_connected</code>(PCIe-only &gt;2 卡直接放弃)→ P2P 实测失败。通过后分配两块 <b>IPC 预注册缓冲</b>(<code>create_shared_buffer</code>:每秩 <code>allocate_shared_buffer_and_handle</code> 取 cudaIpc handle,<code>all_gather_object</code> 互换,<code>ops.open_mem_handle</code> 打开对端指针,<span class="filepath">custom_all_reduce.py:731-750</span>)。CUDA graph 捕获结束时 <code>register_graph_buffers</code>(<span class="filepath">custom_all_reduce.py:477-494</span>)把 graph 内用到的地址经 <code>ops.get_graph_buffer_ipc_meta</code> 导出、逐秩 gloo 广播、注册进 C++,使图内 allreduce 也能直接 IPC 寻址。算法上 C++ 侧按 <code>fully_connected</code> 与 world size 选 <b>one-shot</b>(每卡直写所有对端,ws2/NVLink 小消息最优)或 <b>two-shot</b>(先两两交换再归约)——Python 侧以 <code>world_size==2 or fully_connected</code> 表达该前提。MNNVL 分支(<span class="filepath">custom_all_reduce.py:357-434</span>)用 <code>torch.distributed._symmetric_memory</code> 的 <code>rendezvous</code> 取 <code>multicast_ptr</code>,提供 Lamport all-gather/reduce-scatter 与 low-SM multimem reduce-scatter(<code>_select_reduce_scatter_backend</code>,<span class="filepath">custom_all_reduce.py:618-656</span>)。</p>
    </div>

    <div class="card reveal">
      <h3><span class="ico">🧭</span>3.3 all_gather / reduce_scatter 的路由</h3>
      <p><code>CudaCommunicator.all_gather</code>(<span class="filepath">cuda_communicator.py:482-516</span>):<code>dim==0</code> 且均匀切片且 <code>should_nccl_symm_mem_ag_rs()</code>(<span class="filepath">all_reduce_utils.py:159-168</span>:=启用 NCCL symm mem 且非 batch-invariant)→ <code>_all_gather_symm_mem</code>(NVLS,输出落 <code>_get_symm_scratch</code> 持久注册缓冲,<span class="filepath">cuda_communicator.py:682-730</span> 用几何高水位缓存避免每调用 ~0.5ms 的窗口注册扫描);ROCm 走基类 <code>all_gather_into_tensor</code>;否则 PyNCCL。<code>reduce_scatterv</code>(<span class="filepath">cuda_communicator.py:569-680</span>)门控更多:batch-invariant → AITER(<code>_can_use_aiter_ag_rs</code>:ROCm + FULL cudagraph + 均匀 batch)→ symm mem(仅均匀尺寸,因 <code>ncclCommWindowRegister</code> 是集合操作,非对称会死锁)→ <code>reduce_scatterv</code>(PyNCCL)→ <code>reduce_scatter</code>(PyNCCL);输出直写需 <code>is_symmetric_memory_tensor(output)</code> 或 NCCL ≥ 2.29.2(<code>NCCL_DIRECT_SYMM_RS_OUTPUT_MIN_VERSION</code>,<span class="filepath">cuda_communicator.py:32</span>)。send/recv(<span class="filepath">cuda_communicator.py:788-814</span>)与 <code>batch_isend_irecv</code> 直接用 PyNCCL 的 <code>ncclSend/ncclRecv</code>。</p>
    </div>
  </section>

  <!-- ================= 4 库档案 ================= -->
  <section id="s4">
    <h2 class="sec"><span class="num">4</span>底层通信库档案</h2>
    <p class="lede">九个底层通信库逐一建档:载体、角色、硬件路径与代价——从 NCCL 主力到 CUDA IPC 显存直通。</p>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">📡</span>NCCL(PyNccl 直绑)</h3>
        <p><b>载体</b>:<span class="filepath">vllm/distributed/device_communicators/pynccl.py</span> + <code>pynccl_wrapper.py</code>(ctypes 加载 <code>find_nccl_library()</code> 定位的 libnccl;可用 <code>VLLM_NCCL_SO_PATH</code> 覆盖)。<b>角色</b>:所有 GPU 集合通信的兜底与主力——allreduce/all_gather/reduce_scatterv/send/recv/broadcast/all_to_all_single 全封装;跨节点(无 MNNVL)时是<b>唯一</b>选项。<b>硬件路径</b>:节点内 NVLink/NVSwitch 环与树、节点间 IB/RoCE(SOCKET/TCP 也支持);<code>VLLM_USE_NCCL_SYMM_MEM=1</code> 时经 <code>pynccl_allocator.py</code> 的 <code>nccl_symm_mem_context</code> 把张量分配进 NCCL 内存池并 <code>ncclCommWindowRegister</code>,解锁 NVLS in-switch 归约。<b>特点</b>:通用、拓扑自适应、算法在库内选择;代价是每次调用的 tuner/协议开销与 SM 占用,对小消息延迟不友好。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">⚡</span>自研 Custom AllReduce(vllm::custom_ar)</h3>
        <p><b>载体</b>:<code>custom_all_reduce.py</code> + <code>csrc/custom_all_reduce</code>(CUDA C++)。<b>角色</b>:同节点 ≤8 卡(或 MNNVL 跨节点)的 NVLink/PCIe P2P 低延迟 allreduce/all_gather/reduce_scatter。<b>硬件路径</b>:CUDA IPC(<code>cudaIpcGetMemHandle</code>)互开显存 + 直接 P2P 读写,不走网络栈、零协议开销;one-shot 每卡一次写全对端、two-shot 减半跳数;MNNVL 分支用 multicast 指针做 Lamport / multimem。<b>门控</b>:见 3.2。<b>限制</b>:尺寸上限按架构表收紧(9.0 ws8 仅 256KB,因为 symm mem 可用时把大消息让给 NVLS);无固定归约顺序,故 <code>VLLM_BATCH_INVARIANT</code> 下按 dtype 条件禁用。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🧲</span>torch symmetric memory(SymmMemCommunicator / NCCL symm)</h3>
        <p><b>载体</b>:<code>symm_mem.py</code>(<code>torch.distributed._symmetric_memory</code>)与 <code>pynccl_allocator.py</code>。<b>角色</b>:两层——(a) <code>SymmMemCommunicator</code>:<code>torch_symm_mem.empty + rendezvous</code> 建对称缓冲,world size ∈ {4,6,8} 等(按架构表)时用 <code>multimem_all_reduce_</code>(NVLS 组播,交换机内归约)否则 <code>two_shot_all_reduce_</code>;(b) NCCL symmetric memory:同一块 <code>nccl_symm_mem_context</code> 池让 NCCL 自己调 NVLS kernel,由 <code>should_nccl_symm_mem_allreduce</code> 的尺寸分段调度。<b>硬件路径</b>:NVSwitch NVLS(multicast 显存)节点内。<b>代价</b>:copy-in/copy-out staging,中段尺寸反而慢——所以才有 3.1 的分段表。</p>
      </div>
      <div class="card reveal">
        <h3><span class="ico">🕸️</span>DeepEP(以及 MoRI / MoonEP / NIXL-EP / FlashInfer A2A)</h3>
        <p><b>载体</b>:<span class="filepath">all2all.py:205-429</span> 的 <code>DeepEPHTAll2AllManager</code>/<code>DeepEPLLAll2AllManager</code>/<code>DeepEPV2All2AllManager</code>(<code>import deep_ep</code>,可用性由 <code>has_deep_ep()</code> 探测)。<b>角色</b>:MoE 专家并行的 dispatch/combine(带 per-expert 路由)。HT 模式:<code>self.internode</code> 为真用 RDMA 跨节点模式,否则 NVLink 域内模式(<span class="filepath">all2all.py:269</span>,<code>VLLM_DEEPEP_HIGH_THROUGHPUT_FORCE_INTRA_NODE</code> 可强制);LL 模式:纯 RDMA 低延迟内核,<code>deep_ep.Buffer.get_low_latency_rdma_size_hint</code> 估算缓冲。<b>硬件路径</b>:节点内 NVLink + 节点间 IB/RoCE(RDMA GPUDirect)。<b>同族</b>:MoRI(ROCm,gfx942/950,XGMI+IB)、MoonEP(NVSHMEM)、NixlEP(UCX)、FlashInfer NVLink 单/双边 all2allv——都被 <code>All2AllManagerBase</code> 统一抽象,支持故障掩码(<code>query_active_mask/update_mask/clean_buffers</code>)。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🚚</span>Mooncake / NIXL / hf3fs / moriio / LMCache(KV 传输栈)</h3>
        <p><b>角色</b>:PD 分离与 KV offload 的数据面,<b>完全不经过 NCCL</b>。NIXL(<code>nixl_utils.py</code>):统一 RDMA 抽象,默认 UCX 传输(<code>TLS=^cuda_ipc</code>),agent 元数据经 TCP/gloo 交换后单边 READ;Mooncake:字节跳动 Mooncake <code>TransferEngine</code>,对象存储+RDMA 混合拓扑,默认 rdma 协议;hf3fs:DeepSeek 3FS 文件系统,<code>hf3fs_fuse.io</code> 写共享存储,天然多对多;moriio:<code>mori.io</code> 库(AMD 生态);LMCache:分层 KV cache 引擎(本仓只做 <code>lmcache_connector.py</code> 适配)。<b>硬件路径</b>:IB/RoCE(RDMA GPUDirect)、NVLink(同机 UCX)、共享文件存储。<b>控制面</b>:各 connector 的 <code>LookupRequest</code>/<code>ConnectorMetadata</code> 经 scheduler→KV transfer server(TCP)协调,与数据面分离。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🧠</span>gloo(CPU 控制面集合通信)</h3>
        <p><b>载体</b>:<span class="filepath">parallel_state.py:511</span> 为每个通信组再建一个 gloo 组;<code>CpuCommunicator</code>(<span class="filepath">cpu_communicator.py:20</span>)处理 CPU 张量。<b>角色</b>:对象/元数据广播与收发(<code>broadcast_object/isend_object/send_object</code>)、Custom AR 的 IPC handle 互换、<code>in_the_same_node_as</code> 拓扑探测、EPLB 就绪握手(<code>cpu_all_reduce_</code>)、PP 元数据通道、DP 协调的备选路径。<b>硬件路径</b>:节点内共享内存、节点间 TCP。</p>
      </div>
      <div class="card reveal">
        <h3><span class="ico">🔌</span>ZMQ + POSIX shm(同节点进程消息总线)</h3>
        <p><b>载体</b>:<code>shm_broadcast.py</code> 的 <code>MessageQueue</code>/<code>SpinCondition</code>/<code>ShmRingBuffer</code> 与 <code>v1/engine</code> 的 ZMQ socket。<b>角色</b>:(1) API↔EngineCore 的请求/输出管道(<code>core_client.py</code>,ipc:// unix socket);(2) <code>mq_broadcaster</code> 对象广播:写者 pickle 进 ring buffer,读者自旋读,空闲时 ZMQ PUB/SUB 通知唤醒(CONFLATE 防风暴);(3) <code>ShmTensorArena</code> 大张量零 pickle 传递;(4) <code>SharedOffloadRegion</code> mmap 共享 CPU KV。<b>硬件路径</b>:主机共享内存 + unix domain socket,不占 GPU 通信资源。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🔗</span>CUDA IPC(同机显存直通)</h3>
        <p><b>载体</b>:<code>cuda_wrapper.py</code> 的 <code>CudaRTLibrary</code>(直接 dlopen libcudart 调 <code>cudaIpcGetMemHandle/cudaIpcOpenMemHandle</code>)。<b>角色</b>:Custom AR 缓冲互开、CUDA graph buffer 注册、P2P 实测探测、weight_transfer 的 <code>ipc</code> 引擎(训练进程显存直接映射进推理进程)、FlashInfer PCIe IPC AR。<b>硬件路径</b>:同 PCIe 根复杂域内的 P2P(受 ACS/IOMMU 限制)或 NVLink 一跳。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🛰️</span>Ray(多节点编排)</h3>
        <p><b>载体</b>:<span class="filepath">v1/executor/ray_executor_v2.py</span> + <code>ray_utils.py</code>。<b>角色</b>:worker actor 生命周期、placement group(按节点聚合 GPU bundle)、跨节点环境注入;数据同步本身仍用 NCCL/gloo——Ray 只做编排与控制消息。唯一的数据面特例是 weight_transfer 的 <code>sharded_rdt</code>(Ray Direct Transport 分层拉权重)。<b>硬件路径</b>:GCS/TCP。</p>
      </div>
    </div>
  </section>

  <!-- ================= 5 矩阵表 ================= -->
  <section id="s5">
    <h2 class="sec"><span class="num">5</span>全景矩阵表:行为 → 决策 → 库 → 硬件 → 代码</h2>
    <p class="lede">一张表覆盖全部 16 行行为(B1–B14 及 B8′/B9′ 变体):性能调优时先定位「行为落在哪一行」,再看它被分发到哪个库、落在哪条物理链路。</p>
    <table class="tbl reveal">
      <tr><th>场景</th><th>通信模式</th><th>决策条件</th><th>底层库</th><th>硬件路径</th><th>代码位置</th></tr>
      <tr><td>B1 TP 行并行输出</td><td>all_reduce(逐层×2)</td><td>TP&gt;1 且 reduce_results;尺寸/dtype 分发链</td><td>NCCL symm → Custom AR → torch symm → PyNCCL</td><td>节点内 NVLink(NVLS)/ PCIe;节点间 IB</td><td><code>linear.py:1821</code></td></tr>
      <tr><td>B2 vocab embedding</td><td>all_reduce(带 owner mask)</td><td>TP&gt;1;FP8 时按 int8 SUM</td><td>同上</td><td>NVLink</td><td><code>vocab_parallel_embedding.py:563</code></td></tr>
      <tr><td>B3 logits 汇聚</td><td>all_gather(dim=-1) / gather</td><td>平台 <code>use_all_gather()</code></td><td>PyNCCL(dim0 均匀时可 NVLS)</td><td>NVLink</td><td><code>logits_processor.py:124</code></td></tr>
      <tr><td>B4 DP 秩协调</td><td>小 int32 all_reduce</td><td>DP&gt;1;<code>disable_nccl_for_dp_synchronization</code> 切 CPU</td><td>NCCL(device_group)或 gloo(cpu_group)</td><td>NVLink / TCP-shm</td><td><code>dp_utils.py:57-76</code></td></tr>
      <tr><td>B5 MoE naive DP</td><td>all_gatherv + reduce_scatterv</td><td><code>all2all_backend=naive</code></td><td>PyNCCL / AITER(ROCm) / NCCL symm(NVLS)</td><td>NVLink;跨 DP 节点 IB</td><td><code>all2all.py:57-111</code></td></tr>
      <tr><td>B6 EP 专家路由</td><td>all-to-all dispatch/combine</td><td>all2all_backend 选择;<code>internode</code> 判定</td><td>DeepEP / MoRI / MoonEP / NixlEP / FlashInfer</td><td>NVLink + IB RDMA</td><td><code>cuda_communicator.py:208</code>,<code>all2all.py</code></td></tr>
      <tr><td>B7 CP/DCP</td><td>query all_gather + LSE all_gather + reduce_scatter / all_to_all</td><td>PCP/DCP size&gt;1;全体秩同分支判定</td><td>PyNCCL / NCCL symm</td><td>NVLink / IB</td><td><code>dcp.py:458-529,939-1012</code></td></tr>
      <tr><td>B8 PP 隐状态</td><td>isend/irecv(张量)+ isend(元数据)</td><td>PP&gt;1;非首/末秩;TP 切片优化</td><td>NCCL(device_group)+ gloo(元数据)</td><td>NVLink / IB</td><td><code>gpu_worker.py:1358-1399</code>,<code>parallel_state.py:1168</code></td></tr>
      <tr><td>B8′ PP 采样广播</td><td>broadcast(旁路组+旁路流)</td><td>非末秩需要采样结果时</td><td>NCCL(sibling group)</td><td>NVLink / IB</td><td><code>pp_utils.py:198-266</code></td></tr>
      <tr><td>B9 EPLB 统计</td><td>拼接 all_reduce / CPU all_reduce</td><td>enable_eplb;统计窗口</td><td>NCCL / gloo</td><td>NVLink / TCP</td><td><code>eplb_state.py:1087-1128</code></td></tr>
      <tr><td>B9′ EPLB 迁移</td><td>批量 isend/irecv 或单边 READ</td><td>rearrange 产生新映射</td><td>NCCL / gloo(分级) / NIXL(UCX)</td><td>NVLink / IB RDMA</td><td><code>eplb_communicator.py:122-410</code></td></tr>
      <tr><td>B10 权重热同步</td><td>broadcast / IPC 映射 / Ray 拉取</td><td>训练-推理同步配置</td><td>NCCL / sparse_nccl / CUDA IPC / Ray RDT / m2n</td><td>NVLink / shm / TCP</td><td><code>weight_transfer/factory.py:222</code></td></tr>
      <tr><td>B11 KV 传输(PD)</td><td>RDMA 单边 / 存储写读</td><td>kv_connector 配置;命中前缀</td><td>NIXL(UCX) / Mooncake / hf3fs / moriio / LMCache</td><td>IB/RoCE GPUDirect、共享存储</td><td><code>kv_connector/v1/*</code></td></tr>
      <tr><td>B12 同节点进程</td><td>shm 环形广播 / ZMQ ipc</td><td>单机多进程</td><td>ZMQ + POSIX shm / mmap / CUDA IPC</td><td>主机内存 / unix socket</td><td><code>shm_broadcast.py</code>,<code>core_client.py:518</code></td></tr>
      <tr><td>B13 控制面对象</td><td>broadcast_object / all_gather_object</td><td>元数据与 handle 互换</td><td>gloo(本机优先 mq_broadcaster)</td><td>TCP / shm</td><td><code>parallel_state.py:860-986</code></td></tr>
      <tr><td>B14 拓扑探测</td><td>实测 P2P / 同节点探测 / NIC 映射</td><td>启动期一次,结果缓存</td><td>CUDA IPC + gloo + sysfs</td><td>PCIe BDF / NVLink / NIC</td><td><code>all_reduce_utils.py:346</code>,<code>vllm_net_devices.py:194</code></td></tr>
    </table>
  </section>

  <!-- ================= 6 动画 ================= -->
  <section id="s6">
    <h2 class="sec"><span class="num">6</span>动画演示</h2>
    <p class="lede">两个自动循环动画:同一块 GPU 硬件上不同场景分别点亮哪些链路;以及一条 allreduce 消息沿九重门逐门滑行、最终落入哪个通信库。</p>

    <div class="figure reveal">
      <div class="klabel">ANIMATED · 动画一 · GPU 拓扑通信:同一块硬件,四种流量(自动循环)</div>
      <svg id="topo" class="scene-tp" viewBox="0 0 920 430" width="920" height="430">
        <!-- 节点框 -->
        <rect class="node-box" x="25" y="70" width="400" height="280"/>
        <rect class="node-box" x="495" y="70" width="400" height="280"/>
        <text class="lbl" x="45" y="92">Node 0 (Prefill/TP 组)</text>
        <text class="lbl" x="515" y="92">Node 1 (Decode/TP 组)</text>
        <!-- GPU -->
        <g>
          <rect class="gpu" x="55" y="120" width="90" height="58" rx="6"/><text class="gpu-txt" x="78" y="154">GPU0</text>
          <rect class="gpu" x="185" y="120" width="90" height="58" rx="6"/><text class="gpu-txt" x="208" y="154">GPU1</text>
          <rect class="gpu" x="55" y="225" width="90" height="58" rx="6"/><text class="gpu-txt" x="78" y="259">GPU2</text>
          <rect class="gpu" x="185" y="225" width="90" height="58" rx="6"/><text class="gpu-txt" x="208" y="259">GPU3</text>
          <rect class="gpu" x="525" y="120" width="90" height="58" rx="6"/><text class="gpu-txt" x="548" y="154">GPU0</text>
          <rect class="gpu" x="655" y="120" width="90" height="58" rx="6"/><text class="gpu-txt" x="678" y="154">GPU1</text>
          <rect class="gpu" x="525" y="225" width="90" height="58" rx="6"/><text class="gpu-txt" x="548" y="259">GPU2</text>
          <rect class="gpu" x="655" y="225" width="90" height="58" rx="6"/><text class="gpu-txt" x="678" y="259">GPU3</text>
        </g>
        <!-- NVLink 全互联(平时暗) -->
        <g>
          <line class="nvlink" x1="145" y1="149" x2="185" y2="149"/>
          <line class="nvlink" x1="100" y1="178" x2="100" y2="225"/>
          <line class="nvlink" x1="230" y1="178" x2="230" y2="225"/>
          <line class="nvlink" x1="145" y1="254" x2="185" y2="254"/>
          <line class="nvlink" x1="145" y1="178" x2="185" y2="225"/>
          <line class="nvlink" x1="185" y1="178" x2="145" y2="225"/>
          <line class="nvlink" x1="615" y1="149" x2="655" y2="149"/>
          <line class="nvlink" x1="570" y1="178" x2="570" y2="225"/>
          <line class="nvlink" x1="700" y1="178" x2="700" y2="225"/>
          <line class="nvlink" x1="615" y1="254" x2="655" y2="254"/>
          <line class="nvlink" x1="615" y1="178" x2="655" y2="225"/>
          <line class="nvlink" x1="655" y1="178" x2="615" y2="225"/>
        </g>
        <!-- NIC 与 IB 交换机 -->
        <rect class="nic" x="330" y="185" width="64" height="40"/><text class="lbl" x="344" y="209">NIC0</text>
        <rect class="nic" x="526" y="185" width="64" height="40"/><text class="lbl" x="540" y="209">NIC1</text>
        <line class="ib" x1="394" y1="205" x2="430" y2="205"/>
        <line class="ib" x1="490" y1="205" x2="526" y2="205"/>
        <rect class="switch" x="430" y="180" width="60" height="50" rx="8"/><text class="sw-txt" x="444" y="209">IB</text>
        <!-- 场景 1:TP allreduce -->
        <g class="scn scn-tp">
          <line class="hot" x1="145" y1="149" x2="185" y2="149" stroke="#34d399"/>
          <line class="hot" x1="100" y1="178" x2="100" y2="225" stroke="#34d399"/>
          <line class="hot" x1="230" y1="178" x2="230" y2="225" stroke="#34d399"/>
          <line class="hot" x1="145" y1="254" x2="185" y2="254" stroke="#34d399"/>
          <line class="hot" x1="185" y1="178" x2="145" y2="225" stroke="#34d399"/>
          <line class="hot" x1="145" y1="178" x2="185" y2="225" stroke="#34d399"/>
          <circle class="pkt g" r="5"><animate attributeName="cx" values="150;180;150" dur="1.6s" repeatCount="indefinite"/><animate attributeName="cy" values="149;149;149" dur="1.6s" repeatCount="indefinite"/></circle>
          <circle class="pkt g" r="5"><animate attributeName="cx" values="100;100;100" dur="1.6s" repeatCount="indefinite"/><animate attributeName="cy" values="182;221;182" dur="1.6s" repeatCount="indefinite"/></circle>
          <circle class="pkt g" r="5"><animate attributeName="cx" values="230;230;230" dur="1.6s" repeatCount="indefinite"/><animate attributeName="cy" values="182;221;182" dur="1.6s" repeatCount="indefinite"/></circle>
          <circle class="pkt g" r="5"><animate attributeName="cx" values="150;180;150" dur="1.6s" repeatCount="indefinite"/><animate attributeName="cy" values="254;254;254" dur="1.6s" repeatCount="indefinite"/></circle>
          <text x="60" y="315" fill="#34d399" font-size="13" font-family="monospace">TP allreduce → Custom AR / NCCL symm(NVLink P2P + NVLS)</text>
        </g>
        <!-- 场景 2:EP all2all -->
        <g class="scn scn-ep">
          <line class="hot" x1="145" y1="149" x2="185" y2="149" stroke="#4f8cff"/>
          <line class="hot" x1="145" y1="254" x2="185" y2="254" stroke="#4f8cff"/>
          <line class="hot" x1="394" y1="205" x2="430" y2="205" stroke="#4f8cff"/>
          <line class="hot" x1="490" y1="205" x2="526" y2="205" stroke="#4f8cff"/>
          <line class="hot" x1="615" y1="149" x2="655" y2="149" stroke="#4f8cff"/>
          <line class="hot" x1="615" y1="254" x2="655" y2="254" stroke="#4f8cff"/>
          <circle class="pkt" r="5"><animate attributeName="cx" values="394;526;394" dur="2.2s" repeatCount="indefinite"/><animate attributeName="cy" values="205;205;205" dur="2.2s" repeatCount="indefinite"/></circle>
          <circle class="pkt" r="5"><animate attributeName="cx" values="526;394;526" dur="2.2s" repeatCount="indefinite"/><animate attributeName="cy" values="205;205;205" dur="2.2s" repeatCount="indefinite"/></circle>
          <circle class="pkt" r="5"><animate attributeName="cx" values="150;180;150" dur="1.4s" repeatCount="indefinite"/><animate attributeName="cy" values="149;149;149" dur="1.4s" repeatCount="indefinite"/></circle>
          <circle class="pkt" r="5"><animate attributeName="cx" values="620;650;620" dur="1.4s" repeatCount="indefinite"/><animate attributeName="cy" values="254;254;254" dur="1.4s" repeatCount="indefinite"/></circle>
          <text x="60" y="315" fill="#4f8cff" font-size="13" font-family="monospace">EP dispatch/combine → DeepEP:节点内 NVLink + 节点间 IB RDMA</text>
        </g>
        <!-- 场景 3:KV 传输 -->
        <g class="scn scn-kv">
          <line class="hot" x1="394" y1="205" x2="430" y2="205" stroke="#a78bfa"/>
          <line class="hot" x1="490" y1="205" x2="526" y2="205" stroke="#a78bfa"/>
          <circle class="pkt p" r="6"><animate attributeName="cx" values="394;526" dur="2.4s" repeatCount="indefinite"/><animate attributeName="cy" values="205;205" dur="2.4s" repeatCount="indefinite"/><animate attributeName="opacity" values="1;1;0" dur="2.4s" repeatCount="indefinite"/></circle>
          <circle class="pkt p" r="6"><animate attributeName="cx" values="394;526" dur="2.4s" begin="1.2s" repeatCount="indefinite"/><animate attributeName="cy" values="215;215" dur="2.4s" begin="1.2s" repeatCount="indefinite"/><animate attributeName="opacity" values="1;1;0" dur="2.4s" begin="1.2s" repeatCount="indefinite"/></circle>
          <text x="60" y="315" fill="#a78bfa" font-size="13" font-family="monospace">KV 传输(PD 分离)→ NIXL/UCX 或 Mooncake:IB/RoCE RDMA 单边,不经 NCCL</text>
        </g>
        <text class="lbl" x="25" y="405" id="topo-cap"></text>
      </svg>
      <div class="legend">
        <span><i style="background:#34d399"></i>节点内 NVLink/NVSwitch(P2P、NVLS)</span>
        <span><i style="background:#4f8cff"></i>EP all-to-all(NVLink + IB)</span>
        <span><i style="background:#a78bfa"></i>KV/RDMA 数据面</span>
        <span><i style="background:#5a4a3d"></i>IB 交换机(平时静默)</span>
      </div>
      <div class="cap" id="topo-note"><b>图例:</b>亮线 = 该场景激活的链路;圆点 = 数据包。当前场景:<span class="scene-chip" id="topo-chip">TP allreduce</span></div>
      <div class="cap">图 15-1 · GPU 拓扑通信:同一块硬件上,TP allreduce 走节点内 NVLink、EP all-to-all 混走 NVLink+IB、KV 传输走 IB RDMA 单边——场景每 4.6 秒自动轮播</div>
    </div>

    <div class="figure reveal d1">
      <div class="klabel">ANIMATED · 动画二 · allreduce 分发决策树:消息尺寸决定归宿(自动循环)</div>
      <div class="dt-wrap">
        <div class="dt-msg"><span class="sz" id="dt-size">输入 8 KB · bf16</span><span class="env" id="dt-env">H100×8 · TP 组 · VLLM_USE_NCCL_SYMM_MEM=1</span></div>
        <div class="dt-line"></div>
        <div class="dt-row" id="dt-gates">
          <div class="gate" data-g="symm">NCCL symm mem<small>ws≥4 且 尺寸≤16K 或 ≥128K</small></div>
          <div class="gate" data-g="quick">QuickReduce<small>ROCm MI300 专属 → 跳过</small></div>
          <div class="gate" data-g="pcie">FI PCIe IPC<small>PCIe 机型且显式开启 → 跳过</small></div>
          <div class="gate" data-g="fi">FlashInfer AR<small>未安装 → 跳过</small></div>
          <div class="gate" data-g="aiter">AITER AR<small>ROCm 专属 → 跳过</small></div>
          <div class="gate" data-g="custom">Custom AR<small>≤256KB(9.0×ws8)· NVLink 全互联</small></div>
          <div class="gate" data-g="torch">torch symm mem<small>bf16 且 ≤64MB → multimem/NVLS</small></div>
          <div class="gate" data-g="nccl">PyNCCL<small>最终兜底</small></div>
        </div>
        <div class="dt-arrow">▼</div>
        <div class="gate hit" id="dt-result" style="min-width:280px">→ Custom AllReduce(节点内 NVLink P2P)</div>
      </div>
      <div class="cap" id="dt-note"></div>
      <div class="legend">
        <span><i style="background:#34d399"></i>命中(该后端接管)</span>
        <span><i style="background:#f87171"></i>未命中(条件不满足,滑向下一门)</span>
        <span><i style="background:#22d3ee"></i>最终归宿</span>
      </div>
      <div class="cap">图 15-2 · allreduce 分发决策树:逻辑取自 <code>cuda_communicator.py:384</code> 与 <code>all_reduce_utils.py</code> 真实阈值,四种消息尺寸自动轮播</div>
    </div>
  </section>

  <!-- ================= 7 设计洞察 ================= -->
  <section id="s7">
    <h2 class="sec"><span class="num">7</span>设计洞察:为什么不只用 NCCL?</h2>
    <p class="lede">五条洞察:延迟物理学、硬件代际查表、控制面/数据面分离、单边与存储栈的席位、多硬件阵营可移植性。</p>
    <div class="grid c2">
      <div class="card reveal">
        <h3><span class="ico">⏱️</span>1 · 延迟物理学:小消息的敌人是「协议税」</h3>
        <p>NCCL 每次集合通信要过协议选择、通道/tuner、SM kernel 启动,对 2-64KB 的 decode allreduce 是纯开销。Custom AR 用 <b>IPC 直写 + 单 kernel</b> 把延迟压到微秒级;NCCL 2.27+ 的 symmetric memory(NVLS)让交换机替 GPU 做归约,小消息延迟反超 custom AR——vLLM 两者都要,按 <code>all_reduce_utils.py</code> 的实测分段表在三个后端间切换,而不是赌一个赢家。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧮</span>2 · 硬件代际差异被编码成查表而非 if-else 瀑布</h3>
        <p><code>CUSTOM_ALL_REDUCE_MAX_SIZES / SYMM_MEM_ALL_REDUCE_MAX_SIZES / FI_MNNVL_ALLREDUCE_MAX_SIZE_MB</code> 按 (架构, world size, 节点数) 查表;Blackwell 走 MNNVL Lamport/multimem,Hopper 走 NVLS,PCIe 机器走 FlashInfer IPC——<b>同一份 Python 分发代码适配三代拓扑</b>。MNNVL 甚至让 custom 集合通信跨节点成立(GB200 NVLink 域),这时「节点内专用」的传统假设被打破,<code>same_node</code> 检查让位于 multicast 探测。</p>
      </div>
      <div class="card reveal d2">
        <h3><span class="ico">🛤️</span>3 · 控制面/数据面彻底分离,gloo 不是「二等公民」</h3>
        <p>每个组天然双通道:对象与元数据(IPC handle、路由表、batch 形状)永远走 gloo/shm——<b>它们不占 GPU 通信资源、不怕 NCCL 流水线饿死</b>;只有设备张量才进九重门分发。同节点时 mq_broadcaster/ZMQ/shm 更是连 TCP 都省掉。这套分层让「PP 元数据 isend + NCCL 张量 isend」可以并行,也让 <code>PPHandler</code> 敢为采样广播单开 NCCL sibling communicator,避免与隐状态 p2p 在同一 wire 上排队(<span class="filepath">pp_utils.py:60-63</span> 注释明言此动机)。</p>
      </div>
      <div class="card reveal">
        <h3><span class="ico">📦</span>4 · 「跨卡」不等于「集合通信」:单边与存储栈的席位</h3>
        <p>PD 分离 KV、EPLB 迁移、权重热同步选择 RDMA 单边 READ(NIXL)、对象传输引擎(Mooncake)、共享文件(hf3fs)、CUDA IPC 直映、Ray 直传——因为它们的需求是<b>异步、点对点、可重试、跨集群</b>,NCCL 的集体语义反而是错误工具。<code>All2AllManagerBase</code> 给每个 A2A 后端统一的故障掩码接口(<code>query_active_mask/update_mask/clean_buffers</code>),说明 EP 通信还在向「弹性可恢复」演化,这是 NCCL 目前不提供的。</p>
      </div>
      <div class="card reveal d1">
        <h3><span class="ico">🧬</span>5 · 可移植性:同一接口,三个硬件阵营</h3>
        <p>分发链里 QuickReduce/AITER/MoRI(ROCm)、XCCL staged(XPU)、gloo(CPU)与 CUDA 系并列,靠 <code>current_platform</code> 与 group 名称前缀(<span class="filepath">cuda_communicator.py:57</span> 明确 <code>unique_name.split(":")[0] != "tp"</code> 时禁用 TP 专属后端,防止 ETP 组误用)实现平台守卫。<b>把「哪个库」做成运行时决策而不是编译期绑定</b>,是 vLLM 在多硬件生态存活的根本策略。</p>
      </div>
    </div>
  </section>

  <!-- ================= 8 小结 ================= -->
  <section id="s8">
    <h2 class="sec"><span class="num">8</span>小结</h2>
    <p class="lede">一张三级漏斗 + 五条并行通信面的全景地图。</p>
    <div class="card reveal">
      <h3><span class="ico">🏁</span>三级漏斗与五条并行通信面</h3>
      <p>vLLM 的跨卡通信是一个<b>三级漏斗</b>:模型层只声明意图(allreduce / all_gather / all-to-all / send-recv / KV 迁移);<code>GroupCoordinator</code> 按通信组与 world size 剪枝;<code>CudaCommunicator.all_reduce</code> 再按 <b>消息尺寸 × dtype × 架构 × 拓扑探测结果</b> 在 NCCL symmetric、QuickReduce、FlashInfer(PCIe IPC / AR)、AITER、自研 Custom AR、torch symm mem、PyNCCL 之间完成最终仲裁。围绕这条主链,还并行存在五条独立通信面:PP 的 gloo+NCCL 双通道 p2p、EP 的 all-to-all 插件族(DeepEP/MoRI/MoonEP/NIXL/FlashInfer)、PD 分离的 RDMA/存储栈(NIXL/Mooncake/hf3fs/moriio)、控制面的 gloo/ZMQ/shm,以及同机的 CUDA IPC 显存直通。</p>
      <p>理解这份地图的意义在于:<b>性能调优时先定位「行为落在矩阵表哪一行」,再看它被分发到了哪个库、落在哪条物理链路上</b>——例如同样一次 MoE 前向,dispatch 在 DeepEP 的 IB RDMA 上,combine 却可能在 NCCL NVLS 上,二者瓶颈特征完全不同。</p>
    </div>
    <div class="note good reveal d1">至此本系列十五篇完结,前述各篇(PagedAttention、调度器、并行、MoE、CUDA Graph 等)中出现的每一次「通信」,都能在本篇的矩阵表里找到自己的坐标。</div>
  </section>

  <div class="pgnav">
    <span>vLLM 深度解析系列 · 第 15 篇 · 由 ZCode 生成于 2026-11</span>
    <span><a href="/docs/inference-engines/vllm/14-nccl-pr-history/">← 上一篇:⑭ NCCL 合入历史</a> · <a href="/docs/inference-engines/vllm/">返回总览</a></span>
  </div>
<script>
/* ===== 动画一:拓扑场景轮播 ===== */
(function(){
  var svg=document.getElementById('topo');
  var chip=document.getElementById('topo-chip');
  var cap=document.getElementById('topo-cap');
  var scenes=[
    {cls:'scene-tp', chip:'TP allreduce', note:'RowParallelLinear 每层输出 → 走节点内 NVLink 全互联:小/中消息 Custom AR(IPC 直写),小与大消息可被 NCCL symmetric(NVLS)截胡。'},
    {cls:'scene-ep', chip:'EP all-to-all', note:'MoE dispatch/combine:DeepEP 按拓扑自选节点内 NVLink 内核与跨节点 IB RDMA 内核,token 按专家路由双向流动。'},
    {cls:'scene-kv', chip:'KV 传输(PD)', note:'Prefill 节点把 KV 块经 NIXL/UCX 或 Mooncake 的 RDMA 单边写送往 Decode 节点,GPUDirect 绕过 CPU,NCCL 完全不参与。'}
  ];
  var i=0;
  function show(){
    svg.classList.remove('scene-tp','scene-ep','scene-kv');
    svg.classList.add(scenes[i].cls);
    chip.textContent=scenes[i].chip;
    chip.style.color=['#34d399','#4f8cff','#a78bfa'][i];
    chip.style.border='1px solid '+['#34d399','#4f8cff','#a78bfa'][i];
    cap.textContent='▶ '+scenes[i].chip+' —— '+scenes[i].note;
    i=(i+1)%scenes.length;
  }
  show(); setInterval(show,4600);
})();

/* ===== 动画二:allreduce 分发决策 ===== */
(function(){
  var KB=1024, MB=1024*1024;
  var gates=Array.prototype.slice.call(document.querySelectorAll('#dt-gates .gate'));
  var res=document.getElementById('dt-result');
  var sizeEl=document.getElementById('dt-size');
  var envEl=document.getElementById('dt-env');
  var noteEl=document.getElementById('dt-note');
  var cases=[
    {size:8*KB,  symm:true,  env:'VLLM_USE_NCCL_SYMM_MEM=1 · ws=8',
     note:'8KB ≤ 16KB:NCCL symmetric memory 以最低延迟接管(小消息段),Custom AR 根本不会被咨询。'},
    {size:64*KB, symm:true,  env:'VLLM_USE_NCCL_SYMM_MEM=1 · ws=8',
     note:'64KB 落在 custom AR 优先区 (16KB,128KB):NCCL symm 让位,Custom AR 经 CUDA IPC 直写各对端(one-shot/two-shot)。'},
    {size:4*MB,   symm:false, env:'VLLM_USE_NCCL_SYMM_MEM=0 · ws=8',
     note:'关闭 NCCL symm 后:4MB 超过 Custom AR 上限(9.0×ws8=256KB),但 ≤ torch symm mem 的 64MB → multimem_all_reduce_(NVLS 组播)。'},
    {size:256*MB, symm:false, env:'VLLM_USE_NCCL_SYMM_MEM=0 · ws=8',
     note:'256MB 超过所有 fast path 尺寸门 → PyNccl 原生 all_reduce,由 NCCL 自己选环/树算法跑 NVLink+IB。'}
  ];
  /* 真实判定(简化环境:CUDA、H100 sm9.0、TP 组、bf16、FlashInfer/Quick/AITER/FI-PCIe 不可用) */
  function decide(size, symmOn){
    var r={};
    r.symm = symmOn && (size<=16*KB || size>=128*KB);       /* all_reduce_utils.py:143-155 */
    r.quick=false; r.pcie=false; r.fi=false; r.aiter=false; /* 平台/安装不可用 */
    r.custom = (!r.symm) && size <= 256*KB;                  /* CUSTOM_ALL_REDUCE_MAX_SIZES["9.0"][8] */
    r.torch  = (!r.symm) && (!r.custom) && size <= 64*MB;    /* SYMM_MEM_ALL_REDUCE_MAX_SIZES["9.0"][8] */
    r.nccl   = (!r.symm) && (!r.custom) && (!r.torch);
    return r;
  }
  function fmt(n){ return n>=MB ? (n/MB)+' MB' : (n/KB)+' KB'; }
  var ci=0;
  function run(){
    var c=cases[ci]; ci=(ci+1)%cases.length;
    var r=decide(c.size,c.symm);
    sizeEl.textContent='输入 '+fmt(c.size)+' · bf16';
    envEl.textContent='H100×8 · TP 组 · '+c.env;
    gates.forEach(function(g){g.classList.remove('pass','miss','hit');});
    res.classList.remove('hit');
    var order=['symm','quick','pcie','fi','aiter','custom','torch','nccl'];
    var k=0, hit=null;
    var names={symm:'NCCL symmetric memory(NVLS,经 all_reduce_symmetric_with_copy)',
      quick:'QuickReduce',pcie:'FlashInfer PCIe IPC',fi:'FlashInfer AR',aiter:'AITER Custom AR',
      custom:'Custom AllReduce(CUDA IPC + one-shot/two-shot)',
      torch:'torch symm mem(multimem_all_reduce_ / NVLS)',
      nccl:'PyNCCL(ncclAllReduce,环/树/NV 自适应)'};
    var t=setInterval(function(){
      if(k>=order.length){clearInterval(t);return;}
      var key=order[k];
      if(r[key]){ gates[k].classList.add('pass'); hit=key; clearInterval(t);
        res.textContent='→ '+names[key];
        res.classList.add('hit'); noteEl.innerHTML='<b>解读:</b>'+c.note;
      }else{ gates[k].classList.add('miss'); k++; }
    },430);
  }
  run(); setInterval(run,5200);
})();

// 滚动显现动画
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></channel></rss>