Module contents
Lesson 11 of 28Advanced 115 min

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.

InteractiveWhere the sum appears

Global: X 1024 × 1024 · W 1024 × 2048 · Y 1024 × 2048

Rank 0

W shard

X: 1024 × 1024

W: 1024 × 512

Y: 1024 × 512

Rank 1

W shard

X: 1024 × 1024

W: 1024 × 512

Y: 1024 × 512

Rank 2

W shard

X: 1024 × 1024

W: 1024 × 512

Y: 1024 × 512

Rank 3

W shard

X: 1024 × 1024

W: 1024 × 512

Y: 1024 × 512

W partition
CollectiveBackward
Collective payload (MiB)2.00
Sent per rank and collective (MiB)3.00
Switch between columns, rows, and two layers, and change rank count. With columns each rank computes a different part of Y; with rows each computes a contribution to all of Y. With two layers, column then row keeps the intermediate activation local. The byte readout assumes BF16 and an ideal ring, counting bytes sent per rank and collective.

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 tt and topology matter as much as tensor shapes.

Two ways to split a multiplication

Use example vectors in rows: X∈Rm×kX\in\R^{m\times k}, W∈Rk×nW\in\R^{k\times n}, Y=XWY=XW. 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 WW. This convention avoids confusing the split name with a storage axis.

For columns, if output gradient is sharded as G=[G1  ⋯  Gt]G=[G_1\;\cdots\;G_t], the chain rule gives ∇X=∑rGrWr⊤\grad_X=\sum_r G_rW_r\T and ∇Wr=X⊤Gr\grad_{W_r}=X\T G_r. For rows, after receiving the same GG, each rank computes ∇Xr=GWr⊤\grad_{X_r}=GW_r\T and ∇Wr=Xr⊤G\grad_{W_r}=X_r\T G. 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 tt times.

Shapes let us check the argument without relying on axis names. With columns, WrW_r has shape k×(n/t)k\times(n/t) and GrG_r shape m×(n/t)m\times(n/t). Thus GrWr⊤G_rW_r\T has shape m×km\times k, that of the full input; all ranks contribute to the same positions. X⊤GrX\T G_r, by contrast, has shape k×(n/t)k\times(n/t) and belongs only to shard WrW_r.

With rows, XrX_r is m×(k/t)m\times(k/t) and WrW_r is (k/t)×n(k/t)\times n. The local product already has shape m×nm\times n, but is not yet the full output. After summing those products, the derivative with respect to each XrX_r has only k/tk/t 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 Z=ϕ(XW1)W2Z=\phi(XW_1)W_2 with W1=[W1,r]W_1=[W_{1,r}] split by columns and W2=[W2,r⊤]⊤W_2=[W_{2,r}\T]\T by rows. Each rank computes Zr=ϕ(XW1,r)W2,rZ_r=\phi(XW_{1,r})W_{2,r} and the sum is Z=∑rZrZ=\sum_r Z_r. The nonlinearity is applied to each independent column before the sum. Generally ϕ(∑rUr)≠∑rϕ(Ur)\phi(\sum_r U_r)\ne\sum_r\phi(U_r), so moving it after partial sums changes the network.

Operator ff represents branching a replicated input: identity in forward and summation of ∇X\grad_X contributions in backward. gg 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 Ur=XW1,rU_r=XW_{1,r} and Hr=ϕ(Ur)H_r=\phi(U_r). Column rr of HH depends only on UrU_r and feeds exactly row block W2,rW_{2,r}. No rank needs HjH_j to compute HrW2,rH_rW_{2,r}. In backward each rank receives the same output gradient of the sum and locally computes derivatives of its W2,rW_{2,r}, HrH_r, and W1,rW_{1,r}. Branches are summed only when returning to the shared input.

The backward identity of gg 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.

InteractiveThrough a block

Example: b = 8, s = 2048, h = 4096, a = 32, t = 8.

1. Normalization: replicated
2. f: identity
3. Q, K, V: local heads
4. Projection: partial sum
5. g: all-reduce
6. MLP: columns, local activation, rows
7. g: all-reduce
Pass
Estimated activations (MiB/layer/rank)1472.00
Switch between forward and backward and enable sequence sharding. Memory readouts use the published formula for the specified fixed example; rows are a placement schematic, not an execution trace.

Multi-head attention is split by heads: each rank obtains its columns of Q,K,VQ,K,V, 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 tt 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 tt 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 zz and label yy, loss is log⁡∑jezj−zy\log\sum_j e^{z_j}-z_y. Each rank computes its local maximum and a max reduction obtains m=max⁡jzjm=\max_j z_j. Each rank then sums exp⁡(zj−m)\exp(z_j-m) over its shard, and a sum reduction gives the global denominator. Only the owner of yy contributes zyz_y to another sum. Thus

ℓ=m+log⁡(∑r∑j∈Vrezj−m)−zy.\ell=m+\log\left(\sum_r\sum_{j\in V_r}e^{z_j-m}\right)-z_y.

Subtracting the maximum prevents overflow without changing probabilities. The local gradient is pj−1[j=y]p_j-\mathbf{1}[j=y]. 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, sbh(10+24/t+5as/(ht))sbh(10+24/t+5as/(ht)) bytes per layer and rank with TP, and sbh(34/t+5as/(ht))sbh(34/t+5as/(ht)) with TP plus sequence. Here ss is length, bb batch, hh hidden width, aa heads, and tt 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 dd, 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.

InteractiveCompose placements

2 × 2 mesh; X is M × K and W is K × N. Each grid represents the local region of a matrix divisible by four.

  • X local
  • W local
Rank (0, 0)
Rank (0, 1)
Rank (1, 0)
Rank (1, 1)

Axis 0: Partial. Axis 1: Shard(0).

Partial represents contributions that must be summed; use all-reduce to obtain a replica. To shard the output, use reduce-scatter. If Redistribute is shown, first change input layouts.

Output, axis 0Partial
Output, axis 1Shard(0)
Choose X and W placements independently on each axis. Initially axis 0 shards the contraction dimension and output is Partial; axis 1 shards rows. What communication is needed for replicated output?

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 XX and Shard(0) of WW split the same contraction dimension kk. Each local product contributes to every position of YY, so its output is Partial. By contrast, Shard(0) of XX with replicated WW splits output rows and produces Shard(0). Dimension numbers refer to the particular tensor: Shard(0) of XX and Shard(0) of WW 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.

InteractiveCost when crossing nodes
  • Hypothetical fast link
  • Changes link after 8 GPUs
10
50
Time at 16 GPUs (ms)78.25
Communication fraction at 1696.0 %
The model assumes four all-reduces per layer, a 0.1 GB BF16 message, 1 μs latency per phase, ideally divided compute, and 100 GB/s within a node. Beyond eight ranks it switches to the chosen bandwidth. These are illustrative values, not a measurement of NVLink or a specific network.

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 M=0.1M=0.1 GB collective in an ideal ring takes 2(t−1)α+2(t−1)M/(tβ)2(t-1)\alpha+2(t-1)M/(t\beta), with α=0.001\alpha=0.001 ms and β\beta in GB/s. Four collectives and assumed compute C/tC/t 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.

[ ]Four-rank simulationBrowser
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 ff and gg 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.

[ ]f, g and DTensor with GlooLocal GPU
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())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: Prove the communication needed in backward for Y = XW with W split by columns.
The proof will appear here as you work.

Step 1 of 3. What does rank r compute?

Numeric
With b=8, s=2048, h=4096, BF16 and t=8, how many MiB does each rank send in total for four all-reduces of a b×s×h tensor using an ideal ring?
Numeric
For b=8, s=2048, h=4096, a=32 and t=8, calculate in MiB activation memory per layer and rank from the TP formula without sequence parallelism.
Numeric
With the same parameters, calculate the TP plus sequence-parallelism formula in MiB.
Code
Implement vocab_parallel_cross_entropy(local_logits, targets, rank, world) in a sequential simulator: local_logits is the list of arrays from all ranks, shaped (batch, local_vocabulary), with equal consecutive shards. rank identifies the emulated rank and world the number of shards. Simulate global reductions and return the same loss per row on every rank without concatenating logits.
import numpy as np
def vocab_parallel_cross_entropy(local_logits, targets, rank, world):
  ...
Shift+Enter to run
Quiz
A block has 8 KV heads. Why does splitting it across 16 TP ranks require a strategy beyond assigning complete KV heads without replication?
[ ]Check costsBrowser
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)
Key idea
Splitting columns then rows keeps the nonlinearity local and reduces communication to one sum per sublayer; sequence parallelism shards activations otherwise replicated. Topology and layout determine actual cost.