Track X · Agent RL Frameworks · 03/07

학습 병렬화 — TP, PP, EP, CP, DP와 ZeRO·FSDPTraining parallelism — TP, PP, EP, CP, DP with ZeRO and FSDP

RL trainer가 모델을 GPU 여러 장에 나누는 다섯 가지 축 — 데이터(DP, ZeRO, FSDP), 층 내부(Megatron TP), 층의 순서(PP와 그 스케줄), expert(EP), 토큰(CP, Ulysses) — 을 메모리 식과 통신량 식으로 유도하고, column→row 분할이 dense matmul과 같다는 것, pipeline bubble 공식, ring attention이 full attention과 같다는 것을 NumPy로 확인한다.Derives, with memory and communication formulas, the five axes along which an RL trainer splits a model over GPUs — data (DP, ZeRO, FSDP), inside a layer (Megatron TP), the layer sequence (PP and its schedules), experts (EP) and tokens (CP, Ulysses) — and checks in NumPy that the column→row split equals the dense matmul, that pipeline bubbles follow their formulas, and that ring attention equals full attention.

45 분min tensor parallel · pipeline parallel · expert parallel · context parallel · ZeRO · FSDP · Megatron · memory · communication 먼저 볼 것:Before this: Transformer 블록 해부Anatomy of a Transformer block, 학습 step 해부 — rollout, mini-batch, micro-batchAnatomy of a training step — rollout, mini-batch, micro-batch

The previous lesson treated “a GPU” as one place that holds the model and runs micro-batches. For anything beyond a few billion parameters that is false, and the RL trainer’s first configuration decision is how to cut the model. This lesson derives the memory and communication of each cut, so that settings like tensor_model_parallel_size=2, pipeline_model_parallel_size=2, context_parallel_size=2, expert_model_parallel_size=4 (the Megatron layout of the Qwen3.5-35B-A3B benchmark in verl’s V1 async-trainer docs) read as a set of trade-offs rather than magic numbers. The serving side of the same ideas is in parallelism for inference; MoE routing itself is in MoE.

The budget: 16 bytes per parameter before any activation

Mixed-precision Adam keeps, per parameter, bf16 weights (2 bytes), bf16 gradients (2), and fp32 master weights, first and second moments (4 + 4 + 4). That is the ZeRO paper’s accounting, 16Ψ16\Psi bytes for Ψ\Psi parameters. Qwen3-8B has Ψ=8.19\Psi = 8.19B (from its config.json: 36 layers, hidden 4096, FFN 12288, vocabulary 151,936, untied embeddings), so its training state is 131 GB — more than an 80 GB GPU before a single activation is stored. RL adds three pressures on top: sequences are long (thousands to hundreds of thousands of tokens per trajectory), a colocated rollout engine wants part of the same GPU memory for its KV cache, and a reference policy may need to be resident too.

There are five things one can cut: the batch (data parallelism, optionally sharding the 16 bytes: ZeRO/FSDP), the inside of a layer (tensor parallelism), the stack of layers (pipeline parallelism), the experts of an MoE layer (expert parallelism) and the sequence (context/sequence parallelism). Their product must equal the GPU count; in Megatron’s notation N=TP⋅CP⋅DP⋅PPN = \text{TP}\cdot\text{CP}\cdot\text{DP}\cdot\text{PP}, and EP folds onto the same GPUs (below).

Data parallelism and ZeRO / FSDP

Plain data parallelism replicates everything and averages gradients with an all-reduce. A ring all-reduce of a buffer of XX bytes sends 2N−1NX2\frac{N-1}{N}X bytes per GPU (a reduce-scatter followed by an all-gather), independent of NN for large NN. ZeRO removes the redundancy by sharding the model states over the NN data-parallel ranks:

ZeRO-1: 4Ψ+12ΨN,ZeRO-2: 2Ψ+14ΨN,ZeRO-3 / FSDP: 16ΨN bytes per GPU.\text{ZeRO-1: } 4\Psi + \tfrac{12\Psi}{N}, \qquad \text{ZeRO-2: } 2\Psi + \tfrac{14\Psi}{N}, \qquad \text{ZeRO-3 / FSDP: } \tfrac{16\Psi}{N}\ \text{bytes per GPU.}

ZeRO-1 and -2 cost no extra communication (the reduce-scatter of gradients and all-gather of updated weights are exactly the two halves of the all-reduce). ZeRO-3 must also all-gather the weights before each layer’s forward and again before its backward: 3N−1NΨ3\frac{N-1}{N}\Psi elements instead of 2N−1NΨ2\frac{N-1}{N}\Psi, i.e. 1.5× — and, with gradient accumulation, per micro-batch unless the gathered weights are kept. PyTorch FSDP is ZeRO-3 (FSDP2 shards each parameter as a DTensor along dim 0). Megatron’s “distributed optimizer” is ZeRO-1 over the DP × CP ranks.

NumPy Model-state memory: parameter counts from config.json and the ZeRO stages
import numpy as np

# parameter counts from the official config.json values
cfgs = {"Qwen3-8B":        dict(h=4096, L=36, nq=32, nkv=8, hd=128, f=12288, V=151936, E=0,   fm=0),
        "Qwen3-32B":       dict(h=5120, L=64, nq=64, nkv=8, hd=128, f=25600, V=151936, E=0,   fm=0),
        "Qwen3-30B-A3B":   dict(h=2048, L=48, nq=32, nkv=4, hd=128, f=6144,  V=151936, E=128, fm=768),
        "Qwen3-235B-A22B": dict(h=4096, L=94, nq=64, nkv=4, hd=128, f=12288, V=151936, E=128, fm=1536)}

def params(c):
    attn = 2 * c["h"] * c["nq"] * c["hd"] + 2 * c["h"] * c["nkv"] * c["hd"]
    mlp = c["E"] * 3 * c["h"] * c["fm"] + c["h"] * c["E"] if c["E"] else 3 * c["h"] * c["f"]
    return c["L"] * (attn + mlp) + 2 * c["V"] * c["h"]      # untied input embedding + LM head (norms ignored)

def zero_bytes(psi, N, stage):
    """ZeRO paper accounting: bf16 weights (2) + bf16 grads (2) + fp32 master/m/v (12) bytes per param"""
    return {0: 16 * psi, 1: 4 * psi + 12 * psi / N, 2: 2 * psi + 14 * psi / N, 3: 16 * psi / N}[stage]

for name, c in cfgs.items():
    psi = params(c)
    row = "  ".join(f"ZeRO-{s}: {zero_bytes(psi, 8, s) / 1e9:6.1f} GB" for s in (0, 1, 2, 3))
    print(f"{name:<16} {psi / 1e9:6.2f}B params | 8 GPUs, model states per GPU  {row}")

# data-parallel traffic per GPU per optimizer step (ring algorithms, bf16 = 2 bytes)
psi, N = params(cfgs["Qwen3-8B"]), 8
allreduce = 2 * (N - 1) / N * psi * 2          # = reduce-scatter + all-gather
zero3 = 3 * (N - 1) / N * psi * 2              # all-gather (fwd) + all-gather (bwd) + reduce-scatter
print(f"\nQwen3-8B, DP=8: DDP/ZeRO-1/2 send {allreduce / 1e9:.1f} GB per step, ZeRO-3 {zero3 / 1e9:.1f} GB "
      f"(x{zero3 / allreduce:.2f}) - once per step only if parameters stay gathered across micro-batches")
 

The counts reproduce the model names (8.19B, 32.8B, 30.5B, 235.1B), which is a cheap check that the shapes are right. One 8-GPU node trains Qwen3-8B only with ZeRO-2 or -3, and no amount of data-parallel sharding on one node fits the 235B model: something has to cut the model itself.

앞 레슨은 “GPU”를 모델을 담고 micro-batch를 돌리는 한 장소로 다뤘다. 매개변수가 수십억 개를 넘으면 그 가정은 틀리고, RL trainer의 첫 설정 결정은 모델을 어떻게 자를지다. 이 레슨은 자르는 방법마다 메모리와 통신을 유도한다. 그러면 tensor_model_parallel_size=2, pipeline_model_parallel_size=2, context_parallel_size=2, expert_model_parallel_size=4(verl V1 async trainer 문서의 Qwen3.5-35B-A3B 벤치마크의 Megatron 배치) 같은 설정이 마법의 숫자가 아니라 trade-off의 묶음으로 읽힌다. 같은 아이디어의 서빙 쪽은 추론 병렬화에, MoE routing 자체는 MoE에 있다.

예산: activation 이전에 매개변수당 16바이트

mixed precision Adam은 매개변수 하나마다 bf16 가중치(2바이트), bf16 기울기(2), fp32 master 가중치와 1·2차 모멘트(4 + 4 + 4)를 둔다. ZeRO 논문의 회계로 매개변수 Ψ\Psi개에 16Ψ16\Psi바이트다. Qwen3-8B는 Ψ=8.19\Psi = 8.19B(config.json 기준 36층, hidden 4096, FFN 12288, 어휘 151,936, embedding 비공유)이므로 학습 상태가 131 GB다. activation을 하나도 담기 전에 80 GB GPU를 넘는다. RL은 여기에 압력을 셋 더 얹는다. 시퀀스가 길고(trajectory 하나에 수천에서 수십만 토큰), 같은 GPU에 colocate된 rollout 엔진이 KV cache용 메모리를 원하며, reference 정책도 올려 둬야 할 수 있다.

자를 수 있는 것은 다섯 가지다. 배치(data parallelism, 그리고 16바이트를 나누는 ZeRO/FSDP), 층 내부(tensor parallelism), 층의 쌓임(pipeline parallelism), MoE 층의 expert(expert parallelism), 시퀀스(context/sequence parallelism). 이들의 곱이 GPU 수와 같아야 한다. Megatron 표기로 N=TP⋅CP⋅DP⋅PPN = \text{TP}\cdot\text{CP}\cdot\text{DP}\cdot\text{PP}이고, EP는 같은 GPU 위에 접혀 들어간다(뒤에서 설명).

Data parallelism과 ZeRO / FSDP

평범한 data parallelism은 모든 것을 복제하고 all-reduce로 기울기를 평균한다. XX바이트 버퍼의 ring all-reduce는 GPU당 2N−1NX2\frac{N-1}{N}X바이트를 보낸다(reduce-scatter 다음 all-gather). NN이 크면 NN과 무관하다. ZeRO는 model state를 data-parallel rank NN개에 나눠 중복을 없앤다.

ZeRO-1: 4Ψ+12ΨN,ZeRO-2: 2Ψ+14ΨN,ZeRO-3 / FSDP: 16ΨN GPU당 바이트.\text{ZeRO-1: } 4\Psi + \tfrac{12\Psi}{N}, \qquad \text{ZeRO-2: } 2\Psi + \tfrac{14\Psi}{N}, \qquad \text{ZeRO-3 / FSDP: } \tfrac{16\Psi}{N}\ \text{GPU당 바이트.}

ZeRO-1과 -2는 통신이 늘지 않는다(기울기의 reduce-scatter와 갱신된 가중치의 all-gather가 정확히 all-reduce의 두 반쪽이다). ZeRO-3는 층마다 forward 전에, backward 전에 다시 가중치를 all-gather해야 한다. 2N−1NΨ2\frac{N-1}{N}\Psi 대신 3N−1NΨ3\frac{N-1}{N}\Psi개 원소, 즉 1.5배이고, 기울기 누적을 하면 모은 가중치를 유지하지 않는 한 micro-batch마다 든다. PyTorch FSDP가 ZeRO-3다(FSDP2는 매개변수마다 dim 0을 따라 DTensor로 나눈다). Megatron의 “distributed optimizer”는 DP × CP rank에 대한 ZeRO-1이다.

NumPy model state 메모리: config.json에서 센 매개변수와 ZeRO 단계
import numpy as np

# 공식 config.json 값으로 센 매개변수 수
cfgs = {"Qwen3-8B":        dict(h=4096, L=36, nq=32, nkv=8, hd=128, f=12288, V=151936, E=0,   fm=0),
        "Qwen3-32B":       dict(h=5120, L=64, nq=64, nkv=8, hd=128, f=25600, V=151936, E=0,   fm=0),
        "Qwen3-30B-A3B":   dict(h=2048, L=48, nq=32, nkv=4, hd=128, f=6144,  V=151936, E=128, fm=768),
        "Qwen3-235B-A22B": dict(h=4096, L=94, nq=64, nkv=4, hd=128, f=12288, V=151936, E=128, fm=1536)}

def params(c):
    attn = 2 * c["h"] * c["nq"] * c["hd"] + 2 * c["h"] * c["nkv"] * c["hd"]
    mlp = c["E"] * 3 * c["h"] * c["fm"] + c["h"] * c["E"] if c["E"] else 3 * c["h"] * c["f"]
    return c["L"] * (attn + mlp) + 2 * c["V"] * c["h"]      # 비공유 입력 embedding + LM head (norm 무시)

def zero_bytes(psi, N, stage):
    """ZeRO 논문 회계: 매개변수당 bf16 가중치(2) + bf16 기울기(2) + fp32 master/m/v(12) 바이트"""
    return {0: 16 * psi, 1: 4 * psi + 12 * psi / N, 2: 2 * psi + 14 * psi / N, 3: 16 * psi / N}[stage]

for name, c in cfgs.items():
    psi = params(c)
    row = "  ".join(f"ZeRO-{s}: {zero_bytes(psi, 8, s) / 1e9:6.1f} GB" for s in (0, 1, 2, 3))
    print(f"{name:<16} {psi / 1e9:6.2f}B params | 8 GPUs, model states per GPU  {row}")

# optimizer step당 GPU당 data-parallel 통신량 (ring 알고리즘, bf16 = 2바이트)
psi, N = params(cfgs["Qwen3-8B"]), 8
allreduce = 2 * (N - 1) / N * psi * 2          # = reduce-scatter + all-gather
zero3 = 3 * (N - 1) / N * psi * 2              # all-gather(fwd) + all-gather(bwd) + reduce-scatter
print(f"\nQwen3-8B, DP=8: DDP/ZeRO-1/2 send {allreduce / 1e9:.1f} GB per step, ZeRO-3 {zero3 / 1e9:.1f} GB "
      f"(x{zero3 / allreduce:.2f}) - once per step only if parameters stay gathered across micro-batches")
 

센 값이 모델 이름(8.19B, 32.8B, 30.5B, 235.1B)을 재현한다. shape가 맞는지 확인하는 값싼 방법이다. 8-GPU 노드 하나로 Qwen3-8B를 학습하려면 ZeRO-2나 -3가 필요하고, 노드 하나에서는 data-parallel 분할을 아무리 해도 235B 모델이 들어가지 않는다. 모델 자체를 잘라야 한다.

Tensor parallelism: cut inside the layer

Megatron’s observation is that a transformer MLP Y=ϕ(XA) BY = \phi(XA)\,B splits with one collective per forward if the first matrix is cut by columns and the second by rows. Write A=[A1,…,At]A = [A_1, \dots, A_t] (column blocks) and B=[B1;… ;Bt]B = [B_1; \dots; B_t] (matching row blocks). Rank ii computes

Yi=ϕ(XAi) Bi,Y=∑i=1tYi,Y_i = \phi(X A_i)\,B_i ,\qquad Y = \sum_{i=1}^{t} Y_i ,

which is exact because ϕ\phi acts elementwise, so ϕ(XA)=[ϕ(XA1),…,ϕ(XAt)]\phi(XA) = [\phi(XA_1), \dots, \phi(XA_t)], and a block row times a block column is a sum of block products. The only communication is the sum — an all-reduce of XX‘s shape. Attention splits the same way along heads: WQ,WK,WVW_Q, W_K, W_V by columns (each rank owns nq/tn_q/t query heads and their KV heads), the output projection WOW_O by rows. Cutting the first matrix by rows instead would put a sum inside ϕ\phi, which needs a second all-reduce.

Per layer and micro-batch that is two all-reduces in the forward pass (attention, MLP) and two in the backward, each of s hs\,h bf16 values. Sequence parallelism (Korthikanti et al.) replaces each all-reduce by a reduce-scatter + all-gather of the same total volume and in exchange shards the layer-norm and dropout activations along the sequence, so all activation memory is divided by tt. Because these collectives are on the critical path of every layer, TP lives inside a node on NVLink; at 8 GPUs per node, TP ≤ 8. Head counts must divide: Qwen3-8B’s 32 query heads allow TP up to 32, its 8 KV heads up to 8 before KV heads must be replicated.

NumPy Column→row TP equals the dense layer; heads split exactly
import numpy as np
rng = np.random.default_rng(0)

# ---- Megatron MLP: column-parallel W1, row-parallel W2, one all-reduce ----
b, h, f, tp = 6, 32, 128, 4
X = rng.normal(size=(b, h))
W1 = rng.normal(size=(h, f)) / np.sqrt(h)
W2 = rng.normal(size=(f, h)) / np.sqrt(f)
gelu = lambda z: 0.5 * z * (1 + np.tanh(0.7978845608 * (z + 0.044715 * z ** 3)))

Y_dense = gelu(X @ W1) @ W2

W1_shards = np.split(W1, tp, axis=1)          # column split: each rank owns f/tp output features
W2_shards = np.split(W2, tp, axis=0)          # row split: each rank owns the matching f/tp input rows
partials = [gelu(X @ A) @ B for A, B in zip(W1_shards, W2_shards)]   # no communication so far
Y_tp = np.sum(partials, axis=0)               # the single all-reduce (sum) per MLP
print(f"MLP  column->row TP={tp}: max |Y_tp - Y_dense| = {np.abs(Y_tp - Y_dense).max():.2e}")

# the other order fails: a row split of W1 needs the sum BEFORE the nonlinearity
X_shards = np.split(X, tp, axis=1)
W1_rows = np.split(W1, tp, axis=0)
wrong = sum(gelu(Xs @ Ws) for Xs, Ws in zip(X_shards, W1_rows)) @ W2
print(f"MLP  row-split first layer (sum after GeLU): max error = {np.abs(wrong - Y_dense).max():.2e}  <- needs an extra all-reduce")

# ---- attention: split heads (column-parallel QKV), row-parallel output projection ----
nh, hd, s = 8, 4, 5
Xs = rng.normal(size=(s, nh * hd))
Wq, Wk, Wv = (rng.normal(size=(nh * hd, nh * hd)) / np.sqrt(nh * hd) for _ in range(3))
Wo = rng.normal(size=(nh * hd, nh * hd)) / np.sqrt(nh * hd)
def softmax(z):
    z = z - z.max(-1, keepdims=True); e = np.exp(z); return e / e.sum(-1, keepdims=True)
def attn(heads):                               # heads: list of head indices this rank owns
    cols = np.concatenate([np.arange(i * hd, (i + 1) * hd) for i in heads])
    Q, K, V = Xs @ Wq[:, cols], Xs @ Wk[:, cols], Xs @ Wv[:, cols]
    outs = []
    for j in range(len(heads)):
        sl = slice(j * hd, (j + 1) * hd)
        outs.append(softmax(Q[:, sl] @ K[:, sl].T / np.sqrt(hd)) @ V[:, sl])
    return np.concatenate(outs, axis=1) @ Wo[cols, :]       # row-parallel Wo: partial sum
full = attn(list(range(nh)))
split = sum(attn(list(range(r * nh // tp, (r + 1) * nh // tp))) for r in range(tp))
print(f"attn heads split over TP={tp}: max error = {np.abs(split - full).max():.2e}")
 

Tensor parallelism: 층 안을 자른다

Megatron의 관찰은 transformer MLP Y=ϕ(XA) BY = \phi(XA)\,B를 첫 행렬은 열로, 둘째 행렬은 행으로 자르면 forward당 collective 하나로 나눌 수 있다는 것이다. A=[A1,…,At]A = [A_1, \dots, A_t](열 블록), B=[B1;… ;Bt]B = [B_1; \dots; B_t](짝이 맞는 행 블록)라 쓰면 rank ii는

Yi=ϕ(XAi) Bi,Y=∑i=1tYiY_i = \phi(X A_i)\,B_i ,\qquad Y = \sum_{i=1}^{t} Y_i

를 계산한다. ϕ\phi가 원소별로 작용하므로 ϕ(XA)=[ϕ(XA1),…,ϕ(XAt)]\phi(XA) = [\phi(XA_1), \dots, \phi(XA_t)]이고, 블록 행 곱하기 블록 열은 블록 곱의 합이니 정확하다. 통신은 합 하나, XX 모양의 all-reduce뿐이다. attention은 head를 따라 똑같이 나뉜다. WQ,WK,WVW_Q, W_K, W_V는 열로(rank마다 query head nq/tn_q/t개와 그 KV head), 출력 projection WOW_O는 행으로 자른다. 첫 행렬을 행으로 자르면 합이 ϕ\phi 안에 들어가서 all-reduce가 하나 더 필요하다.

층과 micro-batch마다 forward에 all-reduce 두 번(attention, MLP), backward에 두 번이고, 각각 bf16 값 s hs\,h개다. sequence parallelism(Korthikanti 등)은 all-reduce를 같은 총량의 reduce-scatter + all-gather로 바꾸고, 그 대가로 layer-norm과 dropout activation을 시퀀스 축으로 나눠 activation 메모리 전체를 tt로 나눈다. 이 collective들이 모든 층의 critical path에 있으니 TP는 노드 안 NVLink 위에 둔다. 노드당 GPU 8개면 TP ≤ 8이다. head 수가 나누어떨어져야 한다. Qwen3-8B의 query head 32개는 TP 32까지, KV head 8개는 8까지 허용하고, 그 이상이면 KV head를 복제해야 한다.

NumPy column→row TP는 dense 층과 같다. head 분할도 정확하다
import numpy as np
rng = np.random.default_rng(0)

# ---- Megatron MLP: column-parallel W1, row-parallel W2, all-reduce 한 번 ----
b, h, f, tp = 6, 32, 128, 4
X = rng.normal(size=(b, h))
W1 = rng.normal(size=(h, f)) / np.sqrt(h)
W2 = rng.normal(size=(f, h)) / np.sqrt(f)
gelu = lambda z: 0.5 * z * (1 + np.tanh(0.7978845608 * (z + 0.044715 * z ** 3)))

Y_dense = gelu(X @ W1) @ W2

W1_shards = np.split(W1, tp, axis=1)          # 열 분할: rank마다 출력 특징 f/tp개
W2_shards = np.split(W2, tp, axis=0)          # 행 분할: 짝이 맞는 입력 행 f/tp개
partials = [gelu(X @ A) @ B for A, B in zip(W1_shards, W2_shards)]   # 여기까지 통신 없음
Y_tp = np.sum(partials, axis=0)               # MLP당 단 한 번의 all-reduce(합)
print(f"MLP  column->row TP={tp}: max |Y_tp - Y_dense| = {np.abs(Y_tp - Y_dense).max():.2e}")

# 반대 순서는 틀린다: W1을 행으로 자르면 비선형 함수 앞에서 합이 필요하다
X_shards = np.split(X, tp, axis=1)
W1_rows = np.split(W1, tp, axis=0)
wrong = sum(gelu(Xs @ Ws) for Xs, Ws in zip(X_shards, W1_rows)) @ W2
print(f"MLP  row-split first layer (sum after GeLU): max error = {np.abs(wrong - Y_dense).max():.2e}  <- needs an extra all-reduce")

# ---- attention: head 분할 (column-parallel QKV), row-parallel 출력 projection ----
nh, hd, s = 8, 4, 5
Xs = rng.normal(size=(s, nh * hd))
Wq, Wk, Wv = (rng.normal(size=(nh * hd, nh * hd)) / np.sqrt(nh * hd) for _ in range(3))
Wo = rng.normal(size=(nh * hd, nh * hd)) / np.sqrt(nh * hd)
def softmax(z):
    z = z - z.max(-1, keepdims=True); e = np.exp(z); return e / e.sum(-1, keepdims=True)
def attn(heads):                               # heads: 이 rank가 가진 head 번호들
    cols = np.concatenate([np.arange(i * hd, (i + 1) * hd) for i in heads])
    Q, K, V = Xs @ Wq[:, cols], Xs @ Wk[:, cols], Xs @ Wv[:, cols]
    outs = []
    for j in range(len(heads)):
        sl = slice(j * hd, (j + 1) * hd)
        outs.append(softmax(Q[:, sl] @ K[:, sl].T / np.sqrt(hd)) @ V[:, sl])
    return np.concatenate(outs, axis=1) @ Wo[cols, :]       # row-parallel Wo: 부분합
full = attn(list(range(nh)))
split = sum(attn(list(range(r * nh // tp, (r + 1) * nh // tp))) for r in range(tp))
print(f"attn heads split over TP={tp}: max error = {np.abs(split - full).max():.2e}")
 

Pipeline parallelism: cut the stack of layers

PP gives each of pp stages L/pL/p consecutive layers and streams mm micro-batches through them; only the activation at a stage boundary crosses GPUs (a point-to-point send of s hs\,h values), so PP tolerates slow inter-node links. The price is the bubble. Let a micro-batch’s forward take tft_f and backward tbt_b on one stage. The last stage cannot start until the first micro-batch has gone through p−1p-1 earlier stages, and the first stage sits idle at the end for the same reason, so each stage idles for (p−1)(tf+tb)(p-1)(t_f + t_b) out of (m+p−1)(tf+tb)(m + p - 1)(t_f + t_b):

bubble fraction=p−1m+p−1(GPipe and 1F1B alike).\text{bubble fraction} = \frac{p-1}{m+p-1}\qquad(\text{GPipe and 1F1B alike}).

GPipe runs all forwards, then all backwards, and holds mm micro-batches of activations. 1F1B (one-forward-one-backward) starts backwards as soon as possible: after a warm-up of p−d−1p - d - 1 forwards, stage dd alternates F and B, so at most p−dp - d micro-batches are in flight — the same bubble with memory bounded by pp instead of mm. Interleaved 1F1B gives each GPU vv non-contiguous chunks of L/(pv)L/(pv) layers; each chunk takes 1/v1/v of the time, which shrinks the bubble to (p−1)/(v m)(p-1)/(v\,m) of the ideal time, at the price of vv times more point-to-point messages, more in-flight activations, and mm a multiple of pp in Megatron’s schedule.

Pipeline parallelism: 층의 쌓임을 자른다

PP는 pp개 stage에 연속한 층 L/pL/p개씩을 주고 micro-batch mm개를 흘려보낸다. stage 경계의 activation만 GPU를 건너므로(값 s hs\,h개의 point-to-point 전송), 노드 사이의 느린 링크도 견딘다. 대가는 bubble이다. stage 하나에서 micro-batch의 forward가 tft_f, backward가 tbt_b 걸린다고 하자. 마지막 stage는 첫 micro-batch가 앞의 p−1p-1개 stage를 지날 때까지 시작하지 못하고, 첫 stage도 같은 이유로 끝에서 논다. 그래서 각 stage는 (m+p−1)(tf+tb)(m + p - 1)(t_f + t_b) 중 (p−1)(tf+tb)(p-1)(t_f + t_b) 동안 논다.

bubble 비율=p−1m+p−1(GPipe와 1F1B 모두).\text{bubble 비율} = \frac{p-1}{m+p-1}\qquad(\text{GPipe와 1F1B 모두}).

GPipe는 forward를 전부 한 뒤 backward를 전부 하고, micro-batch mm개 분량의 activation을 들고 있다. 1F1B(one-forward-one-backward)는 backward를 가능한 한 일찍 시작한다. stage dd는 forward p−d−1p - d - 1번의 warm-up 뒤 F와 B를 번갈아 하므로 in-flight micro-batch가 많아야 p−dp - d개다. bubble은 같고 메모리 상한은 mm이 아니라 pp다. interleaved 1F1B는 GPU마다 L/(pv)L/(pv)층짜리 떨어진 chunk vv개를 준다. chunk 하나가 시간의 1/v1/v를 차지하니 bubble이 이상적 시간의 (p−1)/(v m)(p-1)/(v\,m)로 준다. 대가는 point-to-point 메시지 vv배, 더 많은 in-flight activation, 그리고 Megatron 스케줄에서 mm이 pp의 배수여야 한다는 조건이다.

Rows are pipeline stages (GPUs), time runs right. Blue = forward of a micro-batch, green = its backward (twice as long), white = bubble. The schedule is simulated from each stage's op order and the data dependencies, not drawn from a formula; the formula is printed next to the measured bubble. Compare GPipe and 1F1B at the same m: same bubble, very different peak memory (GPipe keeps all m micro-batches' activations, 1F1B at most p). Interleaving (v chunks per GPU, m a multiple of p) cuts the bubble by v at the cost of more in-flight activations and v× more point-to-point messages. 행은 pipeline stage(GPU), 시간은 오른쪽으로 흐른다. 파랑 = micro-batch의 forward, 초록 = backward(두 배 길다), 흰 칸 = bubble. 스케줄은 공식으로 그린 게 아니라 stage별 연산 순서와 데이터 의존성으로 시뮬레이션한 결과이고, 공식 값은 측정한 bubble 옆에 적었다. 같은 m에서 GPipe와 1F1B를 비교하자. bubble은 같고 최대 메모리는 크게 다르다(GPipe는 m개 micro-batch의 activation을 전부, 1F1B는 많아야 p개를 들고 있다). interleaving(GPU당 chunk v개, m은 p의 배수)은 bubble을 v배 줄이는 대신 activation을 더 들고 있고 point-to-point 메시지가 v배 많아진다.
NumPy Simulating GPipe, 1F1B and interleaved 1F1B from their op orders
import numpy as np

def schedule(p, m, kind, v=1, tf=1.0, tb=2.0):
    """Simulate a pipeline schedule. Returns makespan, bubble fraction, peak in-flight chunks per device.
    kind: 'gpipe' | '1f1b' | 'interleaved' (v model chunks per device, Megatron order; needs m % p == 0)."""
    C = p * v                                   # virtual stages; chunk c lives on device c % p
    tf, tb = tf / v, tb / v                     # a chunk is 1/v of the device's layers
    orders = []
    for d in range(p):
        F = []; B = []
        for k in range(m * v):                  # Megatron's interleaved order (reduces to plain for v=1)
            g, r = divmod(k, p * v)
            mb = g * p + r % p
            F.append(('F', (r // p) * p + d, mb))
            B.append(('B', (v - 1 - r // p) * p + d, mb))
        if kind == 'gpipe':
            orders.append(F + B)
            continue
        warm = min(m * v, (p - d - 1) * 2 + (v - 1) * p if kind == 'interleaved' else p - d - 1)
        o = F[:warm]; fi = warm; bi = 0
        while fi < len(F):
            o.append(F[fi]); fi += 1
            o.append(B[bi]); bi += 1
        o += B[bi:]
        orders.append(o)
    done = {}; free = [0.0] * p; ptr = [0] * p; inflight = [0] * p; peak = [0] * p
    total = sum(len(o) for o in orders)
    while len(done) < total:
        progressed = False
        for d in range(p):
            if ptr[d] == len(orders[d]):
                continue
            op, c, mb = orders[d][ptr[d]]
            deps = [('F', c - 1, mb)] if (op == 'F' and c > 0) else []
            if op == 'B':
                deps = [('B', c + 1, mb)] if c < C - 1 else [('F', c, mb)]
            if all(x in done for x in deps):
                start = max([free[d]] + [done[x] for x in deps])
                free[d] = done[(op, c, mb)] = start + (tf if op == 'F' else tb)
                inflight[d] += 1 if op == 'F' else -1
                peak[d] = max(peak[d], inflight[d])
                ptr[d] += 1; progressed = True
        if not progressed:
            raise RuntimeError("deadlock")
    span = max(free)
    ideal = m * (tf + tb) * v
    return span, 1 - ideal / span, peak

p, m = 4, 8
for kind, v in [('gpipe', 1), ('1f1b', 1), ('interleaved', 2), ('interleaved', 4)]:
    span, bub, peak = schedule(p, m, kind, v)
    if kind == 'interleaved':
        formula = (p - 1) / (v * m) / (1 + (p - 1) / (v * m))   # bubble/ideal = (p-1)/(v m)
    else:
        formula = (p - 1) / (m + p - 1)
    print(f"{kind:<11} v={v}: makespan={span:5.2f}  bubble={bub:.3f} (formula {formula:.3f})  "
          f"peak in-flight micro-batch chunks per device={peak}")
 

The simulated bubbles match the formulas to three digits, and the last column shows the memory side: GPipe holds 8 micro-batches on every stage, 1F1B holds 4, 3, 2, 1, and interleaving holds more chunks (11 half-size chunks on stage 0 is 5.5 micro-batches’ worth at v=2v=2). For RL the bubble matters more than in pre-training, because the number of micro-batches per optimizer step is small: one optimizer step sees b n/Db\,n/D trajectories per data-parallel replica, packed into a handful of token-budget micro-batches. verl’s dynamic batching therefore rounds the micro-batch count up to a multiple of the virtual-pipeline size and puts the lightest micro-batches at both ends of the schedule, where the warm-up and cool-down bubbles are (previous lesson). Megatron also allows uneven stages: verl’s Qwen3-235B-A22B launcher splits 94 layers over PP = 8 as 11 + 6 × 12 + 11 (num_layers_in_first_pipeline_stage=11, num_layers_in_last_pipeline_stage=11), because the first stage also holds the embedding and the last the LM head and loss.

NumPy 연산 순서로 GPipe, 1F1B, interleaved 1F1B 시뮬레이션
import numpy as np

def schedule(p, m, kind, v=1, tf=1.0, tb=2.0):
    """pipeline 스케줄 시뮬레이션. makespan, bubble 비율, device별 최대 in-flight chunk 수를 돌려준다.
    kind: 'gpipe' | '1f1b' | 'interleaved' (device당 chunk v개, Megatron 순서, m % p == 0 필요)."""
    C = p * v                                   # virtual stage 수. chunk c는 device c % p에 있다
    tf, tb = tf / v, tb / v                     # chunk 하나는 device 층의 1/v
    orders = []
    for d in range(p):
        F = []; B = []
        for k in range(m * v):                  # Megatron의 interleaved 순서 (v=1이면 평범한 순서)
            g, r = divmod(k, p * v)
            mb = g * p + r % p
            F.append(('F', (r // p) * p + d, mb))
            B.append(('B', (v - 1 - r // p) * p + d, mb))
        if kind == 'gpipe':
            orders.append(F + B)
            continue
        warm = min(m * v, (p - d - 1) * 2 + (v - 1) * p if kind == 'interleaved' else p - d - 1)
        o = F[:warm]; fi = warm; bi = 0
        while fi < len(F):
            o.append(F[fi]); fi += 1
            o.append(B[bi]); bi += 1
        o += B[bi:]
        orders.append(o)
    done = {}; free = [0.0] * p; ptr = [0] * p; inflight = [0] * p; peak = [0] * p
    total = sum(len(o) for o in orders)
    while len(done) < total:
        progressed = False
        for d in range(p):
            if ptr[d] == len(orders[d]):
                continue
            op, c, mb = orders[d][ptr[d]]
            deps = [('F', c - 1, mb)] if (op == 'F' and c > 0) else []
            if op == 'B':
                deps = [('B', c + 1, mb)] if c < C - 1 else [('F', c, mb)]
            if all(x in done for x in deps):
                start = max([free[d]] + [done[x] for x in deps])
                free[d] = done[(op, c, mb)] = start + (tf if op == 'F' else tb)
                inflight[d] += 1 if op == 'F' else -1
                peak[d] = max(peak[d], inflight[d])
                ptr[d] += 1; progressed = True
        if not progressed:
            raise RuntimeError("deadlock")
    span = max(free)
    ideal = m * (tf + tb) * v
    return span, 1 - ideal / span, peak

p, m = 4, 8
for kind, v in [('gpipe', 1), ('1f1b', 1), ('interleaved', 2), ('interleaved', 4)]:
    span, bub, peak = schedule(p, m, kind, v)
    if kind == 'interleaved':
        formula = (p - 1) / (v * m) / (1 + (p - 1) / (v * m))   # bubble/이상적 시간 = (p-1)/(v m)
    else:
        formula = (p - 1) / (m + p - 1)
    print(f"{kind:<11} v={v}: makespan={span:5.2f}  bubble={bub:.3f} (formula {formula:.3f})  "
          f"peak in-flight micro-batch chunks per device={peak}")
 

시뮬레이션한 bubble이 공식과 세 자리까지 맞고, 마지막 열이 메모리 쪽을 보여 준다. GPipe는 모든 stage가 micro-batch 8개를, 1F1B는 4, 3, 2, 1개를, interleaving은 chunk를 더 많이 든다(v=2v=2에서 stage 0의 반 크기 chunk 11개는 micro-batch 5.5개 분량). RL에서는 bubble이 사전학습보다 더 아프다. optimizer step 하나가 data-parallel replica당 trajectory b n/Db\,n/D개만 보고, 그것이 토큰 예산 micro-batch 몇 개로 묶이기 때문이다. 그래서 verl의 동적 배치는 micro-batch 수를 virtual pipeline 크기의 배수로 올리고, 가장 가벼운 micro-batch를 warm-up·cool-down bubble이 있는 스케줄 양 끝에 둔다(앞 레슨). Megatron은 고르지 않은 stage도 허용한다. verl의 Qwen3-235B-A22B 실행 스크립트는 94층을 PP = 8에 11 + 6 × 12 + 11로 나눈다(num_layers_in_first_pipeline_stage=11, num_layers_in_last_pipeline_stage=11). 첫 stage는 embedding을, 마지막 stage는 LM head와 손실을 함께 들기 때문이다.

Expert parallelism: cut the experts

An MoE layer with EE experts and top-kk routing has far more parameters than any token uses (Qwen3-235B-A22B: 128 experts, top-8, so about 2.4B expert parameters per layer of which a token touches 1/16). EP places E/EPE/\text{EP} whole experts on each GPU of an EP group. Each token’s hidden vector must travel to the GPUs that hold its kk experts and come back: an all-to-all dispatch and an all-to-all combine per MoE layer, each moving k hk\,h values per token, of which a fraction (EP−1)/EP(\text{EP}-1)/\text{EP} leaves the GPU under uniform routing — and the backward pass repeats both. Unlike TP, the volume per token does not shrink as EP grows; what EP buys is expert memory divided by EP. Load imbalance (some GPUs receive many more tokens) turns into stragglers on every MoE layer, which is why routing balance (MoE) is a systems concern, and why RL adds routing replay to keep training and rollout experts consistent (mismatch engineering).

Megatron-Core does not make EP a separate factor of NN. The attention part of each pipeline stage uses the TP×CP×DP\text{TP}\times\text{CP}\times\text{DP} grid, and the MoE part re-reads the same GPUs as an ETP×EP×EDP\text{ETP}\times\text{EP}\times\text{EDP} grid (“MoE parallel folding”), so the constraint is TP⋅CP⋅DP=ETP⋅EP⋅EDP\text{TP}\cdot\text{CP}\cdot\text{DP} = \text{ETP}\cdot\text{EP}\cdot\text{EDP}; expert gradients are then averaged over the expert-data-parallel group EDP. In the verl benchmark layout above (32 GPUs, TP 2, PP 2, CP 2), the attention grid has DP=32/(2⋅2⋅2)=4\text{DP} = 32/(2\cdot2\cdot2) = 4 and 16 GPUs per stage, which EP = 4 folds into.

Context parallelism: cut the sequence

Long trajectories make activations, not weights, the problem: per layer they are linear in tokens even with FlashAttention. Context parallelism gives each of cc ranks s/cs/c tokens of every sequence. Everything except attention is token-local. For attention each rank keeps its queries and passes key/value blocks around a ring; after cc steps every query has seen every key, and partial results are merged with the online-softmax rescaling of FlashAttention (keep the running max mm, normaliser ℓ\ell and accumulator, rescale by emold−mnewe^{m_\text{old}-m_\text{new}}). Communication per layer is (c−1)(c-1) KV blocks per rank — with GQA only 2 nkvdh2\,n_{kv} d_h values per token, much smaller than the hidden state — and overlaps with the block computation. With a causal mask, contiguous chunks give the last rank far more work than the first, so implementations cut the sequence into 2c2c chunks and give rank rr chunks rr and 2c−1−r2c-1-r.

Ulysses sequence parallelism (verl’s ulysses_sequence_parallel_size for FSDP) does it differently: an all-to-all turns “all heads, s/cs/c tokens” into ”h/ch/c heads, all tokens” before attention and back afterwards. Its per-GPU volume stays constant when sequence length and GPU count grow together, but it needs the head count to be divisible by cc. verl’s Megatron backend uses CP (context_parallel_size), and since v0.9.0 it can pick a smaller CP group per packed micro-batch when the sequences in it do not need the full size (dynamic context parallel, verl PR #6555).

NumPy Ring attention with zig-zag chunks equals full causal attention
import numpy as np
rng = np.random.default_rng(3)

s, d, cp = 32, 8, 4                       # sequence, head dim, CP ranks
Q, K, V = (rng.normal(size=(s, d)) for _ in range(3))

def full_causal(Q, K, V):
    S = Q @ K.T / np.sqrt(d)
    S[np.triu_indices(s, 1)] = -np.inf
    P = np.exp(S - S.max(1, keepdims=True))
    return (P / P.sum(1, keepdims=True)) @ V

# load-balanced causal split: 2*cp chunks, rank r holds chunks r and 2cp-1-r
chunks = np.array_split(np.arange(s), 2 * cp)
own = [np.concatenate([chunks[r], chunks[2 * cp - 1 - r]]) for r in range(cp)]

def ring_attention(r):
    q_idx = own[r]
    m = np.full(len(q_idx), -np.inf); l = np.zeros(len(q_idx)); acc = np.zeros((len(q_idx), d))
    for step in range(cp):                # KV block of rank (r - step) arrives at step `step`
        k_idx = own[(r - step) % cp]
        S = Q[q_idx] @ K[k_idx].T / np.sqrt(d)
        S = np.where(k_idx[None, :] <= q_idx[:, None], S, -np.inf)     # causal mask by global position
        m_new = np.maximum(m, S.max(1))
        safe = np.where(np.isfinite(m_new), m_new, 0.0)
        scale = np.exp(np.where(np.isfinite(m), m - safe, -np.inf))     # rescale what we had
        P = np.exp(S - safe[:, None])
        l = l * scale + P.sum(1)
        acc = acc * scale[:, None] + P @ V[k_idx]
        m = m_new
    return q_idx, acc / l[:, None]

ref = full_causal(Q, K, V)
out = np.zeros_like(ref)
for r in range(cp):
    idx, o = ring_attention(r)
    out[idx] = o
print(f"ring attention, CP={cp}: max |out - full| = {np.abs(out - ref).max():.2e}")
work = [sum(((own[(r - st) % cp][None, :] <= own[r][:, None]).sum()) for st in range(cp)) for r in range(cp)]
naive = [np.arange(s).reshape(cp, -1)[r] for r in range(cp)]
work_naive = [int(sum((np.arange(s)[None, :] <= naive[r][:, None]).sum(1))) for r in range(cp)]
print("unmasked score entries per rank, zig-zag split :", [int(w) for w in work])
print("unmasked score entries per rank, contiguous    :", work_naive)
 

Expert parallelism: expert를 자른다

expert EE개와 top-kk routing을 쓰는 MoE 층은 토큰 하나가 쓰는 것보다 훨씬 많은 매개변수를 갖는다(Qwen3-235B-A22B: expert 128개, top-8. 층당 expert 매개변수 약 2.4B 중 토큰 하나가 1/16을 쓴다). EP는 EP 그룹의 GPU마다 온전한 expert E/EPE/\text{EP}개를 둔다. 각 토큰의 hidden vector는 자기 expert kk개가 있는 GPU로 갔다가 돌아와야 한다. MoE 층마다 all-to-all dispatch와 all-to-all combine이 있고, 각각 토큰당 값 k hk\,h개를 옮기며 routing이 고르면 그중 (EP−1)/EP(\text{EP}-1)/\text{EP}가 GPU를 떠난다. backward가 둘 다 되풀이한다. TP와 달리 EP를 키워도 토큰당 통신량은 줄지 않는다. EP가 사 주는 것은 EP로 나뉜 expert 메모리다. 부하 불균형(어떤 GPU가 토큰을 훨씬 많이 받음)은 모든 MoE 층에서 낙오자로 바뀐다. 그래서 routing 균형(MoE)은 시스템 문제이고, RL은 학습과 rollout의 expert 선택을 맞추려고 routing replay를 더한다(mismatch engineering).

Megatron-Core는 EP를 NN의 별도 인수로 만들지 않는다. pipeline stage마다 attention 부분은 TP×CP×DP\text{TP}\times\text{CP}\times\text{DP} 격자를 쓰고, MoE 부분은 같은 GPU를 ETP×EP×EDP\text{ETP}\times\text{EP}\times\text{EDP} 격자로 다시 읽는다(“MoE parallel folding”). 그래서 조건은 TP⋅CP⋅DP=ETP⋅EP⋅EDP\text{TP}\cdot\text{CP}\cdot\text{DP} = \text{ETP}\cdot\text{EP}\cdot\text{EDP}이고, expert 기울기는 expert-data-parallel 그룹 EDP에서 평균한다. 위의 verl 벤치마크 배치(GPU 32개, TP 2, PP 2, CP 2)에서 attention 격자는 DP=32/(2⋅2⋅2)=4\text{DP} = 32/(2\cdot2\cdot2) = 4, stage당 GPU 16개이고, EP = 4가 그 안에 접힌다.

Context parallelism: 시퀀스를 자른다

trajectory가 길면 가중치가 아니라 activation이 문제다. FlashAttention을 써도 층당 activation은 토큰 수에 선형이다. Context parallelism은 rank cc개에게 모든 시퀀스의 토큰 s/cs/c개씩을 준다. attention을 빼면 모든 연산이 토큰별이다. attention에서는 rank마다 자기 query를 들고 key/value 블록을 고리로 돌린다. cc step 뒤에는 모든 query가 모든 key를 봤고, 부분 결과는 FlashAttention의 online softmax 재조정(현재 최댓값 mm, 정규화 상수 ℓ\ell, 누적값을 들고 emold−mnewe^{m_\text{old}-m_\text{new}}로 재조정)으로 합친다. 층당 통신은 rank당 KV 블록 (c−1)(c-1)개이고 — GQA면 토큰당 값 2 nkvdh2\,n_{kv} d_h개로 hidden state보다 훨씬 작다 — 블록 계산과 겹친다. causal mask에서는 연속 chunk로 자르면 마지막 rank가 첫 rank보다 일이 훨씬 많으므로, 구현들은 시퀀스를 chunk 2c2c개로 자르고 rank rr에 chunk rr과 2c−1−r2c-1-r을 준다.

Ulysses sequence parallelism(FSDP용 verl의 ulysses_sequence_parallel_size)은 다르게 한다. attention 앞에서 all-to-all로 “모든 head, 토큰 s/cs/c개”를 “head h/ch/c개, 모든 토큰”으로 바꾸고, 뒤에서 되돌린다. 시퀀스 길이와 GPU 수가 함께 늘면 GPU당 통신량이 일정하지만, head 수가 cc로 나누어떨어져야 한다. verl의 Megatron backend는 CP(context_parallel_size)를 쓰고, v0.9.0부터는 packed micro-batch의 시퀀스들이 CP 전체 크기를 필요로 하지 않으면 micro-batch마다 더 작은 CP 그룹을 고를 수 있다(dynamic context parallel, verl PR #6555).

NumPy zig-zag chunk를 쓴 ring attention은 full causal attention과 같다
import numpy as np
rng = np.random.default_rng(3)

s, d, cp = 32, 8, 4                       # 시퀀스, head 차원, CP rank 수
Q, K, V = (rng.normal(size=(s, d)) for _ in range(3))

def full_causal(Q, K, V):
    S = Q @ K.T / np.sqrt(d)
    S[np.triu_indices(s, 1)] = -np.inf
    P = np.exp(S - S.max(1, keepdims=True))
    return (P / P.sum(1, keepdims=True)) @ V

# 부하 균형 causal 분할: chunk 2*cp개, rank r은 chunk r과 2cp-1-r을 갖는다
chunks = np.array_split(np.arange(s), 2 * cp)
own = [np.concatenate([chunks[r], chunks[2 * cp - 1 - r]]) for r in range(cp)]

def ring_attention(r):
    q_idx = own[r]
    m = np.full(len(q_idx), -np.inf); l = np.zeros(len(q_idx)); acc = np.zeros((len(q_idx), d))
    for step in range(cp):                # step `step`에 rank (r - step)의 KV 블록이 도착한다
        k_idx = own[(r - step) % cp]
        S = Q[q_idx] @ K[k_idx].T / np.sqrt(d)
        S = np.where(k_idx[None, :] <= q_idx[:, None], S, -np.inf)     # 전역 위치 기준 causal mask
        m_new = np.maximum(m, S.max(1))
        safe = np.where(np.isfinite(m_new), m_new, 0.0)
        scale = np.exp(np.where(np.isfinite(m), m - safe, -np.inf))     # 지금까지의 값을 재조정
        P = np.exp(S - safe[:, None])
        l = l * scale + P.sum(1)
        acc = acc * scale[:, None] + P @ V[k_idx]
        m = m_new
    return q_idx, acc / l[:, None]

ref = full_causal(Q, K, V)
out = np.zeros_like(ref)
for r in range(cp):
    idx, o = ring_attention(r)
    out[idx] = o
print(f"ring attention, CP={cp}: max |out - full| = {np.abs(out - ref).max():.2e}")
work = [sum(((own[(r - st) % cp][None, :] <= own[r][:, None]).sum()) for st in range(cp)) for r in range(cp)]
naive = [np.arange(s).reshape(cp, -1)[r] for r in range(cp)]
work_naive = [int(sum((np.arange(s)[None, :] <= naive[r][:, None]).sum(1))) for r in range(cp)]
print("unmasked score entries per rank, zig-zag split :", [int(w) for w in work])
print("unmasked score entries per rank, contiguous    :", work_naive)
 

Putting the axes together

The figure below lays a real model out on a cluster with all five axes and estimates where memory and time go. The activation estimate uses bytes per token per layer of about 15h15h for attention and norms plus 3h+6f3h + 6f for a SwiGLU MLP of width ff (for MoE, 3h+k(2h+6fmoe)3h + k(2h + 6f_\text{moe})), divided by TP under sequence parallelism, times L/PPL/\text{PP} layers and min⁡(PP,m)\min(\text{PP}, m) in-flight micro-batches on stage 0 (1F1B). With full recomputation only the 2h2h-byte layer input is kept per layer. The last stage additionally holds fp32 logits, tokens × 151,936 × 4 bytes (about 10 GB for a 16k-token micro-batch without TP), which is why verl computes log-probs and entropy in chunks or with fused kernels.

축들을 합치기

아래 그림은 실제 모델을 다섯 축으로 클러스터에 배치하고 메모리와 시간이 어디로 가는지 추정한다. activation 추정치는 층당 토큰당 바이트로 attention과 norm에 약 15h15h, 폭 ff인 SwiGLU MLP에 3h+6f3h + 6f(MoE면 3h+k(2h+6fmoe)3h + k(2h + 6f_\text{moe}))를 쓰고, sequence parallelism 아래 TP로 나눈 뒤 L/PPL/\text{PP}층과 stage 0의 in-flight micro-batch min⁡(PP,m)\min(\text{PP}, m)개(1F1B)를 곱했다. full recomputation이면 층마다 2h2h바이트짜리 층 입력만 남긴다. 마지막 stage는 여기에 fp32 logit, 즉 토큰 수 × 151,936 × 4바이트(TP 없이 16k 토큰 micro-batch에 약 10 GB)를 더 든다. verl이 log-prob과 entropy를 chunk 단위나 fused kernel로 계산하는 이유다.

Top: the GPUs (one row per node of 8), coloured by pipeline stage; a dark outline groups one tensor-parallel group. Middle: estimated memory on the busiest GPU (pipeline stage 0) against capacity. Bottom: estimated traffic per optimizer step for each parallelism, coloured by link (NVLink inside a node vs InfiniBand across nodes) with times at 450 / 50 GB/s per GPU. Things to try: put TP = 8 with CP = 2 and watch CP spill onto InfiniBand; raise EP on the 235B model and watch expert memory fall while all-to-all grows; switch to ZeRO-3 to see optimizer state leave and parameter all-gathers appear; raise m to shrink the pipeline bubble. Memory and traffic are first-order estimates (bf16 weights and gradients, fp32 Adam; Korthikanti-style activations with flash attention); real frameworks add buffers and fragmentation. 위: GPU(한 행이 8개짜리 노드 하나)를 pipeline stage 색으로 칠했다. 진한 테두리가 tensor-parallel 그룹 하나다. 가운데: 가장 바쁜 GPU(pipeline stage 0)의 메모리 추정치와 용량. 아래: optimizer step당 병렬화별 통신량 추정치. 색은 링크(노드 안 NVLink, 노드 사이 InfiniBand)이고 시간은 GPU당 450 / 50 GB/s로 계산했다. 해 볼 것: TP = 8에 CP = 2를 두면 CP가 InfiniBand로 넘어간다. 235B 모델에서 EP를 키우면 expert 메모리는 줄고 all-to-all은 는다. ZeRO-3로 바꾸면 optimizer state가 빠지는 대신 parameter all-gather가 생긴다. m을 키우면 pipeline bubble이 준다. 메모리와 통신량은 1차 추정이다(bf16 가중치·기울기, fp32 Adam, flash attention 기준 Korthikanti식 activation). 실제 프레임워크는 버퍼와 단편화가 더해진다.

Some rules fall out of the arithmetic, and they match how current launchers are written:

  • TP stays inside a node and is the first axis to raise when the model’s dense part does not fit; it divides weights, gradients, optimizer state and activations, but its 4 collectives per layer per micro-batch are on NVLink only.
  • PP is the cross-node axis for depth: it divides weights and per-stage activations, costs only boundary sends, and pays in bubbles that RL’s few micro-batches per step make large — so keep m≫pm \gg p or use interleaving.
  • EP is the axis for MoE experts: the only way to divide hundreds of GB of expert weights without TP-splitting each small expert, paid for in all-to-all volume that does not shrink with EP.
  • CP (or Ulysses) is the axis for length: it is what lets a 64k–128k-token trajectory fit, and it only touches attention.
  • DP with sharded state is what remains: the distributed optimizer (ZeRO-1) in Megatron, FSDP/FSDP2 for small and mid-size dense models in verl’s FSDP backend, where TP/PP are not used at all and Ulysses handles length.

The RL-specific twist is that the rollout engine uses a different layout from the trainer — in the benchmark above, training uses TP 2 · PP 2 · CP 2 · EP 4 while vLLM serves with TP 4. Every weight update therefore reshards parameters from one layout to the other (verl’s 3D-HybridEngine when they share GPUs, a checkpoint engine over NCCL/NIXL when they do not). That cost and its engineering belong to the verl lesson and to inference for RL.

PyTorch PyTorch: Megatron-style column- and row-parallel linear layers 로컬에서 실행run locally (pip install torch)
import torch
import torch.distributed as dist
import torch.nn.functional as F

class _CopyToTP(torch.autograd.Function):
    """Megatron's f: identity forward, all-reduce of the input gradient backward."""
    @staticmethod
    def forward(ctx, x, group):
        ctx.group = group
        return x
    @staticmethod
    def backward(ctx, g):
        g = g.clone()
        dist.all_reduce(g, group=ctx.group)
        return g, None

class _ReduceFromTP(torch.autograd.Function):
    """Megatron's g: all-reduce forward, identity backward."""
    @staticmethod
    def forward(ctx, x, group):
        x = x.clone()
        dist.all_reduce(x, group=group)
        return x
    @staticmethod
    def backward(ctx, g):
        return g, None

class ColumnParallelLinear(torch.nn.Module):
    def __init__(self, d_in, d_out, group):
        super().__init__()
        self.group, tp = group, dist.get_world_size(group)
        self.weight = torch.nn.Parameter(torch.empty(d_out // tp, d_in))   # this rank's output rows
        torch.nn.init.normal_(self.weight, std=d_in ** -0.5)
    def forward(self, x):                        # x is replicated on all TP ranks
        return F.linear(_CopyToTP.apply(x, self.group), self.weight)   # output stays sharded

class RowParallelLinear(torch.nn.Module):
    def __init__(self, d_in, d_out, group):
        super().__init__()
        self.group, tp = group, dist.get_world_size(group)
        self.weight = torch.nn.Parameter(torch.empty(d_out, d_in // tp))   # this rank's input columns
        torch.nn.init.normal_(self.weight, std=d_in ** -0.5)
    def forward(self, x_shard):                  # x_shard: the column-parallel output of this rank
        return _ReduceFromTP.apply(F.linear(x_shard, self.weight), self.group)

class TPMLP(torch.nn.Module):                    # one all-reduce forward, one backward
    def __init__(self, h, f, group):
        super().__init__()
        self.up = ColumnParallelLinear(h, f, group)
        self.down = RowParallelLinear(f, h, group)
    def forward(self, x):
        return self.down(F.gelu(self.up(x)))
 
확인 문제Check yourself

An RL trainer uses PP=8 with the 1F1B schedule. Each optimizer step has 8 micro-batches per pipeline. Roughly what fraction of the time is pipeline bubble, and how many micro-batches per step would bring it below 10%?

(p−1)/(m+p−1)=7/15≈47%(p-1)/(m+p-1) = 7/15 \approx 47\%. For ≤10%\le 10\% we need 7/(m+7)≤0.17/(m+7) \le 0.1, i.e. m≥63m \ge 63. With RL’s small per-step batches that many micro-batches is often unavailable, which is why interleaving (vv chunks divide the bubble by vv), fewer pipeline stages, or more TP/EP/CP instead of PP are common choices.

확인 문제Check yourself

Why do launchers keep tensor parallelism within one 8-GPU node, while pipeline parallelism routinely spans nodes?

TP’s collectives are O(L)O(L) per micro-batch and block the next layer’s compute; at InfiniBand’s roughly 9× lower per-GPU bandwidth they dominate the step. PP’s traffic is O(p)O(p) point-to-point messages per micro-batch and overlaps with compute, so it tolerates slower links — its cost is the bubble instead.

Summary

  • Mixed-precision Adam needs about 16Ψ16\Psi bytes of model state; ZeRO-1/2/3 shard it over data-parallel ranks for 0, 0 and 50% extra communication. FSDP is ZeRO-3; Megatron’s distributed optimizer is ZeRO-1 over DP × CP.
  • Megatron TP splits the first matrix of a block by columns and the second by rows, giving exactly one all-reduce per block per pass; sequence parallelism divides all activations by TP. Keep TP inside a node.
  • PP’s bubble is (p−1)/(m+p−1)(p-1)/(m+p-1) for GPipe and 1F1B alike; 1F1B bounds in-flight activations by pp; interleaving divides the bubble by vv at the cost of more messages and memory.
  • EP divides expert memory and costs two all-to-alls per MoE layer per pass; Megatron folds the expert grid onto the attention grid (TP⋅CP⋅DP=ETP⋅EP⋅EDP\text{TP}\cdot\text{CP}\cdot\text{DP} = \text{ETP}\cdot\text{EP}\cdot\text{EDP}).
  • CP (ring attention, zig-zag chunks) or Ulysses (all-to-all over heads) divides sequence length; for long agent trajectories it is often the axis that decides whether training fits.

계산에서 규칙 몇 개가 나오고, 지금의 실행 스크립트들도 그렇게 쓰여 있다.

  • TP는 노드 안에 둔다. 모델의 dense 부분이 안 들어갈 때 먼저 키우는 축이다. 가중치, 기울기, optimizer state, activation을 모두 나누지만, 층마다 micro-batch마다 collective 4번이 NVLink에서만 감당된다.
  • PP는 깊이를 노드 너머로 나누는 축이다. 가중치와 stage별 activation을 나누고 경계 전송만 들지만, bubble을 치르는데 RL의 step당 적은 micro-batch가 그것을 키운다. m≫pm \gg p를 지키거나 interleaving을 쓴다.
  • EP는 MoE expert의 축이다. 작은 expert를 하나하나 TP로 쪼개지 않고 수백 GB의 expert 가중치를 나누는 유일한 방법이고, EP를 키워도 줄지 않는 all-to-all 통신량으로 값을 치른다.
  • CP(또는 Ulysses)는 길이의 축이다. 64k–128k 토큰 trajectory를 들어가게 하는 것이 이것이고, attention만 건드린다.
  • 나머지는 상태를 나눈 DP다. Megatron에서는 distributed optimizer(ZeRO-1), verl의 FSDP backend에서는 중소형 dense 모델에 FSDP/FSDP2를 쓰고, 이때 TP/PP는 아예 쓰지 않으며 길이는 Ulysses가 맡는다.

RL만의 꼬임은 rollout 엔진이 trainer와 다른 배치를 쓴다는 것이다. 위 벤치마크에서 학습은 TP 2 · PP 2 · CP 2 · EP 4, vLLM 서빙은 TP 4다. 그래서 가중치를 갱신할 때마다 한 배치에서 다른 배치로 매개변수를 다시 나눈다(GPU를 공유하면 verl의 3D-HybridEngine, 공유하지 않으면 NCCL/NIXL 위의 checkpoint engine). 그 비용과 공학은 verl 레슨과 RL을 위한 추론에서 다룬다.

PyTorch PyTorch: Megatron식 column-parallel·row-parallel linear 층 로컬에서 실행run locally (pip install torch)
import torch
import torch.distributed as dist
import torch.nn.functional as F

class _CopyToTP(torch.autograd.Function):
    """Megatron의 f: forward는 항등, backward에서 입력 기울기를 all-reduce."""
    @staticmethod
    def forward(ctx, x, group):
        ctx.group = group
        return x
    @staticmethod
    def backward(ctx, g):
        g = g.clone()
        dist.all_reduce(g, group=ctx.group)
        return g, None

class _ReduceFromTP(torch.autograd.Function):
    """Megatron의 g: forward에서 all-reduce, backward는 항등."""
    @staticmethod
    def forward(ctx, x, group):
        x = x.clone()
        dist.all_reduce(x, group=group)
        return x
    @staticmethod
    def backward(ctx, g):
        return g, None

class ColumnParallelLinear(torch.nn.Module):
    def __init__(self, d_in, d_out, group):
        super().__init__()
        self.group, tp = group, dist.get_world_size(group)
        self.weight = torch.nn.Parameter(torch.empty(d_out // tp, d_in))   # 이 rank의 출력 행
        torch.nn.init.normal_(self.weight, std=d_in ** -0.5)
    def forward(self, x):                        # x는 모든 TP rank에 복제돼 있다
        return F.linear(_CopyToTP.apply(x, self.group), self.weight)   # 출력은 나뉜 채로 둔다

class RowParallelLinear(torch.nn.Module):
    def __init__(self, d_in, d_out, group):
        super().__init__()
        self.group, tp = group, dist.get_world_size(group)
        self.weight = torch.nn.Parameter(torch.empty(d_out, d_in // tp))   # 이 rank의 입력 열
        torch.nn.init.normal_(self.weight, std=d_in ** -0.5)
    def forward(self, x_shard):                  # x_shard: 이 rank의 column-parallel 출력
        return _ReduceFromTP.apply(F.linear(x_shard, self.weight), self.group)

class TPMLP(torch.nn.Module):                    # forward에 all-reduce 한 번, backward에 한 번
    def __init__(self, h, f, group):
        super().__init__()
        self.up = ColumnParallelLinear(h, f, group)
        self.down = RowParallelLinear(f, h, group)
    def forward(self, x):
        return self.down(F.gelu(self.up(x)))
 
확인 문제Check yourself

RL trainer가 PP=8에 1F1B 스케줄을 쓴다. optimizer step마다 pipeline당 micro-batch가 8개다. 시간의 대략 몇 %가 bubble이고, 10% 아래로 내리려면 step당 micro-batch가 몇 개 필요한가?

(p−1)/(m+p−1)=7/15≈47%(p-1)/(m+p-1) = 7/15 \approx 47\%다. ≤10%\le 10\%이려면 7/(m+7)≤0.17/(m+7) \le 0.1, 즉 m≥63m \ge 63이다. RL의 작은 step당 배치로는 그만큼의 micro-batch가 없는 경우가 많아서, interleaving(chunk vv개가 bubble을 vv로 나눈다), pipeline stage 줄이기, PP 대신 TP/EP/CP 늘리기가 흔한 선택이다.

확인 문제Check yourself

실행 스크립트들은 왜 tensor parallelism을 8-GPU 노드 하나 안에 두고, pipeline parallelism은 노드를 넘기는 걸 예사로 할까?

TP의 collective는 micro-batch당 O(L)O(L)번이고 다음 층의 계산을 막는다. GPU당 대역폭이 대략 9배 낮은 InfiniBand에서는 그것이 step을 지배한다. PP의 통신은 micro-batch당 point-to-point 메시지 O(p)O(p)개이고 계산과 겹치므로 느린 링크를 견딘다. 대신 비용은 bubble이다.

정리

  • mixed precision Adam은 model state로 약 16Ψ16\Psi바이트가 든다. ZeRO-1/2/3는 이를 data-parallel rank에 나누고 추가 통신은 각각 0, 0, 50%다. FSDP는 ZeRO-3이고 Megatron의 distributed optimizer는 DP × CP에 대한 ZeRO-1이다.
  • Megatron TP는 블록의 첫 행렬을 열로, 둘째를 행으로 잘라 pass당 블록마다 all-reduce를 정확히 한 번 한다. sequence parallelism은 activation 전부를 TP로 나눈다. TP는 노드 안에 둔다.
  • PP의 bubble은 GPipe와 1F1B 모두 (p−1)/(m+p−1)(p-1)/(m+p-1)이다. 1F1B는 in-flight activation을 pp로 묶고, interleaving은 메시지와 메모리를 더 쓰는 대신 bubble을 vv로 나눈다.
  • EP는 expert 메모리를 나누고 pass당 MoE 층마다 all-to-all 두 번을 치른다. Megatron은 expert 격자를 attention 격자 위에 접는다(TP⋅CP⋅DP=ETP⋅EP⋅EDP\text{TP}\cdot\text{CP}\cdot\text{DP} = \text{ETP}\cdot\text{EP}\cdot\text{EDP}).
  • CP(ring attention, zig-zag chunk)나 Ulysses(head 축 all-to-all)가 시퀀스 길이를 나눈다. 긴 agent trajectory에서는 학습이 들어가느냐를 정하는 축인 경우가 많다.

더 읽을거리Further reading