<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title>跨卡通信 - 标签 - 集合通信博客</title><link>https://hccl.club/tags/%E8%B7%A8%E5%8D%A1%E9%80%9A%E4%BF%A1/</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/%E8%B7%A8%E5%8D%A1%E9%80%9A%E4%BF%A1/" rel="self" type="application/rss+xml"/><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>跨卡通信全景:通信行为与底层通信库</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>跨卡通信行为与底层通信库</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>