Pipeline parallelism: stages, micro-batches and bubbles
Splitting a model by layers only requires point-to-point communication but leaves GPUs waiting. Starting from naive model parallelism, we progress through GPipe and 1F1B to interleaved pipelines and zero-bubble schedules that split backward into two halves. We derive bubble and memory for each schedule, build a schedule simulator and implement a real multiprocess pipeline.
After this lesson you can
- Derive the GPipe bubble fraction and in-flight activation memory of GPipe and 1F1B.
- Build GPipe, 1F1B, interleaved and zero-bubble schedules in a simulator and verify their formulas.
- Implement a real four-stage pipeline sending and receiving activations and gradients.
- Balance stages accounting for embeddings and the output head.
- Explain how separating input and weight gradients can eliminate the bubble.
Before you start
A network split by depth
When a full copy does not fit on one device, consecutive layers can be placed on different devices. Naive model parallelism moves the activation to the next GPU in forward and returns its gradient in backward. With one batch, each stage waits for the previous one: one active GPU leaves the others unused. Parameter memory is distributed, but example latency traverses every stage.
Pipeline microbatching divides the local batch into parts. A stage can work on the second while the next processes the first. Each part’s loss must be weighted so accumulated gradients equal the batch loss: for equal sizes and mean loss, divide each loss by . With different sizes or masks, weight by the actual count of valid tokens.
If the global batch contains examples, data-parallel degree is , and each microbatch has examples, then when all parts have equal size. Increasing with fixed reduces and can hurt kernel efficiency. Increasing it while keeping fixed changes the global batch and potentially optimization dynamics.
Distinguish three units. An example traverses the network; a microbatch groups examples traversing a stage together; the local batch collects microbatches whose derivatives accumulate before updating. A different data rank processes other examples, but pipeline ranks of one replica cooperate on the same microbatches. Counting each stage as a data replica overstates the calculated global batch.
Boundaries carry activations, not all parameters. A BF16 activation shaped occupies bytes. Its same-type and same-shape gradient occupies another in the opposite direction. With , , , each direction is 128 MiB per microbatch and boundary. The sum of both directions is not a network measurement: protocols, tensor partitions, shared links, and overlap affect observed time.
GPipe: fill and drain
GPipe runs all forwards and then all backwards before updating. Assume balanced stages, microbatches, negligible communication, forward and backward each lasting per stage, and no recomputation. Forward and backward waves each take . Total useful work occupies of device time, while available capacity during the iteration is . The bubble fraction is
Time overhead relative to the bubble-free ideal is a different ratio: . Their denominators answer different questions. For , the first is ; the second, . Ideal time assumes every stage is busy throughout the interval, not that each microbatch takes one operation.
Without checkpointing, GPipe retains activations for up to microbatches per stage before consuming them in backward. Actual peak bytes depend on shapes and what autograd saves; counting in-flight activations excludes parameters, gradients, and communication buffers. Recomputation changes usage and work, so the preceding count should not be applied as an exact measurement.
To visualize the derivation, consider four stages and eight microbatches. The first stage occupies eight forward slots, but the last does not start until the first activation crosses three boundaries. Eleven slots elapse from first forward start to last forward finish; backward needs another eleven. Work per stage totals sixteen of the twenty-two available slots, so idle time is six of twenty-two, or . On a real machine stages do not all take equal time: the slowest can impose additional waiting on every microbatch.
The bubble formula does not imply infinitely many microbatches are free. A small microbatch can underutilize matrix multiplications and increase message count. More simultaneous activations can exceed memory. Find the useful point by measuring stage and link time for the actual microbatch size, not by choosing solely to reduce an algebraic ratio.
1F1B: consume earlier
The one-forward-one-backward schedule warms up the pipeline, alternates operations, and drains it. At stage , numbered from zero, warm-up contains at most forwards. The first backward occurs after one additional forward; thus peak in-flight activations are under this schedule without recomputation. In particular no stage exceeds microbatches, versus in GPipe.
With the same balanced times and zero communication, 1F1B has the same classical bubble as GPipe: it saves activation memory but does not itself eliminate fill and drain. Operations across stages must respect dependencies even though each stage has its own queue. An asynchronous send must retain its buffer until completion; the local code does so explicitly.
For example, with four stages and enough microbatches, stage zero warms up with three forwards and accepts the fourth before its first backward. It then alternates and releases one for each new one; peak is four. The last stage starts backward after its first forward, retaining one. With only two microbatches no stage can store more than two. This count assumes backward releases that microbatch’s activations; if W is deferred, the bound changes because it still needs forward data.
Local order alone does not determine when an operation runs. A backward on the first stage needs the gradient sent by the second; a forward on the second needs the first’s activation. The simulator advances to the next finished event and starts an operation only if resource and dependencies are available. The builder allows invalid placements to expose precisely the difference between a block sequence and an executable DAG.
Interleave and split backward
An interleaved pipeline assigns multiple virtual stages to each GPU. A device can process another part of the network while awaiting communication for the first. In Megatron-LM’s balanced model, with virtual chunks, a multiple of , and communication omitted, overhead relative to ideal time changes from to . More chunks also create more transfers and can reduce each operation’s size. That ratio is not guaranteed for unequal durations, another assignment, or every greedy schedule.
Zero-bubble pipelining distinguishes two backward parts: B computes the input derivative and unblocks the previous stage; W computes the weight derivative. W can wait for a gap as long as its activations remain available. Zero Bubble Pipeline Parallelism constructs schedules with different memory and time tradeoffs: no bubble depends on its assumptions and is not an automatic property of separating B and W.
In the paper’s analysis, the ZB-H2 bubble is , whereas 1F1B’s is . For the first term vanishes, with more memory and enough microbatches; optimizer synchronization between iterations must be handled separately. These expressions count bubble time in the paper’s model and are not directly the idle fraction of a finite execution including fill and drain.
The simulator also constructs a schedule with double warm-up and deferred W: for , , and zero communication, it verifies that each GPU executes operations without gaps between its first and last. In the example peak is seven activations per stage and there are 27 ticks between first start and last finish. Its finite idle fraction is , due to staggered starts and finishes: removing internal gaps does not itself remove synchronization between iterations. The greedy B, F, W variant is another heuristic without a no-gap guarantee. The DeepSeek-V3 report describes DualPipe, using two directions and overlapping work and communication; it is not equivalent to this small simulator. In practice the optimizer step can also require synchronizing gradients, checking nonfinite values, and calculating a global norm for clipping before updating. Those barriers can leave idle time even with a full compute schedule.
Balance cost, not just layers
Balanced stage partitioning must count the embedding and head as well as blocks. A large-vocabulary head can dominate the last stage. Ideal steady-state speed is limited by the slowest stage, not the average. An optimal contiguous partition for known costs can be computed by dynamic programming: , with and impossible states infinite.
The embedding table and head can share weights. If placed on different stages, each copy produces a contribution to the same logical gradient; sum them and keep updates consistent. Splitting layers does not automatically resolve this coordination. The lab compares that shared gradient with the full model’s.
The dynamic-programming recurrence examines every possible previous boundary . The best partition of the first elements into segments has maximum cost ; the new segment costs the sum from to . Its bottleneck is the maximum of both. Minimizing that maximum over lets us reconstruct boundaries from chosen indices. This solution assumes costs are additive and layer order does not change. If two stages share a link or shapes change with the boundary, extend the cost model.
In the figure’s example, initial loads are 4, 4, 4, and 6 units. The ideal steady-state limit is one microbatch every six ticks; a split with the same number of layers per stage does not imply equal loads. If head cost increases, optimal boundaries can move even if all transformer layers cost the same. A stage cannot be empty in the displayed problem, and the figure compares against the optimum under that same constraint.
Pipelining is often combined with tensor parallelism within a node and data parallelism among replicas: each axis needs its own group and communications. PipeDream proposed an asynchronous variant with weight versions so a microbatch’s forward and backward are consistent. Updating while other microbatches are in flight means they can use older versions; this is not equivalent to the synchronous batch update verified here.
Lab: events and dependencies
The simulator counts one tick for B and W and two for F. In GPipe and 1F1B it waits for W to finish before propagating to the neighbor, representing an indivisible two-tick backward. In deferred variants B unblocks the neighbor before W. By default this is a compute model without transfers or memory limits: it measures activations retained from F start to W finish, not actual bytes. The interleaved variant builds 1F1B queues of virtual stages per device, with microbatch count a multiple of p and indivisible backward; it compares ideal overhead with Megatron’s formula. Its queue rule follows PyTorch ScheduleInterleaved1F1B structure.
from collections import defaultdict
def simulate(p, m, mode='1f1b', v=1, cap=None, f=2, b=1, w=1):
# F, B (derivada de entrada) y W (derivada de parámetros) duran un tick.
# Cada etapa virtual pertenece a la GPU etapa % p. En este juguete
# B y W juntos cuestan dos ticks, igual que F (dos ticks).
n = p*v
done, active, live, trace = {}, {}, defaultdict(int), []
queues = []
for stage in range(n):
if mode == 'gpipe':
q = [('F', i) for i in range(m)] + [(k, i) for i in range(m) for k in ('B', 'W')]
elif mode == '1f1b':
warm = min(n-stage-1, m)
q = [('F', i) for i in range(warm)]
for i in range(m-warm): q += [('F', warm+i), ('B', i), ('W', i)]
q += [(k, i) for i in range(m-warm, m) for k in ('B', 'W')]
else: q = []
queues.append(q)
rank_queues = [[] for _ in range(p)]
if mode == 'intercalada':
if m % p: raise ValueError('El ejemplo intercalado requiere m múltiplo de p')
for rank in range(p):
warm = min((v-1)*p + 2*(p-1-rank), v*m)
forward_count, backward_count = defaultdict(int), defaultdict(int)
for step in range(v*m + warm):
if step < v*m:
stage = (step // p % v)*p + rank
i = forward_count[stage]; forward_count[stage] += 1
rank_queues[rank].append(('F',stage,i))
if step >= warm:
stage = (v-1 - ((step-warm)//p % v))*p + rank
i = backward_count[stage]; backward_count[stage] += 1
rank_queues[rank] += [('B',stage,i),('W',stage,i)]
if mode in ('zb1p','zb2p'):
# Una etapa por rango: W se retrasa según el rango; ZB2P amplía
# calentamiento y cola para llenar los huecos internos con F=B=W.
factor = 1 if mode == 'zb1p' else 2
if m < factor*(p-1)+1: raise ValueError('Faltan micro-lotes para este calendario')
for rank in range(p):
warm = min(factor*(p-1-rank),m)
pending = []
for step in range(m+warm):
if step < m: rank_queues[rank].append(('F',rank,step))
if step >= warm:
i=step-warm
rank_queues[rank].append(('B',rank,i)); pending.append(i)
if len(pending)>factor*rank: rank_queues[rank].append(('W',rank,pending.pop(0)))
for i in pending: rank_queues[rank].append(('W',rank,i))
def ready(k, s, i, t):
def finished(key): return key in done and done[key] <= t
if k == 'F':
return (s == 0 or finished(('F', s-1, i))) and (cap is None or live[s] < cap)
if k == 'B':
downstream = 'W' if mode in ('gpipe', '1f1b', 'intercalada') else 'B'
return finished(('F', s, i)) and (s == n-1 or finished((downstream, s+1, i)))
return finished(('B', s, i))
t = 0
while len(done) < 3*n*m:
for gpu, (end, k, s, i) in list(active.items()):
if end == t:
done[k,s,i] = t
if k == 'W': live[s] -= 1
del active[gpu]
if len(done) == 3*n*m: break
for gpu in range(p):
if gpu in active: continue
candidates = []
if mode in ('intercalada','zb1p','zb2p'):
candidates = rank_queues[gpu][:1]
for s in ([] if mode in ('intercalada','zb1p','zb2p') else range(gpu, n, p)):
if mode in ('gpipe', '1f1b'):
candidates += [(queues[s][0][0],s,queues[s][0][1])] if queues[s] else []
else:
# Diferir W permite usar huecos; no pretende reproducir ZB-H2.
candidates += [(k,s,i) for k in ('B','F','W') for i in range(m)
if (k,s,i) not in done and not any(a[1:] == (k,s,i) for a in active.values())]
for k,s,i in candidates:
if ready(k,s,i,t):
duration = f if k == 'F' else b if k == 'B' else w
active[gpu] = (t+duration,k,s,i)
trace.append((gpu,s,i,k,t,t+duration))
if k == 'F': live[s] += 1
if mode in ('gpipe', '1f1b'): queues[s].pop(0)
if mode in ('intercalada','zb1p','zb2p'): rank_queues[gpu].pop(0)
break
if not active: raise RuntimeError('Bloqueo: revisar cap y dependencias')
t = min(item[0] for item in active.values())
peak = [0]*n
for s in range(n):
events = sorted([(a, 1) if k == 'F' else (b, -1) for _,ss,_,k,a,b in trace if ss == s and k in ('F','W')], key=lambda x:(x[0],x[1]))
cur = 0
for _, delta in events:
cur += delta; peak[s] = max(peak[s],cur)
busy = sum(end-start for _,_,_,_,start,end in trace)
return trace, 1-busy/(p*t), peak, t
for mode in ('gpipe','1f1b','intercalada','diferida'):
v = 2 if mode == 'intercalada' else 1
trace, bubble, peak, length = simulate(4, 8, mode, v)
print(mode, 'ticks', length, 'burbuja', round(bubble,4), 'pico por etapa', peak)
for mode in ('gpipe','1f1b'):
_, bubble, peak, _ = simulate(4,8,mode)
assert abs(bubble - 3/11) < 1e-12
if mode == 'gpipe': assert max(peak) == 8
else: assert all(x <= min(8,4-r) for r,x in enumerate(peak))
print('Fórmulas GPipe y 1F1B verificadas para F = B + W')
_, bubble, _, _ = simulate(4,8,'intercalada',2)
assert abs(bubble - 3/19) < 1e-12
print('Intercalada: sobrecarga frente al ideal = 3/16')
_, bubble, peak, length = simulate(4,8,'zb1p',f=1)
print('ZB1P con F=B=W=1:', length, 'ticks; fracción ociosa', round(bubble,4), 'pico', peak)
trace, bubble, peak, length = simulate(4,8,'zb2p',f=1)
for rank in range(4):
operations=[x for x in trace if x[0]==rank]
assert operations[-1][5]-operations[0][4] == 3*8 # sin huecos internos
assert max(peak)==2*4-1 and length==3*8+4-1
print('ZB2P: ningún hueco interno, pico', max(peak), 'fracción finita', round(bubble,4))
Lab: GPT in four processes
The GPT classes from lesson p06-l03 are reused with small dimensions and dropout disabled. Each process creates a copy to form a monolithic reference and executes only its pipeline block. Manual GPipe and 1F1B send activations and gradients through Gloo, retain asynchronous buffers, and accumulate scaled loss. Then both torch.distributed.pipelining schedules run on the same layers. Every stage gradient is verified and the embedding contribution shared with the head is summed. This is a numerical CPU check, not a GPU performance measurement.
import subprocess, sys, tempfile
from pathlib import Path
script = '''
"""GPT-2 desde cero con carga de pesos Hugging Face y controles reproducibles."""
import math
import os
from pathlib import Path
import torch
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(4)
class GPTLinear(nn.Linear):
def forward(self, x):
weight = self.weight.t().contiguous()
return torch.addmm(self.bias, x.reshape(-1, x.size(-1)), weight).view(*x.shape[:-1], self.out_features)
class CausalSelfAttention(nn.Module):
def __init__(self, d, heads, dropout):
super().__init__()
assert d % heads == 0
self.heads, self.d = heads, d
self.p = dropout
self.resid_drop = nn.Dropout(dropout)
self.c_attn = GPTLinear(d, 3*d)
self.c_proj = GPTLinear(d, d)
def forward(self, x):
b, t, d = x.shape
q, k, v = self.c_attn(x).split(d, dim=-1)
def split(z):
return z.view(b, t, self.heads, d//self.heads).transpose(1, 2)
out = F.scaled_dot_product_attention(split(q), split(k), split(v),
is_causal=True, dropout_p=self.p if self.training else 0.0)
out = out.transpose(1, 2).contiguous().view(b, t, d)
return self.resid_drop(self.c_proj(out))
class MLP(nn.Module):
def __init__(self, d, dropout):
super().__init__()
self.c_fc = GPTLinear(d, 4*d)
self.c_proj = GPTLinear(4*d, d)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
x = self.c_fc(x)
x = 0.5*x*(1.0 + torch.tanh(math.sqrt(2.0/math.pi)*(x + 0.044715*torch.pow(x, 3.0))))
return self.dropout(self.c_proj(x))
class Block(nn.Module):
def __init__(self, d, heads, dropout):
super().__init__()
self.ln_1 = nn.LayerNorm(d, eps=1e-5)
self.attn = CausalSelfAttention(d, heads, dropout)
self.ln_2 = nn.LayerNorm(d, eps=1e-5)
self.mlp = MLP(d, dropout)
def forward(self, x):
x = x + self.attn(self.ln_1(x))
return x + self.mlp(self.ln_2(x))
class Transformer(nn.Module):
def __init__(self, vocab, context, layers, heads, d, dropout):
super().__init__()
self.wte = nn.Embedding(vocab, d)
self.wpe = nn.Embedding(context, d)
self.drop = nn.Dropout(dropout)
self.h = nn.ModuleList([Block(d, heads, dropout) for _ in range(layers)])
self.ln_f = nn.LayerNorm(d, eps=1e-5)
class GPT(nn.Module):
def __init__(self, vocab=50257, context=1024, layers=12, heads=12, d=768, scaled=True, dropout=0.1):
super().__init__()
self.context, self.layers, self.d = context, layers, d
self.transformer = Transformer(vocab, context, layers, heads, d, dropout)
self.transformer.apply(self._init)
self.lm_head = nn.Linear(d, vocab, bias=False)
self.lm_head.weight = self.transformer.wte.weight
if scaled:
for block in self.transformer.h:
nn.init.normal_(block.attn.c_proj.weight, std=0.02/math.sqrt(2*layers))
nn.init.normal_(block.mlp.c_proj.weight, std=0.02/math.sqrt(2*layers))
@staticmethod
def _init(module):
if isinstance(module, (nn.Linear, nn.Embedding)):
nn.init.normal_(module.weight, mean=0, std=0.02)
if isinstance(module, nn.Linear) and module.bias is not None:
nn.init.zeros_(module.bias)
def forward(self, ids, return_residual=False):
b, t = ids.shape
if t > self.context:
raise ValueError('El contexto supera el límite del modelo')
z = self.transformer.drop(self.transformer.wte(ids) + self.transformer.wpe(torch.arange(t, device=ids.device)))
residuals = [z]
for block in self.transformer.h:
z = block(z)
residuals.append(z)
logits = self.lm_head(self.transformer.ln_f(z))
return (logits, residuals) if return_residual else logits
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.distributed.pipelining import PipelineStage, ScheduleGPipe, Schedule1F1B
import socket
P, M, D = 4, 4, 8
def run_schedule(rank, schedule):
torch.manual_seed(11)
model = GPT(vocab=16, context=4, layers=P, heads=2, d=D, dropout=0.0)
torch.manual_seed(33)
ids = torch.randint(0, 16, (M, 2, 4))
target = torch.randint(0, 16, (M, 2, 4))
reference = model(ids.view(-1, 4))
F.cross_entropy(reference.reshape(-1, 16), target.reshape(-1)).backward()
expected = {name: param.grad.clone() for name, param in model.named_parameters()}
model.zero_grad(set_to_none=True)
live, works = {}, []
def send(tensor, to, tag):
data = tensor.detach().contiguous()
works.append((dist.isend(data, dst=to, tag=tag), data))
def forward(i):
if rank == 0:
x = model.transformer.wte(ids[i]) + model.transformer.wpe(torch.arange(4))
x = model.transformer.drop(x)
else:
x = torch.empty((2, 4, D))
dist.recv(x, src=rank-1, tag=i)
x.requires_grad_()
y = model.transformer.h[rank](x)
if rank == P-1:
logits = model.lm_head(model.transformer.ln_f(y))
loss = F.cross_entropy(logits.reshape(-1, 16), target[i].reshape(-1)) / M
live[i] = (x, loss)
else:
live[i] = (x, y)
send(y, rank+1, i)
def backward(i):
x, y = live.pop(i)
if rank == P-1:
y.backward()
else:
gradient = torch.empty_like(y)
dist.recv(gradient, src=rank+1, tag=100+i)
y.backward(gradient)
if rank > 0:
send(x.grad, rank-1, 100+i)
if schedule.startswith('torch-'):
class Stage(nn.Module):
def __init__(self, model, rank):
super().__init__()
self.model, self.rank = model, rank
def forward(self, x):
if self.rank == 0:
x = self.model.transformer.wte(x) + self.model.transformer.wpe(torch.arange(4))
x = self.model.transformer.drop(x)
x = self.model.transformer.h[self.rank](x)
if self.rank == P-1:
x = self.model.lm_head(self.model.transformer.ln_f(x))
return x
sample = torch.zeros((2, 4), dtype=torch.long) if rank == 0 else torch.zeros((2, 4, D))
output = torch.zeros((2, 4, 16 if rank == P-1 else D))
stage = PipelineStage(Stage(model, rank), rank, P, torch.device('cpu'), sample, output)
cls = ScheduleGPipe if schedule == 'torch-gpipe' else Schedule1F1B
sched = cls(stage, n_microbatches=M, loss_fn=lambda out, tgt: F.cross_entropy(out.reshape(-1, 16), tgt.reshape(-1)))
if rank == 0: sched.step(ids.view(-1, 4))
elif rank == P-1: sched.step(target=target.view(-1, 4))
else: sched.step()
elif schedule == 'gpipe':
for i in range(M): forward(i)
for i in range(M): backward(i)
else:
warm = min(P-rank-1, M)
for i in range(warm): forward(i)
for i in range(M-warm):
forward(warm+i)
backward(i)
for i in range(M-warm, M): backward(i)
for work, data in works: work.wait()
# La tabla de embedding y la cabeza son el mismo parámetro en el GPT.
tied = torch.zeros_like(model.transformer.wte.weight)
if rank in (0, P-1): tied.copy_(model.transformer.wte.weight.grad)
dist.all_reduce(tied)
model.transformer.wte.weight.grad = tied
prefix = f'transformer.h.{rank}.'
names = [n for n in expected if n.startswith(prefix)]
if rank == 0: names += ['transformer.wte.weight', 'transformer.wpe.weight']
if rank == P-1: names += ['transformer.ln_f.weight', 'transformer.ln_f.bias']
params = dict(model.named_parameters())
for name in names:
torch.testing.assert_close(params[name].grad, expected[name], rtol=2e-4, atol=2e-6)
print(f'{schedule}: rango {rank}, {len(names)} gradientes coinciden', flush=True)
def worker(rank, port):
os.environ['MASTER_ADDR'], os.environ['MASTER_PORT'] = '127.0.0.1', str(port)
dist.init_process_group('gloo', rank=rank, world_size=P)
torch.set_num_threads(1)
for schedule in ['gpipe', '1f1b', 'torch-gpipe', 'torch-1f1b']:
run_schedule(rank, schedule)
dist.barrier()
dist.destroy_process_group()
if __name__ == '__main__':
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
mp.spawn(worker, args=(port,), nprocs=P, join=True)
'''
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "pipeline_gpt.py"
path.write_text(script, encoding="utf-8")
result = subprocess.run([sys.executable, str(path)], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=600)
print(result.stdout)
if result.returncode: raise RuntimeError(result.stderr)npm run lab and open the connection link.Exercises
Step 1 of 2. How many forwards are in warm-up?
def one_f_one_b(p, m):
...