H7Hard★ 高频大厂真题 · 分布式并行Part H · 优化器与训练系统

Megatron 张量并行(Column/Row Parallel Linear)

⚡闪卡盲测➔

第一层按列切分免通信、第二层按行切分合并一次 All-Reduce 的 Megatron-LM 经典两层 MLP 并行切分。

⏱️ 时间复杂度: O(B * D * H / N) 计算每卡 + 1 次 All-Reduce
💾 空间复杂度: O(D * H / N) 权重分片显存
🎯 免登录实战自测闭环(先做再看答案)
按「机制回忆 → 关键行填空 → 边界反例 → 追问与错题记录」顺序自测,进度自动保存在本地。
Step 1 · 机制口述与数值稳定性自检
Step 2 · 核心代码关键行补全
import numpy as np
def tp_mlp_forward(x: np.ndarray, W1_shards: list, W2_shards: list) -> np.ndarray:
"""
Megatron-style Tensor Parallel 2-layer MLP across N ranks:
1) First Linear splits columns: W1_shards[r] has shape (D, H // N)
Each rank computes local activation independently (zero communication).
2) Second Linear splits rows: W2_shards[r] has shape (H // N, D)
Each rank computes partial output, followed by a single sum All-Reduce.
"""
partial_outputs = []
for W1_r, W2_r in zip(W1_shards, W2_shards):
# Column-Parallel: X @ W1_r -> (B, H // N), followed by ReLU activation
h_local =
# Row-Parallel: h_local @ W2_r -> (B, D)
partial_outputs.append(h_local @ W2_r)
# Single All-Reduce (sum across ranks)
return
Step 3 · 反例与边界断言核对
Step 4 · 面试追问盲答与错题记录
Q1: 一个 Transformer Block(Self-Attention + MLP)在前向传播中总共需要几次 All-Reduce?反向传播呢?
下一题: ZeRO-1/2/3 显存切分与每卡模型状态定量计算 →
💡

实战一句话记忆口诀

前层按列切免通信,后层按行切配分片,块末一次全归约,跨卡不出 NVLink 域

📐 核心数学公式与机理推导

Y=GeLU(X[A1,A2])[B1B2]=∑r=1NGeLU(XAr)BrY = \mathrm{GeLU}(X [A_1, A_2]) \begin{bmatrix} B_1 \\ B_2 \end{bmatrix} = \sum_{r=1}^{N} \mathrm{GeLU}(X A_r) B_r
### Column-Parallel + Row-Parallel 最小化通信推导
若两个相邻线性层都按行切分,层间必须先同步拼接激活张量再往下算,每次前向都要多一次通信。
Megatron-LM 利用分块矩阵乘法结合律将 MLP 通信压缩为每层块仅 1 次 All-Reduce:
1. 第一层(Column-Parallel):把权重按列切成 NN 份 A=[A1,…,AN]A = [A_1, \dots, A_N]。每张卡 rr 本地计算 Hr=σ(XAr)H_r = \sigma(X A_r)。因为逐元素非线性激活 σ(⋅)\sigma(\cdot) 在列分片上完全可独立完成,层间不需要通信;
2. 第二层(Row-Parallel):把权重按行切成对应的 NN 份 B=[B1;… ;BN]B = [B_1; \dots; B_N],每张卡原地相乘得到局部和 Yr=HrBrY_r = H_r B_r;
3. 单次归约:对各卡的 YrY_r 执行一次 All-Reduce(求和)即得完整精确结果 Y=∑rYrY = \sum_r Y_r。

🔄 张量维度与形状流转说明

X:(B,D) 广播 -> ColLinear W1_r:(D,H/N) -> local act:(B,H/N) -> RowLinear W2_r:(H/N,D) -> partial:(B,D) -> AllReduce(sum) -> Y:(B,D)

🛡️ 数值稳定性自检与边界要点

  • 第一层按列切分 axis=1,第二层必须按行切分 axis=0,且维度 H 需能被 TP 度 NN 整除
  • 非逐元素操作(如 LayerNorm/Dropout)不能直接夹在两个分片层之间而不同步;Sequence Parallelism 常在此基础上按序列维度切分 LN/Dropout 激活
  • TP 因需要每层前反向高频 All-Reduce,通常严格限制在单机 NVLink 节点内(如 TP=4 或 TP=8),跨机改用 PP/DP

💻 完整参考代码实现

import numpy as np

def tp_mlp_forward(x: np.ndarray, W1_shards: list, W2_shards: list) -> np.ndarray:
    """
    Megatron-style Tensor Parallel 2-layer MLP across N ranks:
    1) First Linear splits columns: W1_shards[r] has shape (D, H // N)
       Each rank computes local activation independently (zero communication).
    2) Second Linear splits rows: W2_shards[r] has shape (H // N, D)
       Each rank computes partial output, followed by a single sum All-Reduce.
    """
    partial_outputs = []
    for W1_r, W2_r in zip(W1_shards, W2_shards):
        # Column-Parallel: X @ W1_r -> (B, H // N), followed by ReLU activation
        h_local = np.maximum(0.0, x @ W1_r)
        # Row-Parallel: h_local @ W2_r -> (B, D)
        partial_outputs.append(h_local @ W2_r)
    # Single All-Reduce (sum across ranks)
    return np.sum(partial_outputs, axis=0)

🧪 本地测试与正确性断言

可直接复制到本地 Python / Jupyter 验证:

import numpy as np
np.random.seed(42)
B, D, H, N = 4, 8, 16, 4
x = np.random.randn(B, D)
W1 = np.random.randn(D, H)
W2 = np.random.randn(H, D)
ref = np.maximum(0.0, x @ W1) @ W2
W1_shards = np.split(W1, N, axis=1)
W2_shards = np.split(W2, N, axis=0)
tp_out = tp_mlp_forward(x, W1_shards, W2_shards)
assert np.allclose(tp_out, ref, atol=1e-10), "Tensor-parallel MLP must match unsharded MLP"
print("✓ Megatron Tensor-Parallel MLP assertion passed")

🎯 核心工程追问与标准应答

Q1:一个 Transformer Block(Self-Attention + MLP)在前向传播中总共需要几次 All-Reduce?反向传播呢?
前向传播一共 2 次 All-Reduce(Attention 末尾 Row-Parallel W_O 后 1 次,MLP 末尾 Row-Parallel W_2 后 1 次)。对应地在反向传播中,前向的广播等价算子 f 变成反传的 All-Reduce,前向 All-Reduce 算子 g 在反传时只需恒等传递,因此反传也是 2 次,整块合计 4 次(若开启 Sequence Parallelism 则由 All-Gather + Reduce-Scatter 替代)。
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!
🎯 立即在闪卡中盲测此题➔
← 上一题: Ring All-Reduce 环形集合通信算法返回 Part H 与全部 105 题下一题: ZeRO-1/2/3 显存切分与每卡模型状态定量计算 →