show-me通信与并行
40 分钟2026-10-21搜索⌘K
show-me 知识库/comm-parallel/a2a-ar-ag-sglang

三种集合通信的落点:all2all、allreduce、allgather 与 GLM-5.3 的一条 forward

先把三者在「目标 / 参与方数据变化 / 典型输出 / 使用场景」四个维度上分开, 再沿着 SGLang 的 communication_op.py → GroupCoordinator → layer_boundary → token_dispatcher 一路走下去,标出它们在 GLM-5.3 的一份 TP8 部署里究竟在哪一行被触发。

2026-10-21SGLang集合通信all2allallreduce allgatherGLM-5.3TP / EP源码走读
术语约定:rank、group、dispatch / combine、 partial、slice、boundary 保留英文原词 —— 它们是 SGLang 源码里的变量名、 函数名或日志片段,译过去就无法与代码对上。所有函数名、参数名、文件路径一律原样保留。 本页的符号与行号取自 sgl-project/sglang main@16eb87c(2026-10-20)的本地检出, 逐条 read 核对过,未做运行时实测。

结论

01三个原语:四个维度逐一拆

下面三张图用同一个约定:行 = rank,列 = 数据块,颜色 = 这块数据由哪个 rank 产出,N = 4。 三张图的输入格子数不同,输出格子数也不同 —— 差异全在布局里,不在"带宽"这种模糊说法里。

allreduce每 rank 持有同 shape 的 partial,求和输入b0b1b2b3r0p0p0p0p0r1p1p1p1p1r2p2p2p2p2r3p3p3p3p32·(N−1)/N·n输出b0b1b2b3r0ΣΣΣΣr1ΣΣΣΣr2ΣΣΣΣr3ΣΣΣΣ每 rank 都得到同一份完整结果allgather每 rank 只持有 n/N 的切片输入b0b1b2b3r0s0r1s1r2s2r3s3(N−1)/N·n输出b0b1b2b3r0s0s1s2s3r1s0s1s2s3r2s0s1s2s3r3s0s1s2s3每 rank 都拼出完整张量,各自相同all2all每 rank 持有发往各 rank 的不同块输入b0b1b2b3r00→00→10→20→3r11→01→11→21→3r22→02→12→22→3r33→03→13→23→3(N−1)/N·n输出b0b1b2b3r00→01→02→03→0r10→11→12→13→1r20→21→22→23→2r30→31→32→33→3每 rank 收齐别人发给它的块,各自不同行 = rank,列 = 数据块;颜色 = 数据由哪个 rank 产出;Σ = 四个 rank 的值已相加。

同一个 N = 4 的 group。左:每个 rank 交一份 partial,输出处处相同。 中:每个 rank 只交一格,输出拼成整行。右:每格都要发出去,输出是输入矩阵的转置。 右图的字节数和中图相同 —— 都是 (N−1)/N·n,区别只在"发给谁"。 窄屏上这张图可横向滑动。

allreduce —— 求和后人人有份

通信目标

把 N 个 rank 上同 shape 的 N 份 partial 逐元素相加, 再把完整的和放回每一个 rank。它的目标里同时包含"归约"和"广播"两件事。

参与方数据变化

每份输入都覆盖全部元素,但只是部分和(例如 o_proj 在本 rank 那 1/8 个 head 上算出的贡献)。输出仍是全部元素, 数值变成 Σ,且 N 份完全相同。

典型输出

所有 rank 上的张量逐字节相同。冗余是它的定义,不是副作用 —— 下游每个 rank 都要独立继续算,所以必须人手一份。

常见场景

TP 的 RowParallelLinear(o_proj、 down_proj)之后;词表并行 embedding 之后;DP attention 上 attention 的 partial 求和; 层尾那次"把 FFN 的 partial 收拢"。

allgather —— 拼起来后人人有份

通信目标

每个 rank 持有一个互不重叠的切片,把它们按顺序拼接成完整张量, 让每个 rank 都拿到这份拼接结果。不做任何算术。

参与方数据变化

输入只有 n/N(列切则宽度是 1/N,行切则行数是 1/N)。输出是 n: 每个 rank 从"我这一片"变成"所有人那几片都在我这"。数据被复制,而不是被求和。

典型输出

所有 rank 上相同,且等于 [s0 | s1 | … | sN-1]。 SGLang 里这一步是显式写出来的:先 all_gather_into_tensor, 再 reshape((world_size,) + input_size) + movedim(0, dim) + reshape, 拼的语义就落在 movedim 这一行。

常见场景

词表并行的 lm_head 之后拼 logits;A2A 打散 token 之后还原完整行; TP 切分的 KV 需要凑齐时;MTP / aux hidden state 需要全序列时。

all2all —— 每对之间交换的块都不一样

通信目标

每个 rank 把自己的 buffer 切成 N 段,第 j 段只发给 rank j, 同时从每个 rank 收一段。它是 N 个"点对点、且每对内容不同"的交换, 而不是 N 次广播。

参与方数据变化

输入是"按目的 rank 切好的块",输出是"按来源 rank 排好的块"。 总字节基本不变(balanced 时严格不变),每 rank 仍是 n,但内容被重排: rank r 的输出恰好是输入矩阵的第 r 列。

典型输出

每个 rank 都不一样。这正是它与前两者的分界: allreduce / allgather 的产物在 rank 之间可以互换,all2all 的产物不能 —— 换过去就是错的。

常见场景

MoE 的 dispatch(token 按路由结果搬到专家所在 rank)与 combine(算完搬回原 token 所在 rank);以及 SGLang 里 TP lm_head 把"all-gather + DP scatter"合并成一次 all_to_all_single 的那条路。

02四维对照,以及一句话判据

维度allreduceallgatherall2all
通信目标 逐元素求和,把和放回所有 rank 拼接切片,把整条放回所有 rank 按目的地重新分发,各 rank 各拿一份
输入布局 N 份 partial,同 shape、不同值 N 份互不重叠的 slice,合起来才完整 每 rank 一个 buffer,按目的 rank 切成 N 块
是否有算术 有,sum 无 无
每 rank 字节 n → n n/N → n n → n(重排)
总线上搬的量 2·(N−1)/N·n (N−1)/N·n (N−1)/N·n
输出在各 rank 上 相同(冗余复制) 相同(冗余复制) 各不相同(置换)
发送模式 同一份发出,收端累加 同一份发 N−1 次(内容相同) 发 N−1 次,每次内容不同
一句话判据 输入是 partial → 必需求和 输入是切片 → 必需拼接 输入按目的地切好 → 必需置换
allgather 与 all2all 的字节数完全相同,都是 (N−1)/N·n。它们的差别不是"搬多少",而是 "每一对之间搬的是不是同一个东西"。allgather 是 N−1 次相同内容的发送(等价于 N 次广播); all2all 是 N−1 次互不相同内容的发送。所以 allgather 的产物在 rank 之间可以互相替代, all2all 的产物不行。

03与其余五种集合通信的区别

把另外五个放进来一起看,三者的特殊性才明显:只有这三个是"无 root、全员参与、全员拿到结果"的。 broadcast / scatter / gather / reduce 都有一个 root 或一个单点接收方;reduce_scatter 虽然全员参与, 但输出只有 n/N,不给全量。

原语输入分布输出分布算术 有 root 吗
broadcastroot 一份完整全员一份完整(相同)无有
scatterroot 一份完整每 rank 1/N(各不相同)无有
gather每 rank 1/N(各不相同)仅 dst 一份完整无有
reduce每 rank 一份 partial仅 dst 一份和sum有
reduce_scatter每 rank 一份 partial每 rank 1/N 的和(各不相同)sum无
allreduce每 rank 一份 partial全员一份和(相同)sum无
allgather每 rank 1/N(各不相同)全员一份完整(相同)无无
all2all每 rank 按目的切成 N 块每 rank 收 N 块(各不相同)无无

读这张表有两个捷径:

04两条恒等式:三者怎么互相造出来

恒等式一:allreduce = reduce_scatter ∘ allgather

allreduce(x₀, x₁, …, x_{N-1})            
  ≡  reduce_scatter(x)   → 每 rank 拿到 Σ 的 1/N 个切片
  ∘  allgather(那一片)    → 把 N 个切片拼回来,人人一份

字节账也对得上:reduce_scatter 搬 (N−1)/N·n,allgather 再搬 (N−1)/N·n, 合计 2·(N−1)/N·n,与一次 ring allreduce 的代价相同。所以"把 allreduce 拆成两段"在带宽上不是免费的, 它换的是别的东西:中间那一步的数据量只有 n/N,可以做在更小的行数上、可以和下一层的 norm 融合、可以和计算重叠。

SGLang 里这条恒等式是字面实现的,不是类比。layer_boundary/ops.py 里两个函数直接对应两段:

# layer_boundary/ops.py:69 —— 前半段:把层尾的 partial 求和并切到本 rank 的行
def tp_reduce_scatter(hidden_states, residual):
    """Complete a TP sum onto each rank's token slice."""
    local_tokens = hidden_states.shape[0] // parallel.tp_size
    output = hidden_states.new_empty(local_tokens, *hidden_states.shape[1:])
    parallel.tp_group.reduce_scatter_tensor(output, hidden_states)
    ...

# layer_boundary/ops.py:109 —— 后半段:下一层的输入需要整行时,再拼回来
def attn_tp_gather_input(hidden_states, forward_batch, gather=None):
    """Gather a stage input from this rank's attention-TP slice of the rows"""
    ...
    attn_tp_all_gather_into_tensor(output, local_hidden_states)

严格说,tp_reduce_scatter 与 attn_tp_gather_input 是两个 stage 的两端, 中间隔着一次残差相加和一次 RMSNorm。把这两段看成"一次 allreduce 被拆开"是理解 --boundary-reduction 的钥匙 —— 见 一节。

恒等式二:allgather = N 次 broadcast

allgather 可以看成"rank 0 广播 s₀、rank 1 广播 s₁…… rank N−1 广播 s_{N-1}"。ring 实现就是这个思路的流水化。反过来, all2all 不是 N 次 broadcast —— 因为 rank r 发出去的那 N 块内容互不相同, 收端也不能共享。所以 all2all 的实现必须是双向的、逐对的,SGLang 里它落在 DeepEP / FlashInfer / NIXL 这些专门的 transport 上,而不是 GroupCoordinator 的通用集合通信通路。

all2all 也不是"all-to-all 版的 allgather"。 两者字节数一样,但 allgather 的每个接收者都得到同一份完整张量; all2all 的每个接收者得到的是自己那一列。把 allgather 换成 all2all, 结果不是"慢一点",而是布局错了 —— 下游拿到的张量形状和内容都不对。

05SGLang 的五层落点

在 SGLang 里找一次集合通信,要沿着五个层往下走。三原语在这五层里的"存在感"完全不同 —— allreduce 和 allgather 走第 2 到第 5 层,all2all 直接从第 1 层跳到第 5 层, 中间两层它不经过。

L1 模型层
models/glm5_next.py

声明这一层的 attention / FFN 用哪个 stage,以及少数"就地决定"的通信 (例如 capture_output() 里的 all_gather、MoE 前的 token 广播)。 它不决定原语,只声明契约。

L2 边界层
layers/layer_boundary/ + layers/dp_attention.py

真正决定"这一次求和现在做、留到下层做、还是用 reduce-scatter 顶掉"的地方。 ops.py 把选择翻译成具体的 all_reduce / all_gather_into_tensor / reduce_scatter_tensor / scatter 调用。

L3 API 层
distributed/communication_op.py

12 个具名函数(其中 8 个是 all-reduce 入口、2 个是 gather、2 个是广播),全部是一行转发:tensor_model_parallel_all_reduce()、 tensor_model_parallel_all_gather()、attention_tensor_model_parallel_all_reduce()…… 名字里的前缀(tensor_model_parallel / attention_… / moe_…) 决定选哪个 group。

L4 组层
distributed/parallel_state.py · class GroupCoordinator

按 dtype、size、是否对称内存、是否在 torch.compile 下,在 msCCL++ / custom all-reduce / pynccl / FlashInfer / quick-all-reduce / torch-symm-mem / NCCL 之间选一个后端。这一层是"同一条 all_reduce 调用,落在不同 kernel 上"的全部来源。

L5 内核层
distributed/device_communicators/ + layers/moe/token_dispatcher/

前者是 custom_all_reduce.py、quick_all_reduce.py、 torch_symm_mem.py、triton_symm_mem_ag.py、vocab_gather.py; 后者是 deepep.py、deepep_v2.py、flashinfer.py、 mooncake.py、nixl.py、pplx.py、standard.py。 all2all 只在这一层。

python/sglang/srt/
├── models/glm5_next.py                  L1  声明 stage、capture_output 的 all_gather
├── layers/
│   ├── layer_boundary/                  L2  契约 → 原语的选择
│   │   ├── contracts.py                     ProducerReduction / ExitRows / OutputContract
│   │   ├── ops.py                            tp_reduce_scatter / attn_tp_gather_input / sum_output
│   │   ├── boundary.py                       _select_entry_step / _select_exit_move
│   │   ├── stage.py                          StageBoundary.prepare / finish / exit
│   │   └── factories.py                      append_stages(),GLM 层在这里组 stage
│   ├── dp_attention.py                      attn_tp_all_gather_into_tensor / reduce_scatterv
│   ├── logits_processor.py                  TP logits 的 all_gather,以及 all_to_all_single 替代
│   ├── vocab_parallel_embedding.py          词表并行出口的 all_reduce
│   └── moe/
│       ├── fused_moe_triton/layer.py        FusedMoE.forward_impl: dispatch → core → combine
│       └── token_dispatcher/            L5  all2all 的全部实现
├── distributed/
│   ├── communication_op.py              L3  12 个具名入口
│   ├── parallel_state.py                L4  GroupCoordinator + 各 group 单例
│   └── device_communicators/            L5  allreduce / allgather 的 kernel
└── arg_groups/
    ├── fields/exec_.py                      --moe-a2a-backend / --boundary-reduction
    ├── fields/parallel.py                   --enable-tp-lm-head-all-to-all
    ├── overrides.py                         _a2a_ep_size:ep_size := tp_size
    └── boundary_reduction.py                auto 如何解析成 ar / rs / rsv / rs+rsv
原语L2 边界层L3 API 层L5 内核层
allreduce sum_output()、attn_tp_all_reduce() tensor_model_parallel_all_reduce() 等 8 个 GroupCoordinator.all_reduce() 的 6 级后端
allgather attn_tp_gather_input()、dp_gather() tensor_model_parallel_all_gather() all_gather_into_tensor、vocab_gather、triton_symm_mem_ag
all2all 不经过 不经过(communication_op.py 里没有 all2all) token_dispatcher/*.dispatch()、tp_group.all_to_all_single()

这张表里没有 p2p。它不是漏掉了 —— 点对点根本不经过 L3/L4/L5 这三层里的任何一层: 它不来自模型层,而是由 managers/scheduler_pp_mixin.py 在调度侧直接调 pp_group.send_tensor_dict()。见 第 11 节。

为什么 all2all 跳过 L2 和 L3? 因为它的接口不是"张量进、张量出",而是 一对语义:dispatch 把 token 搬到专家所在 rank 并顺手把索引、权重、 每专家 token 数一起带过去;combine 把结果按原顺序收回并加权。 这中间夹着一次专家 GEMM,不可能是 communication_op.py 里那种一行转发。 所以它自成一套 TokenDispatcher 接口。

06allreduce 在 SGLang:从具名函数到 kernel

一句话答案:communication_op.py 提供 12 个一行转发的具名函数,真正的选择发生在 GroupCoordinator.all_reduce() 里 —— 那是一个 十步的分支判断,同一个调用在不同机器、 不同 dtype、不同 shape 上会落到完全不同的 kernel。

L3:八个 all-reduce 入口,差别只在 group

# distributed/communication_op.py:21
def tensor_model_parallel_all_reduce(input_):
    """All-reduce the input tensor across model parallel group."""
    return get_tp_group().all_reduce(input_)

# :120   attention 那一组(DP attention 下 attn_tp ≠ tp)
def attention_tensor_model_parallel_all_reduce(input_):
    return get_attn_tp_group().all_reduce(input_)

# :137   MoE 的专家并行组
def moe_expert_parallel_all_reduce(input_):
    return get_moe_ep_group().all_reduce(input_)

八个入口里另外五个:tensor_model_parallel_quant_all_reduce()(量化通信)、 moe_tensor_model_parallel_all_reduce()、 attention_tensor_model_parallel_quant_all_reduce()、 tensor_model_parallel_fused_allreduce_rmsnorm()(把 all-reduce 和 RMSNorm 焊进一个 kernel, 失败时返回 None 让调用方走通用路径)、 tensor_model_parallel_fused_allreduce_rmsnorm_quant_per_group()(再加 per-group FP8 量化)。

整份文件 139 行、12 个函数,没有一个做实际计算。它的价值在于把"用哪个 group"写进函数名: 读 models/glm5_next.py 时看到 attention_tensor_model_parallel_all_reduce, 就知道这次求和只跨 attention-TP,不跨 DP。

L4:GroupCoordinator.all_reduce() 的分支顺序

这个函数在 parallel_state.py:693-804。它的分支顺序就是"谁的 kernel 更快"的顺序, 而且前面的分支一旦命中就 return,不会继续往下走:

#命中条件落到哪个实现
0world_size == 1直接 return input_,一次通信都不发
1输入在 CPU 上torch.ops.sgl_kernel.shm_allreduce(共享内存),否则回落 torch.distributed
2HPU / XPU / NPU 的 communicator 可用各自的 communicator.all_reduce();XPU 走 inplace_all_reduce 自定义算子,避免被 Dynamo 拆成 c10d primitive
3torch.compiler.is_compiling()不在这里做 size 判断(会按符号 shape 反复重编译),统一交给运行时在自定义算子内部选
4pymscclpp_comm.should_mscclpp_allreduce(input_)msCCL++ tuned AllReduce
5ca_comm.should_custom_ar(input_)custom all-reduce(custom_all_reduce.py / _v2),one-shot 或 two-shot
6pynccl_comm 且开了对称内存pynccl_comm.all_reduce(),原地写回
7_can_use_flashinfer_allreduce(input_)flashinfer_allreduce(),可与 GEMM 融合
8_resolve_outplace_all_reduce_method(...) 返回非空quick all-reduce 或 torch symmetric memory
9以上都不满足inplace_all_reduce() → torch.distributed.all_reduce(NCCL ring / tree)

表里第 8 级那一句 _resolve_outplace_all_reduce_method() 自己又是一条阶梯 (parallel_state.py:957-1001),它按这个顺序返回第一个可用者:

# _resolve_outplace_all_reduce_method 可能返回的值,按优先级
"ca"  →  "pcie_ipc"  →  "qr"  →  "pymscclpp"  →  "torch_symm_mem"  →  "pynccl"  →  None
#   custom AR     PCIe IPC     quick AR   msCCL++        torch 对称内存     pynccl(仅 TC piecewise 图内)
# None 落到 _all_reduce_in_place():pynccl → torch_symm_mem → torch.distributed

第 4–8 级都带 should_* / _can_use_* 谓词,也就是说 "用不用自定义 kernel"还取决于输入张量的 dtype、字节数和当前是否在图捕获里。 这解释了为什么同一条 all_reduce 在小 batch 下走 NCCL、在大 batch 下走 one-shot —— 也解释了为什么改 batch size 会让性能曲线出现台阶。

谁在调用它:两个形状不同、选法也不同的出口

(a) RowParallelLinear —— TP 里最经典的一次。layers/linear.py:1800:

if (
    ((self.reduce_results and tp_size > 1) or self.use_decode_attn_tp)
    and not skip_all_reduce
    and not should_skip_mlp_all_reduce()
):
    if self.use_dp_attention_reduce:
        output = get_parallel().attn_tp_group.all_reduce(output_parallel)
    else:
        if quantize_communications:
            output = tensor_model_parallel_quant_all_reduce(output_parallel)
        elif self.parallel_group == "tp":
            output = get_parallel().tp_group.all_reduce(output_parallel)
        else:
            output = tensor_model_parallel_all_reduce(output_parallel)

注意 should_skip_mlp_all_reduce() 与 skip_all_reduce: 模型层可以主动把这次 all-reduce 关掉,交给边界层统一做。GLM-5.3 正是这么干的 —— 见下一节。

(b) VocabParallelEmbedding —— 词表并行的入口。layers/vocab_parallel_embedding.py:518:

output_parallel = self._embed_local_shard(input_)
if (
    output_parallel.numel() > 0
    and self.tp_size > 1
    and not get_attn_tp_context().input_scattered
):
    if self.use_attn_tp_group:
        output_parallel = attn_tp_all_reduce(output_parallel)
    else:
        output_parallel = tensor_model_parallel_all_reduce(output_parallel)

为什么 embedding 用 all-reduce 而不是 all-gather?因为词表并行把词表切了, hidden 维没切:每个 rank 算出的 [T, H] 里,只有落在自己词表分片上的行非零, 其余行是 0(masked_fill_ 置的)。这些是 partial,求和就是正确答案。 同一个布局在出口处换成 lm_head 时却是 all-gather —— 因为那时输出是 [T, V/P],需要的是拼接而不是求和。同一层类型、两种出口、两个原语, 正好是第 01 节那张判据表的两个方向。

07边界层:这一层的 allreduce 到底在哪儿发生

一句话答案:GLM-5.3 的 decoder layer 里,attention、MoE、dense MLP 四个模块全部用 reduce_results=False 构造 —— 它们自己不发起 all-reduce。 求和被记成数据流上的一个"欠账",由 layer_boundary 在层与层的交界处兑现。 兑现方式有三种(就地 all-reduce / 延后 all-reduce / reduce-scatter), 由 --boundary-reduction 与当前 batch 的行布局共同决定。

先看模型层怎么把这次通信关掉的

# models/glm5_next.py:708-772(节选)
if self.is_linear_attn:
    self.self_attn = Glm5NextLinearAttention(..., reduce_results=False)
else:
    self.self_attn = DeepseekV2AttentionMLA(..., reduce_results=False, skip_rope=True)

if self.is_layer_sparse:
    self.mlp = Glm5NextMoE(..., reduce_results=False)
else:
    self.mlp = Glm5NextMLP(..., reduce_results=False, allow_fused_down=False)

四个 reduce_results=False 意味着:o_proj 算完是 partial, down_proj 算完也是 partial,谁都不许自己 all-reduce。 这和 layers/linear.py:1800 里那个 if self.reduce_results and tp_size > 1 是同一个开关 —— 关掉之后,那段 all-reduce 整块跳过,output = output_parallel 直接返回。

为什么要把这件事从模块里拿出来?因为只有站在层与层的交界处,才知道下一个消费者是谁: 它可能只需要 1/N 的行(那就能用 reduce-scatter 顺手切好),也可能需要整行(那就得 all-gather 回来), 还可能这一层的 norm 和残差可以跟求和焊进一个 kernel(fused_allreduce_rmsnorm)。 模块自己看不到这些,所以它没有资格决定。

契约:边界层用什么词说话

# layers/layer_boundary/contracts.py:29
class ProducerReduction(Enum):
    """Who completes the sum a stage's output owes: exactly one completer for
    each output, the boundary. Compute completes it only where an FFN fuses
    it with a reduction its computation needs (``output_complete``).

    ALWAYS_PARTIAL is attention-only: finish() hands the partial sum to the
    next stage's input as its declared sum. EXIT_SCOPED, for an FFN or a
    single-stage mixer: the exit completes the sum, or carries it to the next
    stage's input.
    """
    ALWAYS_PARTIAL = auto()
    EXIT_SCOPED = auto()


# contracts.py:44
class ExitRows(Enum):
    """The rows a layer or branch must leave its output on, independent of
    compute's input rows."""
    ATTENTION = auto()
    TBO_SPLIT = auto()
    SLICE = auto()

再往下一层,是每个 stage 输出声明的 OutputContract(contracts.py:88)。 四个字段正好把"这次通信怎么兑现"的四种自由度写全了:

字段它回答的问题对应的原语
group这份输出"欠谁的 sum";为 None 表示已经是完整的 决定 all_reduce 在哪个 group 上做
always_partial这个和必须留给下一个 stage 的输入去收,本层不收 把 all_reduce 推迟,进而和下一层的 norm 融合
may_defer_to_next本层的出口可以把和带到下一层输入,也可以现在就收 同上,但是可选的
may_reduce_scatter允许由边界选中的一次定长 reduce-scatter 来完成求和 把 allreduce 换成 reduce_scatter

StageBoundary.finish()(stage.py:198)就是兑现入口。它的逻辑可以压成三句话:

# layers/layer_boundary/stage.py:198(语义摘要,非原文)
finish(hidden_states):
  if 这个 stage 有 row_transport:      → 交给 TransportExit,先搬行再收尾
  if 是 attention 且 finishes_directly:
      if 输出声明了 always_partial:      → 记一笔 DeclaredSum,欠着,交给下一层
      else:                              → 就地调用 sum_impl.run(),现在就把和收掉
  else:                                  → 走 exit(),由 ExitPolicy 选 sum_now / defer / reduce_scatter

于是"allreduce 在哪"这个问题,答案变成了三选一:

决定权在命令行:--boundary-reduction

# arg_groups/fields/exec_.py:714
boundary_reduction: A[
    Literal["auto", "ar", "rs", "rsv", "rs+rsv"],
    Arg(help="Select FFN boundary reduction: ar uses all-reduce then token
    redistribution; rs and rsv permit fixed-size and variable-size
    reduce-scatter respectively; rs+rsv permits both (RSv first).
    Unsupported paths fall back to ar. The option applies to the FFN stages of
    decoders built with stage boundaries, where auto resolves the model default;
    other models ignore it. Required attention and MoE collectives and
    all-reduce fusion are unaffected."),
] = "auto"

这段 help 本身就是本页最好的论据:"all-reduce"和"reduce-scatter"在 SGLang 里是同一个位置的两个实现, 由 --boundary-reduction 选。而 auto 怎么解析,写在 arg_groups/boundary_reduction.py 里 —— 它用架构名白名单决定:

# arg_groups/boundary_reduction.py:12-31(节选)
_RSV_ARCHITECTURES = {"BailingMoELinearForCausalLM", "LongcatFlashForCausalLM",
                      "Step3VLForConditionalGeneration", ...}
_AR_ARCHITECTURES  = {"KimiK3ForConditionalGeneration", "Qwen3ForCausalLM",
                      "MossVLForCausalLM", "Qwen4ExpForConditionalGeneration", ...}

def model_boundary_reduction(config):
    architectures = set(getattr(config, "architectures", None) or ())
    if architectures & _RSV_ARCHITECTURES: return "rsv"
    if architectures & _AR_ARCHITECTURES:  return "ar"
    ...
    return "rs+rsv"          ← 兜底值
GLM-5.3 的架构名不在那两张白名单里,所以 auto 落到兜底的 "rs+rsv" —— reduce-scatter 这条路被允许了。 但"允许"不等于"会走"。_select_exit_move() 还要看输出与残差的布局是否一致: 纯 TP8、行没被切开时 produced.layout == residual 成立,它在 boundary.py:724-726 直接返回 ExitMove(keep_output) —— 求和不会变形成 reduce-scatter,而是延后到下一层入口、以 all-reduce 的形式兑现 (prepare.py:163-170)。只有行真的被切开(SP / INPUT_SCATTERED 变体)时, reduce-scatter 才启动。

所以这件事必须分两层说:配置层,GLM-5.3 解析为 rs+rsv; 运行层,默认 TP8 布局下行是完整的,所以实际兑现的是延后执行的 all-reduce。 要确认某次请求到底走了哪条,看 profiler 里出现的是 ncclAllReduce 还是 ncclReduceScatter —— 本页没有跑 trace,只给出了代码上的选择规则。

这一段要加两个限定,免得读成"allreduce 在 GLM-5.3 里消失了": ① help 原话写明 Required attention and MoE collectives and all-reduce fusion are unaffected —— 这个开关只改 FFN stage 出口的求和方式,attention 与 MoE 自身必需的集合通信不受它管; ② auto 的解析发生在模型配置加载之后,且 --boundary-reduction 显式给值时一律优先 (if requested != "auto": target = draft = requested)。

用一句话把两件事连起来:第 04 节那条恒等式(allreduce = reduce_scatter ∘ allgather), 就是 --boundary-reduction rs+rsv 的数学内容。它没有把 allreduce 优化掉 —— 它把 allreduce 拆成两段,让中间那段只处理 1/N 的行;而在行本来就是完整的布局下, 拆开没有收益,于是选择器退回 keep_output,求和照旧是一次延后的 all-reduce。

08allgather 在 SGLang:三个内核、五处落点

一句话答案:allgather 的语义只有一句 —— [T, H/TP] → [T, H], 但 SGLang 为它准备了三条完全不同的实现路径,选择依据是调用者是谁: 通用路径走 GroupCoordinator,logits 路径走 MultimemAllGatherer, 词表路径走 vocab_gather。

通用路径:语义就落在 movedim 那一行

# distributed/parallel_state.py:1382  GroupCoordinator.all_gather
input_size = input_.size()
output_size = (input_size[0] * world_size,) + input_size[1:]
output_tensor = torch.empty(output_size, dtype=input_.dtype, device=input_.device)
...
self.all_gather_into_tensor(output_tensor, input_)

# 拼的语义在这里
output_tensor = output_tensor.reshape((world_size,) + input_size)
output_tensor = output_tensor.movedim(0, dim)
output_tensor = output_tensor.reshape(
    input_size[:dim] + (world_size * input_size[dim],) + input_size[dim + 1 :]
)

先 all_gather_into_tensor 把一个连续的 stack 填满,再用 reshape + movedim + reshape 把它"摊"到目标维上。这三行是拼接语义的完整实现: 把 [N, ...] 的第 0 维移到目标维、再合并。注意代码里的原注释—— we have to use concat-style all-gather here, stack-style all-gather has compatibility issues with torch.compile —— 这不是实现细节,是它能进 CUDA graph 的前提。

三条实现路径

实现干什么什么时候被选中
GroupCoordinator
all_gather_into_tensor
NCCL ring 的 all-gather,或 shm_allgather(CPU 输入) 默认路径;attn_tp_gather_input、dp_gather 都走它
MultimemAllGatherer
triton_symm_mem_ag.py:449
对称内存 multimem.st,沿 hidden 维一次 multimem 写完成; 文件头原话:instead of an NCCL ring,且 CUDA-graph capturable logits 的 TP gather;要求 TP 组不跨节点、dtype/shape/对齐满足契约,否则回落 NCCL
vocab_gather
vocab_gather.py
[rows, local_width] → [rows, world_size·local_width], 文件头明确写了这是 the layout GroupCoordinator.all_gather(dim=-1) produces 词表并行的 draft 模型(dspark.py / deepseek_v4_dspark.py)

落点一:lm_head 出口的 logits gather(GLM-5.3 必走)

# layers/logits_processor.py:939
if self.do_tensor_parallel_all_gather:
    if self.use_attn_tp_group:
        logits = self._gather_attn_tp_logits(logits)
    elif self._can_use_tp_lm_head_all_to_all(logits, local_hidden_states, lm_head, logits_metadata):
        logits = self._tp_lm_head_all_to_all(logits)     ← 用 all2all 顶掉 allgather
    else:
        logits = self._logits_gatherer(logits)            ← MultimemAllGatherer

这是 SGLang 里 allgather 与 all2all 唯一一处可以互相替换的地方,所以值得单独讲(见 第 09 节第 5 小节)。gatherer 的构造在 logits_processor.py:495:

self._logits_gatherer = triton_symm_mem_ag.MultimemAllGatherer(
    max_tokens=triton_symm_mem_ag.recommended_max_tokens(include_prefill=False, floor=128),
    enabled=self.do_tensor_parallel_all_gather and not self.use_attn_tp_group,
    skip_entry_sync=True,
)

include_prefill=False 说明这条 multimem 路径为自己定位在 decode: gather 的字节数随 token 数线性增长,prefill 的大 batch 更适合 NCCL ring。 enabled 里的 not self.use_attn_tp_group 也是一句实话 —— DP attention 打开后,gather 要跨的是 tp_group 而不是 attn_tp_group, multimem 缓冲区的 peer 集合就不对了。

落点二:词表并行的两个出口,两个原语

同一份"词表并行"布局,入口用 all-reduce、出口用 all-gather。这是全页最能说明"判据是输出布局"的例子:

位置输出形状为什么是这个原语
VocabParallelEmbedding
vocab_parallel_embedding.py:518
[T, H],每 rank 覆盖全部 T 行 只有落在本 rank 词表分片上的行非零,其余被 masked_fill_ 置 0 —— 这是 partial,求和即真值 → all_reduce
ParallelLMHead 之后的 logits
logits_processor.py:939
[T, V/P],每 rank 只覆盖 1/P 的列 每列都是独立的值,缺的列只能从别人那里拼过来,不能求和 → all_gather

落点三:A2A 打开之后,capture_output 里的 all_gather

# models/glm5_next.py:1108 —— 只有这三种 A2A 后端才为真
if (
    get_moe_a2a_backend().is_deepep()
    or get_moe_a2a_backend().is_mooncake()
    or get_moe_a2a_backend().is_deepep_v2()
):
    self.enable_a2a_moe = True
else:
    self.enable_a2a_moe = False

# models/glm5_next.py:1189(在 forward 的逐层循环里)
def capture_output(aux_hidden_state, *, owned=False):
    aux_hidden_state = self._prepare_aux_hidden_state(aux_hidden_state)
    owned = owned or (self.dflash_capture and self.config.mhc)
    if self.enable_a2a_moe and i > self.first_k_dense_replace:
        group = get_parallel().attn_tp_group
        aux_hidden_state = group.all_gather(aux_hidden_state, dim=0)
        owned = owned or group.world_size > 1
    aux_hidden_states.capture(aux_hidden_state, owned=owned)

这条链路值得逐字读:开了 A2A 之后,MoE 层的 hidden state 不再是"每个 rank 都有全部 token" —— dispatch 把它们按专家搬走了。但 aux hidden state(给 MTP / eagle 式草稿模型当输入的那几层输出) 要的是完整序列。于是这里补一次 all_gather(dim=0),沿 token 维拼回来。

限定条件也写得很清楚:只对 i > self.first_k_dense_replace 的层做 (dense 层没有 A2A,token 本来就在),且只在这三种后端下做 —— flashinfer / megamoe / nixl 等不在这个判断里。 这是代码的字面事实;为什么这样划界,页面不做推测。

落点四:边界层的入口 gather

attn_tp_gather_input()(ops.py:109)把上一层 reduce-scatter 切小的行拼回来, 供 attention 使用。它的触发条件是 stage 声明了 gathers_attn_tp_input, 并且当前是 SEQUENCE_PARALLEL / INPUT_SCATTERED 变体之一 —— 或者一个环境变量 SGLANG_USE_AG_AFTER_QLORA 被打开(factories.py:699):

gathers = (
    frozenset({TokenAxis.ATTN_TP})
    if stage.gathers_attn_tp_input and (sp or scattered or _use_ag_after_qlora)
    else frozenset()
)

这个 env 默认 False(environ.py:1068), 且要求模型有 q_lora_rank(glm5_next.py:741 会对没有 q_lora_rank 的配置直接报错)。 它的名字指向"低秩投影之后改用 all-gather 而不是 all-reduce",但本页只引它在上面那一行的效果, 不替它解释设计动机。

09all2all 在 SGLang:不是一个函数,是一对语义

一句话答案:communication_op.py 里没有 all2all。 它被拆成 dispatch() 和 combine() 两个方法,中间夹着一次本地专家 GEMM; dispatch() 底下换后端,就是换 transport。

调用点:FusedMoE.forward_impl 的三段式

# layers/moe/fused_moe_triton/layer.py:1578
def forward_impl(self, hidden_states, topk_output, pre_quant_input=None):
    origin_hidden_states_dim = hidden_states.shape[-1]
    ...
    dispatch_output = self._dispatch_with_pre_quant(hidden_states, topk_output, pre_quant_input)
    #   ↑ 第一次 all2all:按路由把 token 搬到专家所在 rank

    combine_input = self.run_moe_core(dispatch_output=dispatch_output)
    #   ↑ 本地 GEMM,没有任何跨 rank 通信
    ...
    final_hidden_states = self.dispatcher.combine(combine_input=combine_input)
    #   ↑ 第二次 all2all:把结果按原 token 顺序搬回去

    if self.reduce_results and (self.moe_tp_size > 1 or self.moe_ep_size > 1):
        final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)

三件事在这段代码里同时可见:

后端表:12 个取值,落到 4 个 dispatcher

# arg_groups/fields/exec_.py:802  --moe-a2a-backend 的全部取值
moe_a2a_backend: A[
    Literal["none", "deepep", "mooncake", "nixl", "mori", "ascend_fuseep",
            "flashinfer", "megamoe", "deepep_v2", "ascend_tp", "pplx",
            "flashinfer_megamoe"],
    Arg(help="Choose the backend for MoE A2A."),
] = "none"
# layers/moe/fused_moe_triton/layer.py:168  create_moe_dispatcher()
a2a_backend = get_moe_a2a_backend()
if a2a_backend.is_none() and is_npu():
    return AscendTPDispatcher(moe_runner_config)
elif (a2a_backend.is_none() or a2a_backend.is_megamoe()
      or a2a_backend.is_flashinfer_megamoe() or a2a_backend.is_ascend_fuseep()):
    # flashinfer_megamoe 把 EP all-to-all 放进 kernel 内部,dispatcher 只是 noop
    return StandardDispatcher(moe_runner_config)
elif (a2a_backend.is_deepep() or a2a_backend.is_mooncake()
      or a2a_backend.is_mori() or a2a_backend.is_nixl()
      or a2a_backend.is_pplx()):
    return MaybeTboDeepEPDispatcher(
        group=_get_deepep_comm_group(a2a_backend),
        router_topk=moe_runner_config.top_k,
        permute_fusion=True,
        num_experts=..., num_local_experts=..., hidden_size=...,
        deepep_mode=get_deepep_mode(), async_finish=True, return_recv_hook=True,
    )
elif a2a_backend.is_deepep_v2():  return DeepEPv2Dispatcher(...)
elif a2a_backend.is_flashinfer(): return FlashinferDispatcher(...)
else: raise NotImplementedError(...)
--moe-a2a-backenddispatcher含义
noneStandardDispatcher 没有 all2all:MoE 走 TP,层尾一次 all-reduce
megamoe / flashinfer_megamoeStandardDispatcher all2all 被融进 mega kernel,dispatcher 退化为 noop passthrough
ascend_fuseepStandardDispatcher 绕过 dispatcher 抽象,走 forward_fuseep(StandardDispatcher 创建但不调用)
deepep / mooncake / nixl / mori / pplxMaybeTboDeepEPDispatcher 同一套 DeepEP 语义(buffer.dispatch / combine),换 group 与 transport
deepep_v2DeepEPv2Dispatcher v2 接口,多一个 use_fp8_dispatch 与 scale block size
flashinferFlashinferDispatcher FlashInfer 的 a2a,配 --flashinfer-a2a-dispatch-type
ascend_tpAscendTPDispatcher NPU 上 none 的等价物,不是 A2A

真实的那一行:DeepEP 的 buffer.dispatch

# layers/moe/token_dispatcher/deepep.py:640
(
    num_tokens_per_rank, num_tokens_per_rdma_rank,
    num_tokens_per_expert, is_token_in_rank, previous_event,
) = buffer.get_dispatch_layout(topk_ids, self.num_experts, ..., async_finish=self.async_finish)

...
(recv_x, recv_topk_ids, recv_topk_weights,
 num_recv_tokens_per_expert, self.handle, event) = buffer.dispatch(
    x,
    topk_idx=topk_ids,
    topk_weights=topk_weights,
    num_tokens_per_rank=num_tokens_per_rank,
    num_tokens_per_rdma_rank=num_tokens_per_rdma_rank,
    is_token_in_rank=is_token_in_rank,
    num_tokens_per_expert=num_tokens_per_expert,
    async_finish=self.async_finish,
    expert_alignment=128 if deep_gemm_wrapper.ENABLE_JIT_DEEPGEMM else 1,
    config=DeepEPConfig.get_instance().normal_dispatch_config,
)

参数逐个对应第 01 节那张图的右栏:num_tokens_per_rdma_rank 是"发给每个 rank 多少", is_token_in_rank 是"每个 token 要去哪几个 rank",num_tokens_per_expert 是"每个专家收多少"。三个张量就是 all2all 的发送清单 —— 这也解释了为什么它是 "变长"的 alltoallv 而不是 all_to_all_single: 每个 rank 收到的 token 数不同,缓冲区必须按约定上限预分配,实际用多少由 num_recv_tokens_per_expert 决定。

ep_size 被强制等于 tp_size

# arg_groups/overrides.py:1612
def _a2a_ep_size(view):
    if view.moe_a2a_backend in _A2A_EP_SPANNING_BACKENDS:
        if view.ep_size != view.tp_size:
            logger.info(
                f"{view.moe_a2a_backend} MoE is enabled. The expert parallel size "
                f"is adjusted from {view.ep_size} to the tensor parallel size "
                f"[{view.tp_size}]."
            )
        return {"ep_size": view.tp_size}
    return {}

所以"开了 A2A,就不要再谈独立的 --ep-size"这句话是有代码根据的: _A2A_EP_SPANNING_BACKENDS 覆盖了除 none / ascend_tp 之外的全部后端 (overrides.py:1579)。你给 --ep-size 4 --tp-size 8 --moe-a2a-backend deepep, 启动日志会告诉你 ep 被改成了 8。

第 5 小节:MoE 之外的那一处 all2all —— TP lm_head

这是 SGLang 里唯一一处可以在 allgather 与 all2all 之间二选一的地方,也是理解两者差别的 最好样本。

# layers/logits_processor.py:1218
def _tp_lm_head_all_to_all(self, logits: torch.Tensor) -> torch.Tensor:
    """Exchange only the row block owned by each destination DP rank."""
    logits = logits.contiguous()
    all_to_all_output = torch.empty_like(logits)
    get_parallel().tp_group.all_to_all_single(
        all_to_all_output.view(-1), logits.view(-1)
    )
    return _reassemble_tp_lm_head_all_to_all_output(all_to_all_output)

为什么能换?因为两边的输出布局需求不同:

做法每个 rank 最后拿到冗余
all-gather全部 T 行 × 完整 V([T, V]) TP 倍冗余:每个 rank 都存了所有人的 logits
all-to-all本 rank 负责的那 1/TP 行 × 完整 V 零冗余:每行只存在一个 rank 上

触发条件写在 _can_use_tp_lm_head_all_to_all()(logits_processor.py:1179), 而默认值由部署形态决定(overrides.py:1405):

enable = (
    view.disaggregation_mode == "decode"
    and view.attn_dp_size > 1
    and view.tp_size == view.attn_dp_size
    and view.attn_cp_size == 1
    and not view.enable_dp_lm_head
)

即:PD 分离里的 decode 节点、且是纯 DP attention 时默认开启。 函数里还有一个必须满足的布局契约 —— logits.shape[0] == local_rows * tp_size; 不满足就退回 all-gather(batches without an equal padded row count fall back to the existing all-gather path)。

这一小节直接回答"allgather 和 all2all 到底差在哪":数学结果不同,代价可以相同。 两者都搬 (N−1)/N·n 字节,但 all-gather 之后每个 rank 都持有全量(冗余 N 倍), all-to-all 之后每个 rank 只持有自己那一片(无冗余)。当"全量"是下游所需时(例如 embedding 之后人人要算), 冗余是必要成本;当"全量"没人要时(例如 sampling 之后每 rank 只处理自己的行), 冗余就是纯粹浪费 —— 这就是这里能换的原因。

10GLM-5.3 的一条 forward:通信时序

先说配置。 SGLang 仓库里 GLM-5.3 的官方用例只给了这一份 (test/glm53_flash_common.py):

MODEL_PATH = "zai-org/GLM-5.3-Flash"

COMMON_SERVER_ARGS = [
    "--tp-size", "8",
    "--dsa-prefill-backend", "tilelang",
    "--dsa-decode-backend", "tilelang",
    "--kv-cache-dtype", "bf16",
    "--moe-runner-backend", "deep_gemm",
    "--reasoning-parser", "auto",
    "--tool-call-parser", "auto",
]

三条推论,全部可以从参数本身读出来:

模型结构:KDA / DSA-MLA 混排 + 稀疏 MoE

# models/glm5_next.py:707 —— 逐层二选一
self.is_linear_attn = config.is_kda_layer(layer_id)
if self.is_linear_attn:
    self.self_attn = Glm5NextLinearAttention(...)                    KDA 线性注意力
else:
    self.self_attn = DeepseekV2AttentionMLA(..., skip_rope=True)     DSA 稀疏 MLA

# :750 —— FFN 按 is_layer_sparse 二选一
self.mlp = Glm5NextMoE(config, ..., reduce_results=False)   = DeepseekV2MoE 的别名
self.mlp = Glm5NextMLP(..., reduce_results=False)           = DeepseekV2MLP 的别名

两个"别名"不是随手起的:glm5_next.py:100-102 直接 from sglang.srt.models.deepseek_v2 import DeepseekV2MLP as Glm5NextMLP、 DeepseekV2MoE as Glm5NextMoE。GLM-5.3 的 MoE 层与 DeepSeek 系共用同一份实现 —— 第 09 节讲的那份 FusedMoE 与 dispatcher 原样适用。

is_kda_layer() 的默认策略在 configs/glm5_next.py:198-206: layer_idx % 4 != 3 —— 每四层里留第四层给 MLA,其余三层是 KDA。

项值依据
text layers45 仓库自带文档 docs/cookbook/autoregressive/GLM/GLM-5.3-Flash.mdx("Its 45 text layers combine MLA attention, DSA sparse attention, and KDA linear attention")
attention 构成34 KDA + 11 MLA layer_idx % 4 != 3 在 45 层上的直接结果;layer_types 若存在则以它为准
FFN 构成3 dense + 42 MoE first_k_dense_replace=3、moe_layer_freq=1(configs/glm5_next.py 默认值)
专家288 routed,top-8,1 个 shared n_routed_experts=288 / num_experts_per_tok=8 / n_shared_experts=1;文档同述"288 routed experts with 8 active experts per token"
MLA 形状q_lora 1536 · kv_lora 512 · qk_nope 256 · v_head 256 configs/glm5_next.py 默认值;qk_rope_head_dim=0
MTP1 个 draft layer num_nextn_predict_layers=1,且 glm5_next.py:1687 断言它必须为 1

这张表里 45 与 288 是文档写明的,34/11 与 3/42 是默认配置字段推出来的。 真正的 config.json 不在检出里,所以如果它的 layer_types / first_k_dense_replace 与默认值不同,后两行会随之改变。 要断定实际层数,读那份 config,不要读代码默认值。

通信清单:一次 text forward 里 91 次 all-reduce + 1 次 all-gather

把上面的层数和第 07 节的边界机制合起来,就能数出总数。TP = 8、A2A = none 时:

阶段次数原语 group依据
embedding1all-reducetp_group vocab_parallel_embedding.py:533
attention 出口 ×4545all-reduceattn_tp_group prepare.py:163-170 的 attn_tp_all_reduce(attention 的 sum 一律是 partial,延后到下一层入口收)
MoE 出口 ×4242all-reducemoe_tp_group moe/utils.py:878-885 的 moe_tensor_model_parallel_all_reduce; moe_tp_size = tp_size // moe_ep_size // moe_dp_size(runtime_context.py:154),ep = 1 时它等于 tp_group
dense MLP 出口 ×33all-reducetp_group 同 attention 出口的边界路径,SumGroup.TP
lm_head logits1all-gathertp_group logits_processor.py:939 → MultimemAllGatherer
MoE dispatch / combine0—— StandardDispatcher 无跨 rank 交换
DSA indexer0—— 只有 opt-in 的 rank-0 top-k 广播,SGLANG_DSA_TOPK_BROADCAST 默认 False(environ.py)

两个值得记住的结论:

这两段是按源码调用点计数,不是 trace 实测。真实次数还会被 --boundary-reduction 的取值、may_defer_to_next 是否生效、 以及空 batch 早退影响,所以把它当上界与量级,而不是常数。

一个 decoder layer 的通信时序

① 取残差本地

hidden_states_orig = residual_access.buffer(hidden_states)(glm5_next.py:966)。 不发通信,只是留一份干净的残差给后面融合用。

② attention 入口all-gather(条件性)

self.attn_boundary.prepare(hidden_states, forward_batch, ...)(:968)。 如果上一层的出口把行切成了 1/8(ExitRows.SLICE),这里就要 attn_tp_gather_input() → attn_tp_all_gather_into_tensor 拼回整行。 纯 TP、无 SP、无 dp-attention 时这一格不触发。

③ attention 计算all-reduce 推迟

self.self_attn(...)(:970)。QKV 是 column-parallel,o_proj 是 row-parallel 且 reduce_results=False —— 算完是 partial,不在这里收。

④ attention 出口all-reduce / reduce-scatter

self.attn_boundary.finish(hidden_states, forward_batch)(:984)。 attention 的 ProducerReduction 是 ALWAYS_PARTIAL, 所以这里的 partial 通常记成欠账交给下一个 stage,真正兑现发生在 FFN 入口的 norm 里。 兑现方式由 --boundary-reduction 决定。

⑤ FFN 入口norm + 残差

self.ffn_boundary.prepare(hidden_states, forward_batch)(:985)。 如果上一步欠了 sum,这里与 post_attention_layernorm 一起做, 可以用 tensor_model_parallel_fused_allreduce_rmsnorm() 一次完成。

⑥ MoE 层(is_layer_sparse)all2all × 2 仅当 --moe-a2a-backend ≠ none

self.mlp(hidden_states, forward_batch, ...)(:1003)→ FusedMoE.forward_impl:dispatch()(→ buffer.dispatch)→ 本地专家 GEMM → combine()。默认 none 时这两个格子都不存在, 此时 MoE 在 TP 上切专家,出口是 partial。

⑦ dense 层(not is_layer_sparse)本地 GEMM

Glm5NextMLP(...):gate_up_proj column-parallel + down_proj row-parallel 且 reduce_results=False,出口同样是 partial。

⑧ FFN 出口边界求和

self.ffn_boundary.finish(hidden_states, forward_batch)(:1008)。 FFN 的 ProducerReduction 是 EXIT_SCOPED —— 由 ExitPolicy 三选一:就地 all-reduce / 留给下一层 / reduce-scatter。 GLM-5.3 的 auto 解析结果是 rs+rsv(第 07 节)。

一个 layer 之外还有三处:

L0 · embeddingall-reduce

self.embed_tokens(input_ids)(:1136)→ VocabParallelEmbedding.forward → tensor_model_parallel_all_reduce。

L1 · PP 边界send / recv(不是集合通信)

residual_batch.to_pp(...) / attn_boundary.from_pp(...)(:1140-1143、:1220-1221)。 PP 用点对点收发,pp_group 里没有任何 collective —— 但这条 p2p 在 PP + TP 下 每跳都套着一次 all-gather,详见 第 11 节。 非首 rank 的 embed_tokens、非末 rank 的 lm_head 都被替换成 PPMissingLayer(:1284-1297)。

L2 · 末层 logitsall-gather / all-to-all

self.logits_processor(input_ids, hidden_states, self.lm_head, forward_batch, aux) (:1674)→ MultimemAllGatherer 把 [T, V/8] 拼成 [T, V]; 若命中了 enable_tp_lm_head_all_to_all 则改成一次 all_to_all_single。

开 --moe-a2a-backend deepep 之后,这张图怎么变

环节TP8 默认(none) 加 --moe-a2a-backend deepep
MoE 的通信无 all2all;专家切在 TP 上,层尾一次求和 每层两次 all2all:dispatch + combine
ep_size1 被强制改成 8(_a2a_ep_size 的日志会写出来)
层尾求和边界层的 all-reduce / reduce-scatter 同样归边界层;但 MoE 的 reduce_results 已是 False,不会再叠一次
aux hidden state每 rank 已有全部 token,无需 gather 多一次 attn_tp_group.all_gather(dim=0)(glm5_next.py:1191)
CUDA graph可捕获 受 A2A 后端限制(DeepEP 的 get_dispatch_layout 带 CPU 侧的 token 计数)
一句话总结这张表:在 GLM-5.3 上,"开 A2A"不是给现有的一条 allreduce 加个更快的内核, 而是把一次稠密求和换成一堆变长 dispatch/combine,同时顺手把 ep_size 绑到 tp_size、 并在 MTP 的捕获路径上补回一次 allgather。三件事必须一起看。

11PP 的点对点:第四种通信,和它藏在里面的 all-gather

一句话答案:PP 不用集合通信,它用 send / recv。 但在 PP + TP 下这条 p2p 不是裸的点对点 —— 每个 rank 只发自己那 1/P 的切片, 接收端再 all_gather 拼回来。所以每跨一条 stage 边界,都会出现一次 allgather; 而且正是这次 allgather,逼着边界层在传输前把欠的 sum 全部收干净。

11.1 把 p2p 放回原语地图

前面的表只覆盖了 N→N 的三种。补上按"方向"分类的全景,p2p 的位置就清楚了:

方向原语有 root 吗语义
1 → 1send / recv无(两端对称) 把一份数据交给指定的那一个 rank;两端的 src / dst 必须对上
1 → Nbroadcast有(root)root 的一份完整数据发给所有人
1 → Nscatter有(root)root 切成 N 份,一人一份
N → 1gather / reduce有(dst)收到一处,其余人手里不留
N → Nallreduce / allgather / all2all无 全员参与、全员拿到结果(第 01–04 节)

p2p 是唯一"只跟一个对端说话"的原语,也正因为如此,它不需要 group 的语义 —— 它只需要 src / dst。PP 之所以选它,理由很直接:一条流水线上, stage i 只跟 i±1 有数据依赖,把别的 rank 拉进来纯属浪费。

这也是"PP 不降低通信量"这句话的准确含义:它不降低的是"每对相邻 rank 之间"的传输量, 而不是"总线上一点通信都没有"。在 PP + TP 的混合布局里,pp_group 是 rank 的一个正交划分 ([g0,g4], [g1,g5] …,见 parallel_state.py 里 initialize_model_parallel 的注释), 所以同一个 tensor 既会沿 pp 方向被点对点送出去,也会在每组内部被 TP 的集合通信处理。

11.2 send_tensor_dict():元数据走 CPU 组,张量走 device 组

# distributed/parallel_state.py:1796
def send_tensor_dict(self, tensor_dict, dst=None, all_gather_group=None, async_send=False):
    """Send the input tensor dictionary.
    NOTE: `dst` is the local rank of the source rank."""
    if dst is None:
        dst = (self.rank_in_group + 1) % self.world_size      ← 默认发给"下一个"

    metadata_list, tensor_list = _split_tensor_dict(tensor_dict)
    send_func = torch.distributed.isend if async_send else torch.distributed.send

    p2p_works = self.send_object(metadata_list, dst=dst, async_send=async_send)   ← 元数据走 CPU 组
    for tensor in tensor_list:
        if tensor.numel() == 0:
            continue
        ...
        comm_group = metadata_group if tensor.is_cpu else group                       ← 张量走 device 组
        work = send_func(tensor, self.ranks[dst], group=comm_group)
        if async_send:
            p2p_works.append(P2PWork(work, tensor))
    return p2p_works

三个细节值得注意:

11.3 这条 p2p 里藏着一次 all-gather

# 发送端 parallel_state.py:1841-1843 —— 只发自己那一片
# send-allgather: send only a slice, then do allgather.
if all_gather_group is not None and tensor.numel() % all_gather_size == 0:
    tensor = tensor.reshape(all_gather_size, -1)[all_gather_rank]

# 接收端 parallel_state.py:1885-1903 —— 收齐所有片再拼回来
if use_all_gather:
    tensor = all_gather_group.all_gather(tensor, dim=0)
    tensor = tensor.reshape(orig_shape)

调用方在 scheduler 里把 all_gather_group 显式设成 attention-TP 组 (managers/scheduler_pp_mixin.py:867):

p2p_work.extend(
    self.pp_group.send_tensor_dict(
        tensor_dict=tensor_dict,
        all_gather_group=(self.attn_tp_group),
        async_send=async_send,
    )
)

于是 PP 的每一跳变成:每个 attn-TP rank 发 1/P 的切片 → 下一 stage 的对应 rank 用 all-gather 拼回整张。 字节总数不变(p2p 的 n/P 加上 all-gather 的 (P−1)/P·n,合起来还是 n), 换掉的是那一跳 p2p 的规模。至于这样换来的是不是更快,本页不做判断 —— 代码只写了"send a slice, then do allgather"这句注释,没有给理由。

但这个切片协议有一个硬性前提,而它正好解释了第 07 节。 接收端要 all-gather 出一个正确结果,前提是每个 attn-TP rank 手里那一份补全后必须相同。 如果某个 rank 的 hidden state 还是一份 partial(求和没做完),拼出来的就是错的。 所以 residual_batch.to_pp()(residual/batch.py:270)的 docstring 写得很直白:
Every sum the output owes is completed before transport, a declared one too: the pipeline sends each tensor as one slice per attention-TP rank and gathers the slices back on the next rank, which reassembles only a tensor that every attention-TP rank holds alike.

反过来,接收端的 from_pp()(stage.py:270)就据此断言"收到的已经是完整的":

Returns:
    The received output, complete: the sender completes every sum
    before transport (see residual_batch.to_pp), so where this stage's
    entry declares a sum its producer leaves, it takes the path for a
    sum already completed.

这就是全页最紧的一处耦合:PP 的切片协议、边界层的"欠账"机制、以及 --boundary-reduction 的选择,三者是绑在一起的。 to_pp 会把每一笔欠账在出口处结清(哪怕声明的是 always_partial), 因为下一跳的 all-gather 不接受 partial。

11.4 调度侧:带类型的消息 + 独立的 comm stream

# managers/scheduler_pp_mixin.py:849
def _pp_send_dict_to_next_stage(self, tensor_dict, async_send=True, msg_type="default", ready_event=None):
    tensor_dict["__msg_type__"] = msg_type
    p2p_work = []
    with self.pp_comm_stream_ctx:
        if ready_event is not None:
            self.device_module.current_stream().wait_event(ready_event)
        p2p_work.extend(self.pp_group.send_tensor_dict(..., async_send=async_send))
    return p2p_work

11.5 GLM-5.3 的 PP 路径

模型侧只有两行,但位置很关键:

# models/glm5_next.py:1140-1143 —— 非首 rank:从上一 stage 收
else:
    assert pp_proxy_tensors is not None
    hidden_states = self.layers[self.start_layer].attn_boundary.from_pp(
        pp_proxy_tensors, forward_batch
    )

# models/glm5_next.py:1220-1221 —— 非末 rank:发给下一 stage
if not self.pp_group.is_last_rank:
    return residual_batch.to_pp(hidden_states, forward_batch)
else:
    hidden_states = residual_batch.complete_output(hidden_states, forward_batch)

首末 rank 的特权也写在构造里:只有 pp_group.is_last_rank 才建 lm_head, 其余是 PPMissingLayer();首 rank 才建 embed_tokens; tie_word_embeddings 与 pp_size > 1 不能同时成立(glm5_next.py:1284-1297)。

还有两个与"能不能开 PP"直接相关的机制:

11.6 更正:PP 不是"完全没有集合通信"

第 12 节那张速查表里,PP 那一行原本写的是"无集合通信"。看到 all_gather_group 之后, 这句话需要更精确:

视角PP 打开时看到什么
pp_group 内部只有 send / recv, 没有任何 collective —— 这一点成立
attn_tp_group 内部每跨一条 stage 边界, 多一次 all-gather(接收端拼接切片)
整体PP 不减少"stage 之间"的传输量,但它把一跳 p2p 拆成了 "1/P 的 p2p + 一次 all-gather";而这次 all-gather 是硬性的正确性要求, 不是可选的优化

所以更准确的说法是:PP 的对外接口是 p2p,PP + TP 的内部实现是 p2p 套 all-gather。 对第 10 节那张通信清单的影响也有两处,方向相反:

12并行配置速查:哪种并行触发哪条原语

把这页的结论压成一张表。同一个原语可以由完全不同的并行方式触发, 所以"GLM-5.3 里 allreduce 有几次"这个问题,必须先问并行配置。

并行方式触发的原语 落在哪个 group依据(源码位置)
TP
--tp-size N
allreduce
allgather
tp_group RowParallelLinear / embedding 出口的求和(linear.py:1800); lm_head 的 logits 拼接(logits_processor.py:939)
DP attention
--attn-dp-size
allreduce
allgather
reduce_scatter
attn_tp_group attn_tp_size = tp_size // attn_cp_size // attn_dp_size (parallel_state.py:2599-2601);dp_gather() / dp_reduce_scatterv() 在 layer_boundary/ops.py:249 起
EP
--moe-a2a-backend
all2all × 2
+ 可能的 allreduce
moe_ep_group FusedMoE.forward_impl(layer.py:1578): dispatch → GEMM → combine; ep_size := tp_size(overrides.py:1612)
PP
--pp-size N
p2p(send/recv)
+ 接收端一次 all-gather
pp_group(p2p)
attn_tp_group(拼接)
residual_batch.to_pp() / attn_boundary.from_pp() (glm5_next.py:1140-1143、:1220-1221)→ send_tensor_dict()(parallel_state.py:1796)。 pp_group 内没有 collective,但每跳的接收端会 all-gather —— 详见 第 11 节
CP
--attn-cp-size
allgather
reduce_scatter
attn_cp_group cp_gather_full_sequence_states / cp_shard_hidden_states (ops.py 的 import 与 cp_gather_in_token_order()); CP 是 tp_size 的一个因子,不额外占卡
SP
sequence parallel
scatter
allgather
tp_group BatchVariant.SEQUENCE_PARALLEL(contracts.py:56); norm 之后行被切开,层尾再拼回

PP 那一行值得单独记住,也值得纠正一次:pp_group 内部确实只发 p2p,一条 collective 都没有; 但在 PP + TP 下,send_tensor_dict() 走的是"每 rank 发 1/P 切片 + 接收端 all-gather", 所以每跨一条 stage 边界都会多一次 allgather(见 第 11 节)。 "PP 不降低 stage 之间的传输量"成立,"PP 一点集合通信都没有"不成立。

13常见误解

all2all 就是"更通用的 allgather",因为两者字节数一样的。

两者字节数相同(都是 (N−1)/N·n),语义完全不同。

allgather 之后每个 rank 都持有全量、且内容一致,产物可以在 rank 之间互换; all2all 之后每个 rank 持有的是输入矩阵的一列,互换就是错的。 第 09 节第 5 小节那处 _tp_lm_head_all_to_all 能换来换去,是因为那里 下游只需要自己那一片,不是因为两者等价。

既然 allreduce = reduce_scatter + allgather,那拆开肯定更快。

拆开不会降低总线字节数 —— 两段加起来正好等于一次 ring allreduce。

收益只能来自别的地方:中间那一步只有 n/N 的行,norm 与残差可以做在更小的张量上; 这一段可以和下一层的计算重叠;还能被融合进一个 kernel。 --boundary-reduction 的 help 里写的是 ar uses all-reduce then token redistribution —— "token redistribution"就是拆开之后必须补的那笔开销,说明拆开是有代价的。

开了 EP / A2A 之后,MoE 层就没有 allreduce 了。

要看 reduce_results 与 moe_tp_size / moe_ep_size。

layer.py:1612 那一行是 if self.reduce_results and (self.moe_tp_size > 1 or self.moe_ep_size > 1): —— 条件成立时 combine 之后仍然会有一次 tensor_model_parallel_all_reduce。 GLM-5.3 之所以没有,是因为它在构造时传了 reduce_results=False(glm5_next.py:758), 把这次求和交给了边界层,不是因为它开了 A2A。

给了 --ep-size 8 之后 MoE 走专家并行,那 42 次 MoE 的 allreduce 就没了。

次数不变,变的只是它落在哪个 group、叫什么名字。

moe_tp_size = tp_size // moe_ep_size // moe_dp_size (runtime_context.py:154)。--ep-size 8 把它从 8 变成 1,于是 moe/utils.py:878-885 的两个分支对调:reduce_ep 为真走 moe_expert_parallel_all_reduce,reduce_tp 为假不再走 moe_tensor_model_parallel_all_reduce —— 还是一层一次。 真要消掉它,只能开 A2A 后端,让求和并进 dispatch/combine;代价是每层多出两次变长 all2all。

--boundary-reduction 对 GLM-5.3 解析成 rs+rsv, 所以它的层尾根本不是 allreduce,是 reduce-scatter。

解析成 rs+rsv 只是允许 reduce-scatter;走不走还要看布局。

_select_exit_move() 在 produced.layout == residual 时直接 返回 ExitMove(keep_output)(boundary.py:724-726)。纯 TP8、行没被切开时 条件成立,求和因此延后到下一层入口,以 all-reduce 兑现(prepare.py:163-170)。 reduce-scatter 只在行真的被切开(SP / INPUT_SCATTERED)时才启动。 "配置允许"和"这次请求走了"是两件事。

PP 只做点对点,所以开 PP 之后通信和集合通信没关系了。

pp_group 内部只发 p2p,但 PP + TP 下每一跳都套着一次 all-gather。

send_tensor_dict(..., all_gather_group=attn_tp_group) 里,发送端 tensor.reshape(all_gather_size, -1)[all_gather_rank] 只发 1/P 切片 (parallel_state.py:1841-1843),接收端 all_gather_group.all_gather(tensor, dim=0) 拼回(:1903)。而且这个协议对数据有硬要求:拼出来的必须是对的,所以 to_pp() 会在出口把每一笔欠的 sum 都结清——包括声明为 always_partial 的。

14自测

N = 8 的 TP 组上,一次 all_reduce 搬多少字节?换成 reduce_scatter + all_gather 呢?

两者都是 2·(N−1)/N·n = 1.75n。 all_reduce 一次搬 1.75n;拆开是 0.875n + 0.875n。 总额一样,差别在于中间那一步只有 n/8 的数据量可以做别的事。

为什么 VocabParallelEmbedding 用 all_reduce,而 lm_head 之后的 logits 用 all_gather?

因为输出布局不同。embedding 的输出是 [T, H],hidden 维没切, 每个 rank 算出来的是"只有自己词表分片那几行非零"的 partial —— 求和即真值。 logits 是 [T, V/P],V 维被切了,每列都是独立值 —— 只能拼接。 同一份词表并行布局,两个出口、两个原语。

在 GLM-5.3 的默认 H200 配方里,MoE 层会不会出现 all2all?为什么?

不会。配方只给了 --tp-size 8,--moe-a2a-backend 取默认 none,create_moe_dispatcher() 于是返回 StandardDispatcher —— 它的 dispatch / combine 不做跨 rank 交换,MoE 在 TP 上切专家。 要出现 all2all,必须显式给 --moe-a2a-backend deepep 之类的值。

为什么开了 A2A 之后,capture_output() 里反而多了一次 all_gather?

因为 A2A 把 token 按专家搬散了,MoE 层输出时每个 rank 不再持有完整序列; 而 aux hidden state 要喂给草稿模型,必须��完整序列。 所以 glm5_next.py:1191 在 enable_a2a_moe and i > first_k_dense_replace 时补一次 attn_tp_group.all_gather(..., dim=0),沿 token 维拼回来。 ——这是"置换"与"复制"两种语义在同一份 forward 里同时出现的实例。

PP 用的是 send/recv,那为什么 to_pp() 还要先把 所有 partial 求和收干净?

因为 PP + TP 下的 p2p 不是裸点对点:发送端只发本 attn-TP rank 的 1/P 切片, 接收端用 all_gather 拼回整张。all-gather 只是"把几片拼起来",不会求和, 所以每一片必须本身已经是完整值,否则拼出来的是错的。 to_pp() 的 docstring 把这条前提写死了: Every sum the output owes is completed before transport, a declared one too. —— 换句话说,PP 把"延后求和"这个优化给关掉了。

同分类的其他条目