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, bytes for parameters. Qwen3-8B has B (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 , 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 bytes sends bytes per GPU (a reduce-scatter followed by an all-gather), independent of for large . ZeRO removes the redundancy by sharding the model states over the data-parallel ranks:
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: elements instead of , 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.
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 논문의 회계로 매개변수 개에 바이트다. Qwen3-8B는 B(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 표기로 이고, EP는 같은 GPU 위에 접혀 들어간다(뒤에서 설명).
Data parallelism과 ZeRO / FSDP
평범한 data parallelism은 모든 것을 복제하고 all-reduce로 기울기를 평균한다. 바이트 버퍼의 ring all-reduce는 GPU당 바이트를 보낸다(reduce-scatter 다음 all-gather). 이 크면 과 무관하다. ZeRO는 model state를 data-parallel rank 개에 나눠 중복을 없앤다.
ZeRO-1과 -2는 통신이 늘지 않는다(기울기의 reduce-scatter와 갱신된 가중치의 all-gather가 정확히 all-reduce의 두 반쪽이다). ZeRO-3는 층마다 forward 전에, backward 전에 다시 가중치를 all-gather해야 한다. 대신 개 원소, 즉 1.5배이고, 기울기 누적을 하면 모은 가중치를 유지하지 않는 한 micro-batch마다 든다. PyTorch FSDP가 ZeRO-3다(FSDP2는 매개변수마다 dim 0을 따라 DTensor로 나눈다). Megatron의 “distributed optimizer”는 DP × CP rank에 대한 ZeRO-1이다.
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 splits with one collective per forward if the first matrix is cut by columns and the second by rows. Write (column blocks) and (matching row blocks). Rank computes
which is exact because acts elementwise, so , and a block row times a block column is a sum of block products. The only communication is the sum — an all-reduce of ‘s shape. Attention splits the same way along heads: by columns (each rank owns query heads and their KV heads), the output projection by rows. Cutting the first matrix by rows instead would put a sum inside , 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 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 . 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.
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 를 첫 행렬은 열로, 둘째 행렬은 행으로 자르면 forward당 collective 하나로 나눌 수 있다는 것이다. (열 블록), (짝이 맞는 행 블록)라 쓰면 rank 는
를 계산한다. 가 원소별로 작용하므로 이고, 블록 행 곱하기 블록 열은 블록 곱의 합이니 정확하다. 통신은 합 하나, 모양의 all-reduce뿐이다. attention은 head를 따라 똑같이 나뉜다. 는 열로(rank마다 query head 개와 그 KV head), 출력 projection 는 행으로 자른다. 첫 행렬을 행으로 자르면 합이 안에 들어가서 all-reduce가 하나 더 필요하다.
층과 micro-batch마다 forward에 all-reduce 두 번(attention, MLP), backward에 두 번이고, 각각 bf16 값 개다. sequence parallelism(Korthikanti 등)은 all-reduce를 같은 총량의 reduce-scatter + all-gather로 바꾸고, 그 대가로 layer-norm과 dropout activation을 시퀀스 축으로 나눠 activation 메모리 전체를 로 나눈다. 이 collective들이 모든 층의 critical path에 있으니 TP는 노드 안 NVLink 위에 둔다. 노드당 GPU 8개면 TP ≤ 8이다. head 수가 나누어떨어져야 한다. Qwen3-8B의 query head 32개는 TP 32까지, KV head 8개는 8까지 허용하고, 그 이상이면 KV 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 stages consecutive layers and streams micro-batches through them; only the activation at a stage boundary crosses GPUs (a point-to-point send of values), so PP tolerates slow inter-node links. The price is the bubble. Let a micro-batch’s forward take and backward on one stage. The last stage cannot start until the first micro-batch has gone through earlier stages, and the first stage sits idle at the end for the same reason, so each stage idles for out of :
GPipe runs all forwards, then all backwards, and holds micro-batches of activations. 1F1B (one-forward-one-backward) starts backwards as soon as possible: after a warm-up of forwards, stage alternates F and B, so at most micro-batches are in flight — the same bubble with memory bounded by instead of . Interleaved 1F1B gives each GPU non-contiguous chunks of layers; each chunk takes of the time, which shrinks the bubble to of the ideal time, at the price of times more point-to-point messages, more in-flight activations, and a multiple of in Megatron’s schedule.
Pipeline parallelism: 층의 쌓임을 자른다
PP는 개 stage에 연속한 층 개씩을 주고 micro-batch 개를 흘려보낸다. stage 경계의 activation만 GPU를 건너므로(값 개의 point-to-point 전송), 노드 사이의 느린 링크도 견딘다. 대가는 bubble이다. stage 하나에서 micro-batch의 forward가 , backward가 걸린다고 하자. 마지막 stage는 첫 micro-batch가 앞의 개 stage를 지날 때까지 시작하지 못하고, 첫 stage도 같은 이유로 끝에서 논다. 그래서 각 stage는 중 동안 논다.
GPipe는 forward를 전부 한 뒤 backward를 전부 하고, micro-batch 개 분량의 activation을 들고 있다. 1F1B(one-forward-one-backward)는 backward를 가능한 한 일찍 시작한다. stage 는 forward 번의 warm-up 뒤 F와 B를 번갈아 하므로 in-flight micro-batch가 많아야 개다. bubble은 같고 메모리 상한은 이 아니라 다. interleaved 1F1B는 GPU마다 층짜리 떨어진 chunk 개를 준다. chunk 하나가 시간의 를 차지하니 bubble이 이상적 시간의 로 준다. 대가는 point-to-point 메시지 배, 더 많은 in-flight activation, 그리고 Megatron 스케줄에서 이 의 배수여야 한다는 조건이다.
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 ). 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 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.
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를 더 많이 든다(에서 stage 0의 반 크기 chunk 11개는 micro-batch 5.5개 분량). RL에서는 bubble이 사전학습보다 더 아프다. optimizer step 하나가 data-parallel replica당 trajectory 개만 보고, 그것이 토큰 예산 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 experts and top- 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 whole experts on each GPU of an EP group. Each token’s hidden vector must travel to the GPUs that hold its experts and come back: an all-to-all dispatch and an all-to-all combine per MoE layer, each moving values per token, of which a fraction 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 . The attention part of each pipeline stage uses the grid, and the MoE part re-reads the same GPUs as an grid (“MoE parallel folding”), so the constraint is ; 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 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 ranks 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 steps every query has seen every key, and partial results are merged with the online-softmax rescaling of FlashAttention (keep the running max , normaliser and accumulator, rescale by ). Communication per layer is KV blocks per rank — with GQA only 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 chunks and give rank chunks and .
Ulysses sequence parallelism (verl’s ulysses_sequence_parallel_size for FSDP) does it differently: an all-to-all turns “all heads, tokens” into ” 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 . 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).
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 개와 top- routing을 쓰는 MoE 층은 토큰 하나가 쓰는 것보다 훨씬 많은 매개변수를 갖는다(Qwen3-235B-A22B: expert 128개, top-8. 층당 expert 매개변수 약 2.4B 중 토큰 하나가 1/16을 쓴다). EP는 EP 그룹의 GPU마다 온전한 expert 개를 둔다. 각 토큰의 hidden vector는 자기 expert 개가 있는 GPU로 갔다가 돌아와야 한다. MoE 층마다 all-to-all dispatch와 all-to-all combine이 있고, 각각 토큰당 값 개를 옮기며 routing이 고르면 그중 가 GPU를 떠난다. backward가 둘 다 되풀이한다. TP와 달리 EP를 키워도 토큰당 통신량은 줄지 않는다. EP가 사 주는 것은 EP로 나뉜 expert 메모리다. 부하 불균형(어떤 GPU가 토큰을 훨씬 많이 받음)은 모든 MoE 층에서 낙오자로 바뀐다. 그래서 routing 균형(MoE)은 시스템 문제이고, RL은 학습과 rollout의 expert 선택을 맞추려고 routing replay를 더한다(mismatch engineering).
Megatron-Core는 EP를 의 별도 인수로 만들지 않는다. pipeline stage마다 attention 부분은 격자를 쓰고, MoE 부분은 같은 GPU를 격자로 다시 읽는다(“MoE parallel folding”). 그래서 조건은 이고, expert 기울기는 expert-data-parallel 그룹 EDP에서 평균한다. 위의 verl 벤치마크 배치(GPU 32개, TP 2, PP 2, CP 2)에서 attention 격자는 , stage당 GPU 16개이고, EP = 4가 그 안에 접힌다.
Context parallelism: 시퀀스를 자른다
trajectory가 길면 가중치가 아니라 activation이 문제다. FlashAttention을 써도 층당 activation은 토큰 수에 선형이다. Context parallelism은 rank 개에게 모든 시퀀스의 토큰 개씩을 준다. attention을 빼면 모든 연산이 토큰별이다. attention에서는 rank마다 자기 query를 들고 key/value 블록을 고리로 돌린다. step 뒤에는 모든 query가 모든 key를 봤고, 부분 결과는 FlashAttention의 online softmax 재조정(현재 최댓값 , 정규화 상수 , 누적값을 들고 로 재조정)으로 합친다. 층당 통신은 rank당 KV 블록 개이고 — GQA면 토큰당 값 개로 hidden state보다 훨씬 작다 — 블록 계산과 겹친다. causal mask에서는 연속 chunk로 자르면 마지막 rank가 첫 rank보다 일이 훨씬 많으므로, 구현들은 시퀀스를 chunk 개로 자르고 rank 에 chunk 과 을 준다.
Ulysses sequence parallelism(FSDP용 verl의 ulysses_sequence_parallel_size)은 다르게 한다. attention 앞에서 all-to-all로 “모든 head, 토큰 개”를 “head 개, 모든 토큰”으로 바꾸고, 뒤에서 되돌린다. 시퀀스 길이와 GPU 수가 함께 늘면 GPU당 통신량이 일정하지만, head 수가 로 나누어떨어져야 한다. verl의 Megatron backend는 CP(context_parallel_size)를 쓰고, v0.9.0부터는 packed micro-batch의 시퀀스들이 CP 전체 크기를 필요로 하지 않으면 micro-batch마다 더 작은 CP 그룹을 고를 수 있다(dynamic context parallel, verl PR #6555).
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 for attention and norms plus for a SwiGLU MLP of width (for MoE, ), divided by TP under sequence parallelism, times layers and in-flight micro-batches on stage 0 (1F1B). With full recomputation only the -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에 약 , 폭 인 SwiGLU MLP에 (MoE면 )를 쓰고, sequence parallelism 아래 TP로 나눈 뒤 층과 stage 0의 in-flight micro-batch 개(1F1B)를 곱했다. full recomputation이면 층마다 바이트짜리 층 입력만 남긴다. 마지막 stage는 여기에 fp32 logit, 즉 토큰 수 × 151,936 × 4바이트(TP 없이 16k 토큰 micro-batch에 약 10 GB)를 더 든다. verl이 log-prob과 entropy를 chunk 단위나 fused kernel로 계산하는 이유다.
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 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.
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)))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%?
. For we need , i.e. . With RL’s small per-step batches that many micro-batches is often unavailable, which is why interleaving ( chunks divide the bubble by ), fewer pipeline stages, or more TP/EP/CP instead of PP are common choices.
Why do launchers keep tensor parallelism within one 8-GPU node, while pipeline parallelism routinely spans nodes?
TP’s collectives are 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 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 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 for GPipe and 1F1B alike; 1F1B bounds in-flight activations by ; interleaving divides the bubble by 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 ().
- 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가 그것을 키운다. 를 지키거나 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을 위한 추론에서 다룬다.
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)))RL trainer가 PP=8에 1F1B 스케줄을 쓴다. optimizer step마다 pipeline당 micro-batch가 8개다. 시간의 대략 몇 %가 bubble이고, 10% 아래로 내리려면 step당 micro-batch가 몇 개 필요한가?
다. 이려면 , 즉 이다. RL의 작은 step당 배치로는 그만큼의 micro-batch가 없는 경우가 많아서, interleaving(chunk 개가 bubble을 로 나눈다), pipeline stage 줄이기, PP 대신 TP/EP/CP 늘리기가 흔한 선택이다.
실행 스크립트들은 왜 tensor parallelism을 8-GPU 노드 하나 안에 두고, pipeline parallelism은 노드를 넘기는 걸 예사로 할까?
TP의 collective는 micro-batch당 번이고 다음 층의 계산을 막는다. GPU당 대역폭이 대략 9배 낮은 InfiniBand에서는 그것이 step을 지배한다. PP의 통신은 micro-batch당 point-to-point 메시지 개이고 계산과 겹치므로 느린 링크를 견딘다. 대신 비용은 bubble이다.
정리
- mixed precision Adam은 model state로 약 바이트가 든다. 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 모두 이다. 1F1B는 in-flight activation을 로 묶고, interleaving은 메시지와 메모리를 더 쓰는 대신 bubble을 로 나눈다.
- EP는 expert 메모리를 나누고 pass당 MoE 층마다 all-to-all 두 번을 치른다. Megatron은 expert 격자를 attention 격자 위에 접는다().
- CP(ring attention, zig-zag chunk)나 Ulysses(head 축 all-to-all)가 시퀀스 길이를 나눈다. 긴 agent trajectory에서는 학습이 들어가느냐를 정하는 축인 경우가 많다.
더 읽을거리Further reading
- Shoeybi et al., Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism (2019) — column→row 분할과 층당 all-reduce. TP의 원전.The column→row split and the all-reduce per block — the origin of TP.
- Narayanan et al., Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM (SC 2021) — PTD-P 조합, 1F1B와 interleaved 스케줄, bubble 식 (p−1)/(v·m).The PTD-P combination, 1F1B and interleaved schedules, and the bubble formula (p−1)/(v·m).
- Korthikanti et al., Reducing Activation Recomputation in Large Transformer Models (2022) — sequence parallelism과 selective recomputation, 층당 activation 메모리 식.Sequence parallelism, selective recomputation and the per-layer activation-memory formula.
- Rajbhandari et al., ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (SC 2020) — 매개변수당 16바이트 회계와 ZeRO-1/2/3의 메모리·통신 식.The 16-bytes-per-parameter accounting and the memory and communication of ZeRO-1/2/3.
- Zhao et al., PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel (VLDB 2023) — PyTorch 쪽 ZeRO-3. verl의 FSDP/FSDP2 backend의 바탕.ZeRO-3 in PyTorch; the basis of verl's FSDP/FSDP2 backend.
- Huang et al., GPipe (2019) — micro-batch pipeline과 bubble의 첫 분석.The first micro-batched pipeline and its bubble.
- Liu et al., Ring Attention with Blockwise Transformers for Near-Infinite Context (2023); Jacobs et al., DeepSpeed Ulysses (2023) — 시퀀스를 자르는 두 방법. KV를 고리로 돌리기(ring)와 head 축 all-to-all(Ulysses, arXiv 2309.14509).The two ways to split a sequence — pass KV around a ring, or all-to-all over heads (Ulysses, arXiv 2309.14509).
- Liu et al., MoE Parallel Folding: Heterogeneous Parallelism Mappings for Efficient Large-Scale MoE Model Training with Megatron Core (2025) — attention의 TP×CP×DP 격자와 expert의 ETP×EP×EDP 격자를 같은 GPU 위에 접는 방식. GShard(arXiv 2006.16668)의 EP를 잇는다.Folding the attention TP×CP×DP grid and the expert ETP×EP×EDP grid onto the same GPUs; builds on GShard's EP (arXiv 2006.16668).