Tensor and sequence parallelism
When one layer is too large or slow for a GPU, split the matmul itself. We build Megatron tensor parallelism from block multiplication: column- and row-parallel layers, conjugate operators f and g, MLP and per-head attention with one all-reduce per sublayer, and vocabulary-parallel embeddings and cross-entropy. Sequence parallelism shards what remained replicated and DTensor offers general notation for reasoning about layouts.
After this lesson you can
- Split a matmul by columns or rows and deduce required collectives in forward and backward.
- Implement Megatron MLP and attention with f and g and verify exact equality with the unsharded block.
- Implement vocabulary-parallel cross-entropy without gathering logits.
- Add sequence parallelism and calculate resulting activation memory.
- Express layouts with DeviceMesh and DTensor placements and explain why tensor parallelism stays within the node.
Before you start
Split the operation, not just the data
In data parallelism each rank retains a copy of the layer. If a matrix does not fit on one GPU, or one GPU takes too long to multiply it, the operation itself must be split. Transformer structure allows a partition that keeps the intermediate activation local and communicates only at the end of each sublayer.
Tensor parallelism (TP) distributes dimensions of an operation across ranks collaborating on the same example. It does not itself increase the number of distinct batch examples. Rank count and topology matter as much as tensor shapes.
Two ways to split a multiplication
Use example vectors in rows: , , . In PyTorch nn.Linear, the weight is stored transposed, with shape (salida, entrada) (output, input): splitting its rows equals splitting the columns of this section’s . This convention avoids confusing the split name with a storage axis.
For columns, if output gradient is sharded as , the chain rule gives and . For rows, after receiving the same , each rank computes and . Those sharded gradients are not summed. Biases must be handled according to their partition: adding a full bias in every partial contribution would count it times.
Shapes let us check the argument without relying on axis names. With columns, has shape and shape . Thus has shape , that of the full input; all ranks contribute to the same positions. , by contrast, has shape and belongs only to shard .
With rows, is and is . The local product already has shape , but is not yet the full output. After summing those products, the derivative with respect to each has only columns: those derivatives are conceptually concatenated, not summed together. Gathering them is a downstream consumer’s decision, not a requirement of this multiplication.
The column and row pair
The sharded Megatron block applies with split by columns and by rows. Each rank computes and the sum is . The nonlinearity is applied to each independent column before the sum. Generally , so moving it after partial sums changes the network.
Operator represents branching a replicated input: identity in forward and summation of contributions in backward. represents the sum of partial outputs: all-reduce in forward and identity in backward, for one replicated logical loss. They are conjugates under that replica and loss convention, not a rule for arbitrarily summing duplicated losses. Megatron-LM uses one all-reduce each way per MLP and another per attention.
To see why the MLP needs no intermediate gather, write and . Column of depends only on and feeds exactly row block . No rank needs to compute . In backward each rank receives the same output gradient of the sum and locally computes derivatives of its , , and . Branches are summed only when returning to the shared input.
The backward identity of deserves care. Each output copy represents the same logical variable, and in this scheme each rank has the same gradient of that variable. If instead each copy produces a different loss, specify and correctly reduce those loss contributions; treating each copy as an independent loss and summing again without adjusting scale would change the result. The lab uses one logical loss and checks both weights and input.
Multi-head attention is split by heads: each rank obtains its columns of , computes its attention, and applies the corresponding row block of the output projection. Contributions are summed. With GQA, each KV head serves multiple query heads: sharding across ranks without replicating or splitting KV heads requires a partition compatible with their count. With 8 KV heads you cannot assign at least one distinct complete head to each of 16 ranks. Other strategies can replicate KV or split another dimension, with associated costs.
Independence is by head, not sequence position: within each head the attention matrix mixes positions allowed by the mask. The output projection decomposes into blocks because multiplying concatenated contexts by its matrix equals summing each block’s projection. That sum must complete before the residual connection or a nonlinearity consuming full output. The lab uses noncausal attention to keep the algebra visible; a causal mask changes allowed positions, not head partitioning.
If does not evenly divide query and KV heads, decide what to replicate, pad, and how to assign groups. Replicating a KV head does not multiply distinct heads: it multiplies copies and may require reducing or coordinating their gradients. Some implementations also split within a head. Thus the limit of eight is a property of the proposed simple partition, not an impossibility of running higher-degree TP.
Vocabulary without gathering logits
Vocabulary-parallel embedding divides table rows by token. Each rank returns its vector when it owns the token and zero otherwise; a reduction sums contributions. In the output projection each rank computes only local logits. Gathering all logits costs space proportional to vocabulary size; cross-entropy needs much less.
For a logits row and label , loss is . Each rank computes its local maximum and a max reduction obtains . Each rank then sums over its shard, and a sum reduction gives the global denominator. Only the owner of contributes to another sum. Thus
Subtracting the maximum prevents overflow without changing probabilities. The local gradient is . Each label must belong to exactly one shard, and an invalid-token mask must be applied to both numerator and denominator of the final loss.
The maximum must be global: if each rank subtracts its own maximum and then sums exponentials without correcting scales, sums are no longer comparable. Nor can local losses be averaged, because each would normalize over only part of the vocabulary. The label owner supplies the selected logit; others supply zero and all end with the same loss. In backward each rank can calculate probabilities using the common denominator without communicating the full vector.
Shard the sequence too
Sequence parallelism shards the token dimension in operations acting per token, such as LayerNorm and dropout. Reduce-scatter leaves a portion of output on each rank, and all-gather reunites input when the next parallel multiplication needs it. An all-reduce equals reduce-scatter followed by all-gather under the same group, although buffers and schedule change.
Table 2 of Korthikanti et al. gives, for their transformer and precision accounting, bytes per layer and rank with TP, and with TP plus sequence. Here is length, batch, hidden width, heads, and TP degree. Coefficients reflect their saved activations and types; they are not a law for FlashAttention, GQA, another precision, or recomputation. The difference is the previously replicated term.
LayerNorm computes mean and variance over each token’s hidden dimension. If each rank has all features of its own tokens, it can normalize them without consulting others. This does not mean every normalization is local under every partition: if you split the normalized dimension, combine statistics or redistribute. The NumPy example shards sequence and checks both output and input derivative.
In backward collectives appear in reverse order with their adjoints: all-gather and reduce-scatter exchange roles under the sum convention. Total volume may resemble an all-reduce, but not necessarily time: exposure, call count, and simultaneously live buffers matter. The memory advantage comes from not retaining full activation copies of per-token operations on every rank.
Placements and topology
DeviceMesh and DTensor placements express sharding per mesh axis: Replicate keeps a copy, Shard(d) splits dimension , and Partial represents contributions awaiting reduction. The interactive applies conservative local rules to each axis of a 2 × 2 mesh. An unlisted layout requires redistribution before using that rule; it does not imply global multiplication is impossible.
An operation with two Partial inputs cannot be solved by multiplying only shards on the same rank: cross terms are missing. To materialize a partial sum as a replica use all-reduce; to shard the result, reduce-scatter can be used. The PyTorch API offers ColwiseParallel, RowwiseParallel, and SequenceParallel over a mesh; input and output layouts must match tensor meaning.
For example, on one mesh axis, Shard(1) of and Shard(0) of split the same contraction dimension . Each local product contributes to every position of , so its output is Partial. By contrast, Shard(0) of with replicated splits output rows and produces Shard(0). Dimension numbers refer to the particular tensor: Shard(0) of and Shard(0) of do not split the same mathematical dimension.
Partial does not mean the local value is a valid copy of the global answer. Nor is it itself an error: it may be the desired layout if the next operation knows about the pending sum. The interactive presents only simple local rules. In a real implementation redistribution costs communication and a two-dimensional mesh can combine different partitions and replicas on each axis.
TP’s advantage erodes with frequent collectives and smaller local matmuls. The internode network may be slower than local links, so TP is often kept within a high-speed group and combined with other parallelisms outside it. This is a profiling decision, not a universal prohibition. The figure is an alpha-beta model without contention, heterogeneous latencies, or kernel-efficiency changes.
To reproduce its calculation, an GB collective in an ideal ring takes , with ms and in GB/s. Four collectives and assumed compute are added. When moving from 8 to 16 ranks the example changes bandwidth; that jump is an explicit assumption, not a property of every cluster. On real hardware measure the group, message sizes, and exposed time in a trace.
Lab: four simulated ranks
The cell uses NumPy and four shards: it compares MLP and attention against monolithic forward and backward, additionally checks three attention-input gradients by finite differences, calculates distributed cross-entropy, and shards LayerNorm by sequence. Attention is noncausal and the example excludes dropout, biases, and GQA. Collectives are simulated with local sums; the byte counter uses an ideal ring model, not a network measurement.
import numpy as np
rng = np.random.default_rng(7)
B, S, H, A, T, F, V = 2, 4, 8, 4, 4, 16, 12
X = rng.normal(size=(B,S,H)); dY = rng.normal(size=(B,S,H))
W1 = rng.normal(size=(H,F)); W2 = rng.normal(size=(F,H))
X2 = X.reshape(-1,H); G = dY.reshape(-1,H)
Z = X2 @ W1; R = np.maximum(Z,0); Y = R @ W2
dw2 = R.T @ G; dz = (G @ W2.T)*(Z>0); dw1 = X2.T @ dz; dx = dz @ W1.T
partials = []; dx_parts = []; dw1s=[]; dw2s=[]
for r in range(T):
sl = slice(r*(F//T),(r+1)*(F//T))
z=X2@W1[:,sl]; relu=np.maximum(z,0)
partials.append(relu@W2[sl,:]); dw2s.append(relu.T@G)
delta=(G@W2[sl,:].T)*(z>0)
dw1s.append(X2.T@delta); dx_parts.append(delta@W1[:,sl].T)
assert np.allclose(sum(partials),Y) and np.allclose(sum(dx_parts),dx)
assert np.allclose(np.concatenate(dw1s,axis=1),dw1) and np.allclose(np.concatenate(dw2s,axis=0),dw2)
print('MLP: forward y todos los gradientes coinciden:', True)
# Atención no causal, una cabeza por rango; coeficientes y sus derivadas por cabeza.
Wq,Wk,Wv,Wo=[rng.normal(size=(H,H)) for _ in range(4)]
def head(x,wq,wk,wv,wo,upstream=None):
q,k,v=x@wq,x@wk,x@wv
[email protected](-1,-2)/np.sqrt(q.shape[-1])
e=np.exp(scores-scores.max(axis=-1,keepdims=True)); p=e/e.sum(axis=-1,keepdims=True)
context=p@v; out=context@wo
if upstream is None: return out
context2=context.reshape(-1,context.shape[-1]); up2=upstream.reshape(-1,H)
dwo=context2.T@up2; [email protected]
[email protected](-1,-2); dv=p.swapaxes(-1,-2)@dc
ds=p*(dp-(dp*p).sum(axis=-1,keepdims=True))/np.sqrt(q.shape[-1])
dq=ds@k; dk=ds.swapaxes(-1,-2)@q
[email protected][email protected][email protected]
return out,dx,[email protected](-1,q.shape[-1]),[email protected](-1,k.shape[-1]),[email protected](-1,v.shape[-1]),dwo
head_outputs=[]; head_dx=[]; dqs=[]; dks=[]; dvs=[]; dos=[]
for r in range(A):
sl=slice(r*(H//A),(r+1)*(H//A))
o,di,dq,dk,dv,do=head(X,Wq[:,sl],Wk[:,sl],Wv[:,sl],Wo[sl,:],dY)
head_outputs.append(o);head_dx.append(di);dqs.append(dq);dks.append(dk);dvs.append(dv);dos.append(do)
Yatt=sum(head_outputs); dxatt=sum(head_dx)
# Cálculo monolítico vectorizado por cabezas; la salida proyecta la concatenación.
def heads(z): return z.reshape(B,S,A,H//A).transpose(0,2,1,3)
def merge(z): return z.transpose(0,2,1,3).reshape(B,S,H)
q,k,v=heads(X@Wq),heads(X@Wk),heads(X@Wv)
[email protected](-1,-2)/np.sqrt(H//A)
e=np.exp(scores-scores.max(axis=-1,keepdims=True)); p=e/e.sum(axis=-1,keepdims=True)
c=p@v; cfull=merge(c); yfull=cfull@Wo
dc=heads([email protected]); [email protected](-1,-2); dv=p.swapaxes(-1,-2)@dc
ds=p*(dp-(dp*p).sum(axis=-1,keepdims=True))/np.sqrt(H//A)
dq,dk=ds@k,ds.swapaxes(-1,-2)@q
dq,dk,dv=merge(dq),merge(dk),merge(dv)
[email protected][email protected][email protected]
assert np.allclose(Yatt,yfull) and np.allclose(dxatt,dxfull)
assert np.allclose(np.concatenate(dqs,axis=1),[email protected](-1,H))
assert np.allclose(np.concatenate(dks,axis=1),[email protected](-1,H))
assert np.allclose(np.concatenate(dvs,axis=1),[email protected](-1,H))
assert np.allclose(np.concatenate(dos,axis=0),cfull.reshape(-1,H).T@G)
def objective(x):
return sum((head(x,Wq[:,r*2:(r+1)*2],Wk[:,r*2:(r+1)*2],Wv[:,r*2:(r+1)*2],Wo[r*2:(r+1)*2])*dY).sum() for r in range(A))
eps=1e-6
for idx in [(0,0,0),(1,3,7),(0,2,4)]:
plus=X.copy();minus=X.copy();plus[idx]+=eps;minus[idx]-=eps
assert np.allclose((objective(plus)-objective(minus))/(2*eps),dxatt[idx],rtol=1e-5,atol=1e-5)
print('Atención: forward y gradientes coinciden; diferencias finitas en tres entradas:',True)
def ce_sharded(logits,targets):
shards=np.split(logits,T,axis=-1)
maximum=np.maximum.reduce([shard.max(axis=-1) for shard in shards])
sums=sum(np.exp(shard-maximum[:,None]).sum(axis=-1) for shard in shards)
selected=sum(np.where((targets>=r*(V//T))&(targets<(r+1)*(V//T)),
shard[np.arange(len(targets)),np.clip(targets-r*(V//T),0,V//T-1)],0) for r,shard in enumerate(shards))
grads=[]
for r,shard in enumerate(shards):
g=np.exp(shard-maximum[:,None])/sums[:,None]
mask=(targets>=r*(V//T))&(targets<(r+1)*(V//T))
rows=np.flatnonzero(mask)
g[rows,targets[rows]-r*(V//T)]-=1
grads.append(g)
return maximum+np.log(sums)-selected, np.concatenate(grads,axis=-1)
logits=rng.normal(size=(B*S,V))*20; targets=rng.integers(0,V,size=B*S)
maxima=logits.max(axis=-1); expected=maxima+np.log(np.exp(logits-maxima[:,None]).sum(axis=-1))-logits[np.arange(B*S),targets]
loss,grad=ce_sharded(logits,targets)
expected_grad=np.exp(logits-maxima[:,None]);expected_grad/=expected_grad.sum(axis=-1,keepdims=True)
expected_grad[np.arange(B*S),targets]-=1
assert np.allclose(loss,expected) and np.allclose(grad,expected_grad)
print('Entropía cruzada y gradiente repartidos coinciden:',True)
def norm(x):
mu=x.mean(axis=-1,keepdims=True); centered=x-mu
return centered/np.sqrt((centered**2).mean(axis=-1,keepdims=True)+1e-5)
assert np.allclose(np.concatenate([norm(part) for part in np.split(X,T,axis=1)],axis=1),norm(X))
def norm_backward(x,g):
mu=x.mean(axis=-1,keepdims=True); centered=x-mu
scale=np.sqrt((centered**2).mean(axis=-1,keepdims=True)+1e-5)
n=centered/scale
return (g-g.mean(axis=-1,keepdims=True)-n*(g*n).mean(axis=-1,keepdims=True))/scale
dx_seq=np.concatenate([norm_backward(x,g) for x,g in zip(np.split(X,T,axis=1),np.split(dY,T,axis=1))],axis=1)
assert np.allclose(dx_seq,norm_backward(X,dY))
print('Normalización de secuencia: forward y backward coinciden:',True)
print('All-reduce BF16 ideal: bytes enviados por rango:',4*2*(T-1)/T*(B*S*H*2))Lab: processes and DTensor
Four Gloo processes implement and with autograd.Function and compare MLP outputs and gradients with the full version. Then ColwiseParallel, RowwiseParallel, and SequenceParallel execute the same pattern with LayerNorm over a CPU mesh. Each rank contributes only its sequence rows to loss, avoiding duplication. This is a small equivalence test, not a GPU benchmark.
import os, subprocess, sys, tempfile
from pathlib import Path
program = r'''
import copy, os, socket, subprocess, sys
import torch
import torch.distributed as dist
P = 4
def worker(rank,port):
torch.set_num_threads(1)
dist.init_process_group('gloo',init_method='tcp://127.0.0.1:'+port,rank=rank,world_size=P)
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.tensor import Shard
from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel, RowwiseParallel, SequenceParallel
class F(torch.autograd.Function):
@staticmethod
def forward(ctx,x): return x
@staticmethod
def backward(ctx,g):
g=g.contiguous().clone();dist.all_reduce(g);return g
class G(torch.autograd.Function):
@staticmethod
def forward(ctx,x):
x=x.contiguous().clone();dist.all_reduce(x);return x
@staticmethod
def backward(ctx,g): return g
class ColumnParallelLinear(torch.nn.Module):
def __init__(self,weight):
super().__init__();self.weight=torch.nn.Parameter(weight.chunk(P,dim=0)[rank].clone())
def forward(self,x): return F.apply(x) @ self.weight.T
class RowParallelLinear(torch.nn.Module):
def __init__(self,weight):
super().__init__();self.weight=torch.nn.Parameter(weight.chunk(P,dim=1)[rank].clone())
def forward(self,x): return G.apply(x @ self.weight.T)
torch.manual_seed(7)
x0=torch.randn(8,8); up=torch.randn(8,8)
reference=torch.nn.Sequential(torch.nn.Linear(8,16,bias=False),torch.nn.Tanh(),torch.nn.Linear(16,8,bias=False))
col=ColumnParallelLinear(reference[0].weight.detach());row=RowParallelLinear(reference[2].weight.detach())
x=x0.clone().requires_grad_(); y=row(torch.tanh(col(x))); (y*up).sum().backward()
xr=x0.clone().requires_grad_();yr=reference(xr);(yr*up).sum().backward()
assert torch.allclose(y,yr,atol=1e-6)
assert torch.allclose(x.grad,xr.grad,atol=1e-6)
assert torch.allclose(col.weight.grad,reference[0].weight.grad.chunk(P,dim=0)[rank],atol=1e-6)
assert torch.allclose(row.weight.grad,reference[2].weight.grad.chunk(P,dim=1)[rank],atol=1e-6)
if rank==0: print('f/g: forward y gradientes coinciden con MLP completo',flush=True)
model=torch.nn.Sequential(torch.nn.Linear(8,16,bias=False),torch.nn.Tanh(),torch.nn.Linear(16,8,bias=False),torch.nn.LayerNorm(8))
base=copy.deepcopy(model)
mesh=init_device_mesh('cpu',(P,))
parallelize_module(model,mesh,{'0':ColwiseParallel(),
'2':RowwiseParallel(output_layouts=Shard(0)),
'3':SequenceParallel(sequence_dim=0)})
xt=x0.clone().requires_grad_(); yt=model(xt)
full=yt.full_tensor()
xb=x0.clone().requires_grad_(); yb=base(xb)
assert torch.allclose(full,yb,atol=1e-6), (rank,(full-yb).abs().max().item())
# Cada rango contribuye con sus filas; la pérdida local no duplica muestras.
(yt.to_local()*up.chunk(P,dim=0)[rank]).sum().backward()
(yb*up).sum().backward()
for a,b in zip(model.parameters(),base.parameters()):
got=a.grad.full_tensor()
assert torch.allclose(got,b.grad,atol=1e-5), (rank,(got-b.grad).abs().max().item())
assert torch.allclose(xt.grad,xb.grad,atol=1e-5), (rank,(xt.grad-xb.grad).abs().max().item())
if rank==0: print('DTensor: columnas, filas y secuencia coinciden con referencia',flush=True)
dist.destroy_process_group()
if len(sys.argv)==3:
worker(int(sys.argv[1]),sys.argv[2])
else:
with socket.socket() as sock:
sock.bind(('127.0.0.1',0));port=str(sock.getsockname()[1])
env=dict(os.environ,PYTHONUTF8='1',OMP_NUM_THREADS='1')
ps=[subprocess.Popen([sys.executable,__file__,str(r),port],stdout=subprocess.PIPE,stderr=subprocess.PIPE,
text=True,encoding='utf-8',errors='replace',env=env) for r in range(P)]
try:
for proc in ps:
out,err=proc.communicate(timeout=120)
if proc.returncode: raise RuntimeError(err or out)
if out.strip(): print(out.strip())
finally:
for proc in ps:
if proc.poll() is None: proc.kill()
for proc in ps: proc.wait()
'''
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / 'tp.py'
script.write_text(program, encoding='utf-8')
env = dict(os.environ, PYTHONUTF8='1', OMP_NUM_THREADS='1')
result = subprocess.run([sys.executable, str(script)], capture_output=True,
text=True, encoding='utf-8', errors='replace', env=env, timeout=180)
if result.returncode:
raise RuntimeError(result.stderr or result.stdout)
print(result.stdout.strip())npm run lab and open the connection link.Exercises
Step 1 of 3. What does rank r compute?
import numpy as np
def vocab_parallel_cross_entropy(local_logits, targets, rank, world):
...b,s,h,a,t=8,2048,4096,32,8
message=b*s*h*2
print('MiB comunicados por rango:',4*2*(t-1)/t*message/2**20)
print('MiB activaciones TP:',s*b*h*(10+24/t+5*a*s/(h*t))/2**20)
print('MiB activaciones TP y secuencia:',s*b*h*(34/t+5*a*s/(h*t))/2**20)