<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title>Nccl - 标签 - 集合通信博客</title><link>https://hccl.club/tags/nccl/</link><description>Nccl - 标签 - 集合通信博客</description><generator>Hugo -- gohugo.io</generator><language>zh-CN</language><lastBuildDate>Sun, 06 Dec 2026 10:00:00 +0800</lastBuildDate><atom:link href="https://hccl.club/tags/nccl/" rel="self" type="application/rss+xml"/><item><title>Ring AllReduce：环形算法详解</title><link>https://hccl.club/docs/algorithms/ring-allreduce/</link><pubDate>Tue, 03 Nov 2026 10:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/algorithms/ring-allreduce/</guid><description>&lt;p>在数据并行（Data Parallelism）训练中，每个 rank 一步迭代结束时都持有一份本地梯度，AllReduce（全规约）负责把 p 份梯度求和并让所有 rank 得到同一份结果。这个操作每次迭代都会发生，它的效率直接决定集群的扩展上限：梯度同步慢，再多的 GPU 也只是互相等待。&lt;/p>
&lt;p>Ring AllReduce（环形全规约）是这个问题最经典的解法：把所有 rank 排成一条逻辑环，消息切块后沿环流水转发，让每个 rank 的收发量收敛到约 2 倍消息大小、与 rank 数 p 无关，从而把每一条链路的带宽都利用起来。本文推导它的两阶段结构，逐步演算 p=4 的完整数据变化，给出通信量与时间公式，并讨论它的时延短板、层次化改造，以及它与 Baidu、Horovod、NCCL 的渊源。&lt;/p></description></item><item><title>Broadcast：广播</title><link>https://hccl.club/docs/primitives/broadcast/</link><pubDate>Mon, 02 Nov 2026 10:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/primitives/broadcast/</guid><description>&lt;p>几乎每个分布式作业的第一步都是广播（Broadcast）：由 root 进程把同一份配置、超参数或控制消息，发送给通信域（Communicator）内的所有进程。它是语义最简单的一对多集合通信原语，也是理解 Scatter、AllGather、AllReduce 等更复杂原语的基石。&lt;/p></description></item><item><title>NCCL 环境变量调优</title><link>https://hccl.club/docs/tuning/nccl-env-tuning/</link><pubDate>Sun, 08 Nov 2026 10:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/tuning/nccl-env-tuning/</guid><description><![CDATA[<p>拿到 nccl-tests 的基线（baseline）之后（见<a href="/docs/tuning/nccl-tests-and-bandwidth-metrics/" rel="">nccl-tests 与带宽指标</a>），环境变量（environment variables）就是 NCCL 最直接的调优与诊断旋钮：走哪条网络路径、开多少通道、用哪个算法与协议，几乎都能在不改一行训练代码的情况下控制。</p>
<p>但环境变量也是最容易制造混乱的东西：一次改五个，效果好坏都说不清原因。本文按&quot;调试、选网、并发度、特性开关、算法协议强制&quot;五类整理最常用的一批变量，每个只讲一句话作用，再给一张典型场景组合表。使用纪律只有一条：<strong>先量再调，一次只改一个变量</strong>，每次改动后回到同一份基线复测。</p>]]></description></item><item><title>Scatter：散射</title><link>https://hccl.club/docs/primitives/scatter/</link><pubDate>Mon, 02 Nov 2026 10:20:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/primitives/scatter/</guid><description><![CDATA[<p>如果说 Broadcast 解决的是&quot;人人都拿同一份&quot;，那么散射（Scatter）解决的就是&quot;人人各拿一份&quot;：root 进程把一段大缓冲区按进程号切成 $p$ 片，第 $i$ 片发给第 $i$ 个进程。它是数据并行训练中切分数据集、分布式矩阵计算中按行分发矩阵的基础原语。</p>]]></description></item><item><title>通信域、Rank 与进程组</title><link>https://hccl.club/docs/basics/communicator-and-rank/</link><pubDate>Sun, 01 Nov 2026 11:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/basics/communicator-and-rank/</guid><description>&lt;p>「什么是集合通信」一文反复强调：集合操作的参与者是「一组进程」。那么这一组进程如何被精确定义？进程在组内如何编号？不同模块的消息如何避免串线？答案都指向同一个概念——通信域（Communicator）。它是 MPI 语义的核心构件，也被 NCCL 等 GPU 通信库以自己的方式实现。&lt;/p>
&lt;p>本文先讲清通信域的定义与 rank 编号规则，再分别给出 MPI、NCCL 和 PyTorch 中的实践代码，最后解释为什么 PyTorch 这类框架会同时维护一大堆通信域。&lt;/p></description></item><item><title>NCCL 常见故障排查</title><link>https://hccl.club/docs/tuning/nccl-troubleshooting/</link><pubDate>Mon, 09 Nov 2026 10:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/tuning/nccl-troubleshooting/</guid><description><![CDATA[<p>&ldquo;NCCL 挂了&quot;是一类问题的统称：可能是网络不通导致的 hang，可能是 GPU 或 IB 链路的硬件报错，也可能只是拓扑识别错误带来的性能劣化。排查的第一原则是分层定位（driver / network / NCCL / framework），而不是一上来就改环境变量。</p>
<p><code>NCCL_DEBUG=INFO</code> 是第一工具：它把版本、拓扑探测、通道划分、传输路径选择和初始化进度全部打进日志，绝大多数&quot;慢&quot;和&quot;挂&quot;都能在日志里找到特征行。本文按 hang、报错、性能劣化三类症状给出排查路径，并整理成一份 checklist。</p>]]></description></item><item><title>Gather：收集</title><link>https://hccl.club/docs/primitives/gather/</link><pubDate>Mon, 02 Nov 2026 10:40:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/primitives/gather/</guid><description>&lt;p>收集（Gather）是散射（Scatter）的镜像操作：每个进程交出自己的一段数据，root 进程按进程号顺序把它们拼接成一段完整缓冲区。它是最典型的多对一原语，广泛用于把各工作进程的局部结果汇聚到主进程统一处理。&lt;/p></description></item><item><title>AllGather：全收集</title><link>https://hccl.club/docs/primitives/allgather/</link><pubDate>Mon, 02 Nov 2026 11:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/primitives/allgather/</guid><description><![CDATA[<p>全收集（AllGather）是 Gather 的&quot;民主版&quot;：每个进程都把自己的块贡献出去，同时拿到所有进程的块，相当于人人都是 root 的 Gather。它是多对多通信的核心原语之一，大模型训练中的 ZeRO 参数聚合、张量并行的结果拼接都靠它完成。</p>]]></description></item><item><title>Reduce：规约</title><link>https://hccl.club/docs/primitives/reduce/</link><pubDate>Mon, 02 Nov 2026 11:20:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/primitives/reduce/</guid><description><![CDATA[<p>规约（Reduce）是第一个&quot;边搬运边计算&quot;的集合原语：各进程的数据按指定算子（SUM、MAX、MIN、PROD 等）逐元素合并，最终结果只落在 root 进程上。它是多对一通信与计算的结合，也是梯度同步的核心组件 AllReduce 的直接基础。</p>]]></description></item><item><title>NCCL 使用场景全景(代码级) · DeepInfer</title><link>https://hccl.club/docs/inference-engines/deepinfer/08-nccl-usage/</link><pubDate>Mon, 09 Nov 2026 09:00:00 +0800</pubDate><author><name>Innoecho</name></author><guid>https://hccl.club/docs/inference-engines/deepinfer/08-nccl-usage/</guid><description><![CDATA[<div class="fwdoc">
<style>
.fwdoc{--bg:#0b1020; --bg2:#0f1729; --panel:#141d33; --panel2:#1a2440;
  --border:#263352; --text:#dbe4f5; --muted:#8ea0c2;
  --accent:#4f8cff; --accent2:#22d3ee; --good:#34d399; --warn:#fbbf24; --bad:#f87171; --purple:#a78bfa;
  --code-bg:#0d1424; --radius:14px;
  --serif:"Noto Serif SC","Songti SC",serif;}
.fwdoc *{box-sizing:border-box;margin:0;padding:0}
.fwdoc{background:linear-gradient(160deg,var(--bg) 0%,var(--bg2) 60%,#0a0f1e 100%);color:var(--text);
  font-family:"PingFang SC","Microsoft YaHei","Segoe UI",system-ui,sans-serif;line-height:1.75;}
.fwdoc{flex:1;min-width:0;padding:36px 48px 80px}
@media(max-width:960px){.fwdoc{padding:24px 18px 60px}}
.fwdoc .hero{position:relative;border-radius:var(--radius);overflow:hidden;padding:46px 44px;margin-bottom:34px;
  background:radial-gradient(1200px 400px at 15% -20%,rgba(79,140,255,.28),transparent 60%),
             radial-gradient(900px 380px at 95% 0%,rgba(167,139,250,.20),transparent 55%),
             linear-gradient(135deg,#16213e,#101a30);border:1px solid var(--border)}
.fwdoc .hero .crumb{font-size:12px;color:var(--accent2);letter-spacing:1px;margin-bottom:12px}
.fwdoc .hero h1{font-size:34px;color:#fff;font-weight:800;letter-spacing:.5px;margin-bottom:10px}
.fwdoc .hero p.desc{color:var(--muted);max-width:760px;font-size:15px}
.fwdoc .hero .tags{margin-top:18px;display:flex;gap:10px;flex-wrap:wrap}
.fwdoc .hero .tag{font-size:12px;padding:4px 14px;border-radius:999px;border:1px solid var(--border);
  background:rgba(79,140,255,.10);color:var(--accent2)}
.fwdoc .tag.good{border-color:rgba(52,211,153,.4);color:var(--good);background:rgba(52,211,153,.08)}
.fwdoc .tag.warn{border-color:rgba(251,191,36,.4);color:var(--warn);background:rgba(251,191,36,.08)}
.fwdoc section{margin-bottom:44px;scroll-margin-top:20px}
.fwdoc h2.sec{display:flex;align-items:center;gap:12px;font-size:23px;color:#fff;margin-bottom:6px;padding-bottom:10px;border-bottom:1px solid var(--border)}
.fwdoc h2.sec .num{display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:10px;flex-shrink:0;
  background:linear-gradient(135deg,var(--accent),var(--purple));color:#fff;font-size:15px;font-weight:800}
.fwdoc .lede{color:var(--muted);font-size:14px;margin-bottom:20px}
.fwdoc .grid{display:grid;gap:18px}
.fwdoc .grid.c2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}
.fwdoc .grid.c3{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}
.fwdoc .card{background:linear-gradient(180deg,var(--panel),var(--panel2));border:1px solid var(--border);
  border-radius:var(--radius);padding:22px 24px;transition:transform .3s,border-color .3s,box-shadow .3s}
.fwdoc .card:hover{transform:translateY(-3px);border-color:rgba(79,140,255,.55);box-shadow:0 12px 34px -14px rgba(79,140,255,.35)}
.fwdoc .card h3{font-size:16.5px;color:#fff;margin-bottom:8px;display:flex;align-items:center;gap:9px}
.fwdoc .card h3 .ico{width:26px;height:26px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;
  background:rgba(79,140,255,.16);font-size:14px;flex-shrink:0}
.fwdoc .card p{font-size:13.5px;color:var(--muted)}
.fwdoc .card p code,.fwdoc .inline-code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1.5px 7px;border-radius:6px;
  font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px}
.fwdoc ul.feat{list-style:none}
.fwdoc ul.feat li{padding:9px 0 9px 30px;position:relative;font-size:14px;color:var(--text);border-bottom:1px dashed rgba(38,51,82,.6)}
.fwdoc ul.feat li:last-child{border-bottom:none}
.fwdoc ul.feat li::before{content:"▸";position:absolute;left:8px;color:var(--accent);font-weight:700;animation:fw-blink 2.4s infinite}
.fwdoc ul.feat li:nth-child(2n)::before{animation-delay:1.2s}
@keyframes fw-blink{0%,100%{opacity:.35}50%{opacity:1}}
.fwdoc pre.code{background:var(--code-bg);border:1px solid var(--border);border-radius:12px;padding:18px 20px;
  overflow-x:auto;font-family:"JetBrains Mono",Consolas,monospace;font-size:12.5px;line-height:1.65;margin:14px 0;position:relative}
.fwdoc pre.code::before{content:"● ● ●";display:block;color:#3a4a70;font-size:10px;letter-spacing:3px;margin-bottom:10px}
.fwdoc pre.code .k{color:#c792ea}
.fwdoc pre.code .s{color:#89ddff}
.fwdoc pre.code .c{color:#5d7294;font-style:italic}
.fwdoc pre.code .f{color:#82aaff}
.fwdoc pre.code .n{color:#f78c6c}
.fwdoc pre.code .h{color:#ffcb6b}
.fwdoc .filepath{font-family:"JetBrains Mono",Consolas,monospace;font-size:11.5px;color:var(--accent2);
  background:rgba(34,211,238,.08);border:1px solid rgba(34,211,238,.25);border-radius:6px;padding:2px 10px;display:inline-block;margin-bottom:4px}
.fwdoc table.tbl{width:100%;border-collapse:collapse;font-size:13px;margin:14px 0;border-radius:12px;overflow:hidden;border:1px solid var(--border)}
.fwdoc table.tbl th{background:#1b2a4a;color:#fff;text-align:left;padding:11px 14px;font-size:12.5px;letter-spacing:.4px}
.fwdoc table.tbl td{padding:10px 14px;border-top:1px solid var(--border);color:var(--text);vertical-align:top}
.fwdoc table.tbl tr{transition:background .2s}
.fwdoc table.tbl tr:nth-child(even) td{background:rgba(20,29,51,.5)}
.fwdoc table.tbl tr:hover td{background:rgba(79,140,255,.10)}
.fwdoc table.tbl td code{background:rgba(79,140,255,.13);color:var(--accent2);padding:1px 6px;border-radius:5px;font-family:Consolas,monospace;font-size:12px}
.fwdoc .badge{display:inline-block;font-size:11px;padding:2px 10px;border-radius:999px;font-weight:600;letter-spacing:.3px}
.fwdoc .badge.merged{background:rgba(52,211,153,.15);color:var(--good);border:1px solid rgba(52,211,153,.4)}
.fwdoc .badge.open{background:rgba(79,140,255,.13);color:var(--accent);border:1px solid rgba(79,140,255,.4)}
.fwdoc .badge.closed{background:rgba(248,113,113,.13);color:var(--bad);border:1px solid rgba(248,113,113,.4)}
.fwdoc .badge.nccl{background:rgba(251,191,36,.12);color:var(--warn);border:1px solid rgba(251,191,36,.4)}
.fwdoc .badge.hccl{background:rgba(167,139,250,.13);color:var(--purple);border:1px solid rgba(167,139,250,.4)}
.fwdoc .badge.deepep{background:rgba(34,211,238,.12);color:var(--accent2);border:1px solid rgba(34,211,238,.4)}
.fwdoc .reveal{opacity:0;transform:translateY(26px);transition:opacity .7s cubic-bezier(.2,.7,.3,1),transform .7s cubic-bezier(.2,.7,.3,1)}
.fwdoc .reveal.on{opacity:1;transform:none}
.fwdoc .reveal.d1{transition-delay:.12s}
.fwdoc .reveal.d2{transition-delay:.24s}
.fwdoc .reveal.d3{transition-delay:.36s}
.fwdoc .figure{background:linear-gradient(180deg,#0e1729,#111c33);border:1px solid var(--border);border-radius:var(--radius);
  padding:20px;margin:18px 0;position:relative;overflow:hidden}
.fwdoc .figure .cap{text-align:center;font-size:12.5px;color:var(--muted);margin-top:10px}
.fwdoc .figure svg{width:100%;height:auto;display:block}
.fwdoc .flowline{stroke-dasharray:7 7;animation:fw-flow 1.2s linear infinite}
@keyframes fw-flow{to{stroke-dashoffset:-14}}
.fwdoc .pulse{animation:fw-pulse 2s ease-in-out infinite;transform-origin:center}
@keyframes fw-pulse{0%,100%{opacity:.45;transform:scale(1)}50%{opacity:1;transform:scale(1.06)}}
.fwdoc .node-gpu{fill:#16233f;stroke:#4f8cff;stroke-width:1.6;rx:10}
.fwdoc .node-gpu-title{fill:#dbe4f5;font-size:13px;font-weight:700}
.fwdoc .token-dot{fill:#22d3ee}
.fwdoc .barrow{filter:drop-shadow(0 0 6px rgba(34,211,238,.7))}
.fwdoc .timeline{position:relative;padding-left:34px}
.fwdoc .timeline::before{content:"";position:absolute;left:10px;top:6px;bottom:6px;width:2px;
  background:linear-gradient(180deg,var(--accent),var(--purple),transparent)}
.fwdoc .tl-item{position:relative;margin-bottom:20px}
.fwdoc .tl-item::before{content:"";position:absolute;left:-30px;top:7px;width:12px;height:12px;border-radius:50%;
  background:var(--accent);box-shadow:0 0 0 4px rgba(79,140,255,.18);animation:fw-pulse 2.4s infinite}
.fwdoc .tl-item .tl-date{font-size:11.5px;color:var(--accent2);letter-spacing:.5px}
.fwdoc .tl-item .tl-body{font-size:13.5px;color:var(--text);margin-top:3px}
.fwdoc .note{border-left:3px solid var(--accent);background:rgba(79,140,255,.07);border-radius:0 10px 10px 0;
  padding:13px 18px;font-size:13px;color:var(--text);margin:16px 0}
.fwdoc .note.warn{border-left-color:var(--warn);background:rgba(251,191,36,.06)}
.fwdoc .note.good{border-left-color:var(--good);background:rgba(52,211,153,.06)}
.fwdoc .note b{color:#fff}
.fwdoc .pgnav{margin-top:60px;padding-top:20px;border-top:1px solid var(--border);color:#5a6b92;font-size:12px;
  display:flex;justify-content:space-between;flex-wrap:wrap;gap:10px}
.fwdoc .pgnav a{color:var(--accent2);text-decoration:none}
/* ===== 导入面板附加样式 ===== */
.fwdoc{border-radius:14px;margin:18px 0}
.fwdoc table.tbl{display:block;overflow-x:auto;max-width:100%}
@media (prefers-reduced-motion:reduce){
.fwdoc *,.fwdoc *::before,.fwdoc *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
.fwdoc .reveal{opacity:1!important;transform:none!important}
}

</style>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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