Module contents
Lesson 13 of 28Advanced 110 min

Context and expert parallelism

Two parallelism axes address two modern problems. For contexts of hundreds of thousands of tokens, a single sequence's activations do not fit: context parallelism shards tokens throughout layers and ring attention or Ulysses handles attention with communication. With MoEs containing hundreds of billions of parameters, each GPU hosts experts and tokens travel by all-to-all. We simulate both with exact equality and implement expert parallelism with processes.

After this lesson you can

  • Implement ring attention with logsumexp merging and verify exact equality with full attention.
  • Balance causal load with zigzag or striped partitions.
  • Compare ring attention and Ulysses by communication and head-count restrictions.
  • Implement an expert-parallel MoE layer with variable-size all-to-all dispatch and combine.
  • Estimate MoE all-to-all volume and explain limited dispatch and overlap optimizations.

Before you start

Two distinct dimensions

A long sequence can exhaust activation memory even when model weights fit. Context parallelism distributes positions of one sequence across ranks through all layers. Per-position operations such as an MLP or feature normalization work locally; attention needs information from positions that may reside on other ranks. The partition must preserve global indices for the causal mask and RoPE.

An MoE presents another problem: it has many parameters even though each token uses few experts. The DeepSeek-V3 report describes 671 billion total parameters and 37 billion activated per token. Sparse activation reduces work per token but does not make weights that must be hosted disappear. Expert parallelism distributes those weights and moves activations to their owners. Context and experts are different axes that can be combined.

Ring attention

In ring attention, each rank retains its local Q queries. K and V blocks move around a ring; each round computes the received block’s contribution and merges it with previous ones. After pp blocks each query has seen all permitted keys. The Ring Attention algorithm allows transfer and compute overlap when hardware and block size permit; the next example shows dependencies only and does not measure overlap.

InteractiveOne trip around the ring
GPU 0Q: 0, 1, 2, 3K/V from GPU 0: 0, 1, 2, 310 pairsAccumulated LSE for Q=0: 0.994 (example scores)
GPU 1Q: 4, 5, 6, 7K/V from GPU 1: 4, 5, 6, 710 pairsAccumulated LSE for Q=4: −0.935 (example scores)
GPU 2Q: 8, 9, 10, 11K/V from GPU 2: 8, 9, 10, 1110 pairsAccumulated LSE for Q=8: −0.911 (example scores)
GPU 3Q: 12, 13, 14, 15K/V from GPU 3: 12, 13, 14, 1510 pairsAccumulated LSE for Q=12: 0.997 (example scores)

Scroll to see all columns. Each round adds another block; the accumulator uses a shared maximum and sum of exponentials, not an average of partial softmaxes.

0
Pairs per rank10–58
Total pairs136
Advance rounds and compare partitions. The displayed LSE uses toy scores for each rank's first query; causal pairs count global positions.

It is not enough to average block softmax outputs: each block can have a different probability mass. For one query, maintain maximum mm, sum ℓ\ell, and unnormalized accumulator aa. If the new block has scores sjs_j, value vjv_j, and maximum mbm_b, write m′=max⁡(m,mb)m'=\max(m,m_b) and calculate

ℓ′=em−m′ℓ+∑jesj−m′,a′=em−m′a+∑jesj−m′vj.\ell'=e^{m-m'}\ell+\sum_j e^{s_j-m'},\qquad a'=e^{m-m'}a+\sum_j e^{s_j-m'}v_j.

At the end, a/ℓa/\ell is the full output. If a block is fully masked for a query, it contributes nothing and evaluation of −∞−(−∞)-\infty-(-\infty) is avoided. Summation order can change the last bit: mathematical equality does not imply bitwise floating-point equality. The lab compares with tolerance and explicitly checks a causal mask with global positions.

To understand merging, consider two blocks with very different maxima. If the first has scores near 1000 and the second near 0, direct exponentiation can overflow. Shifting both by the larger maximum makes the smaller block contribute tiny exponentials while the larger remains representable. If an even larger maximum arrives later, both old sum and value accumulator are rescaled: both need the same factor to preserve their ratio. Storing only the first block’s normalized output without its mass ℓ\ell would lose information needed to combine it.

The local query retains its original position even if K/V blocks arrive in another order. A local-index comparison such as k <= q would be incorrect if each block starts at zero: a future-position key could appear as a small local index and pass the mask. Positions also determine the RoPE angle; rotating a key with its local instead of global position changes attention products even with a correct mask.

The first round uses local K/V and each of the next p−1p-1 receives another block. For ordinary multi-head attention with hh total features, sequence TT divisible by pp, and BF16, each rank sends 2(T/p)h⋅2(p−1)2(T/p)h\cdot 2(p-1) bytes of K/V in forward. This counts point-to-point message data, not aggregate traffic per physical link or backward. With GQA, replace hh with total K or V width, which may be smaller than Q’s.

Causality and balance

Causal load increases with position: query ii can attend to i+1i+1 keys counting the diagonal. With contiguous blocks the last rank has more useful pairs than the first. Divide TT into 2p2p equal chunks and give rank rr chunks rr and 2p−1−r2p-1-r. For each position ii in the first there is position T−1−iT-1-i in the second. Their loads sum to (i+1)+(T−i)=T+1(i+1)+(T-i)=T+1; each rank has the same number of pairs and therefore the same number of useful causal pairs.

This argument assumes a full causal triangle and cost proportional to pair count. Partially masked blocks, kernel granularity, documents with additional masks, and traffic can produce different times. Striped Attention uses striped distribution to improve balance; it is not identical to the two-chunk partition. Llama 3 uses symmetric two-chunk assignment and gathers K/V with all-gather before attending to local Q. This simplifies masks but materializes more K/V and exposes communication on the critical path.

In the example with 16 positions and four ranks, contiguous sharding has 10, 26, 42, and 58 useful pairs; total is 136, the sum from 1 to 16. Zigzag retains the same total and gives 34 to each rank. This redistributes work, not reduces pair count. If a sequence contains independent documents, keys from earlier documents may be forbidden and this proof’s symmetry no longer guarantees exact work equality.

All-gather and ring also differ in temporary memory. All-gather can give every rank all K/V before computation; ring can work block by block and retain only schedule-required buffers. The choice is not universal: gathering may simplify a complex mask while ring may exploit overlap. In GQA, narrower K/V reduce bytes in both cases but do not change the need to attend to all permitted keys for each query head.

Exchange sequence for heads

Ulysses initially shards sequence. An all-to-all redistributes Q, K, and V so each rank receives every position for a subset of heads; it computes attention for those heads and another all-to-all returns output to the sequence partition. The idea and analysis appear in DeepSpeed-Ulysses. For simple sharding without replication, both Q and KV head counts must be divisible by pp; with GQA, KV head count may be the stricter limit. Other variants can replicate or redistribute KV but change cost.

InteractiveUlysses versus ring
  • Ring
  • Ulysses

BF16, 32 query heads, dimension 128, no additional batches. The model counts bytes sent outside the rank in forward and excludes KV replication, congestion and backward. Simple Ulysses requires both head counts divisible by the number of ranks.

Ranks
KV heads
50
20
Ring at 128 Ki tokens (MiB)448.0
Ulysses at 128 Ki tokens (MiB)280.0
Causal-forward model with no communication overlap and fixed throughput; change bandwidth, latency, and KV heads. Values are not measurements and exclude backward.

With HH Q heads, HKVH_{KV} K/V heads, dimension dd, and two bytes per element, volume sent outside a rank by the two ideal forward all-to-alls is (2H+2HKV)(T/p)d⋅2(p−1)/p(2H+2H_{KV})(T/p)d\cdot2(p-1)/p. It counts Q, K, V, and output and excludes the shard remaining local. Comparison with ring depends on HKVH_{KV}, latency, topology, granularity, and overlap. The chart adds modeled compute and communication time; it does not establish which system wins on a real machine.

The Ulysses transformation permutes data; it does not approximate attention. Before the first exchange each rank owns a shard of positions for all heads; afterward it owns all positions for some heads. The causal mask still uses full-sequence order. The inverse exchange gathers each position’s heads on the rank that owned that position. The second all-to-all is needed so subsequent operations receive the expected layout.

For conventional attention with 32 heads of dimension 128, T=128⋅1024T=128\cdot1024 and p=8p=8, the formulas’ assumptions give 1792 MiB per rank for ring and 448 MiB for Ulysses in forward. Here K and V have the same width as Q. With GQA and eight KV heads, the values change differently because Q and output still have 32 heads while K/V have eight. Neither figure includes latency, backward, temporary memory, or traffic from the rest of the transformer.

Experts and all-to-all

Expert parallelism places subsets of experts on different ranks. A router assigns each token to kk experts; the first all-to-all sends activations and metadata to their owners, who compute their functions, and a second exchange returns contributions. The origin multiplies by gate weights and sums. If one activation goes to multiple experts, an implementation can send separate copies or group destinations and replicate afterward: accounting must state which.

InteractiveDispatch to experts

Accepted sends: rows = source GPU, columns = expert GPU. The diagonal is local work, not network traffic.

SourceGPU 0GPU 1GPU 2GPU 3
GPU 02222
GPU 13320
GPU 21131
GPU 32010
Token 0: E3→GPU1, E4→GPU2
Token 1: E5→GPU2, E2→GPU1
Token 2: E1→GPU0, E6→GPU3
Token 3: E1→GPU0, E6→GPU3
Token 4: E2→GPU1, E5→GPU2
Token 5: E4→GPU2, E3→GPU1
Token 6: E0→GPU0, E1→GPU0
Token 7: E1→GPU0, E3→GPU1
Token 8: E0→GPU0, E5→GPU2
Token 9: E7→GPU3, E3→GPU1
Token 10: E5→GPU2, E4→GPU2
Token 11: E1 dropped, E3 dropped
Token 12: E1 dropped, E3 dropped
Token 13: E0→GPU0, E3 dropped
Token 14: E5 dropped, E4→GPU2
Token 15: E0→GPU0, E1 dropped

Accepted experts: 4 · 4 · 2 · 4 · 4 · 4 · 2 · 1. Capacity priority is token and top-2 position; weights are not renormalized after dropping.

1.0
Capacity per expert4
Dropped assignments7
Minimum–maximum load3–8
The matrix counts accepted assignments by origin and destination; the diagonal remains local. Limiting to one node changes expert selection in the example.

Per-expert capacity is often expressed as ⌈cNk/E⌉\lceil cNk/E\rceil for NN global tokens, EE experts, and factor cc. A policy must specify which assignments it rejects when requests exceed capacity; the lab uses global order by token and top-k position and does not renormalize gates after dropping. Other implementations may sort by score, reroute, or avoid dropping. Measure actual load per expert and rank: low auxiliary loss does not guarantee no spikes in every batch.

Total capacity can equal the total number of assignments and still produce drops. If every token chooses the same two experts, they can fill while others remain empty. The capacity factor controls a tradeoff between reserved space and drop risk; it does not automatically correct router bias. In the lab each expert first accepts assignments with smallest global indices and others return as zero contribution. Preserving that rule in the reference is essential to compare the same problem.

A variable all-to-all needs each receiver to know how many rows to expect from each origin. First exchange a count vector; then allocate the receive buffer and transmit rows and metadata with those sizes. Returning results reverses input and output sizes. Order must preserve correspondence among contribution, token, and expert, even if a destination receives no rows. The example includes zero-element origin-destination pairs and compares each token’s final sum.

With 16 Ki tokens per rank, top-8, width 7168, and BF16, sending one copy per assignment means 16384⋅8⋅7168⋅2=179216384\cdot8\cdot7168\cdot2=1792 MiB of dispatch input per rank. If destinations are perfectly balanced over 64 ranks and the local fraction is excluded, 1792⋅63/64=17641792\cdot63/64=1764 MiB are sent outside the rank. This calculation precedes drops, metadata, grouping, and return; it does not predict traffic for a specific router.

MoE communication optimization can limit nodes each token visits, group transfers, and overlap dispatch with expert work. Changing the destination set also changes the routing problem, not just the network. DeepEP provides specialized communication kernels; behavior and performance depend on topology, precision, and configuration. Combining EP with DP and TP requires defined groups: distinct experts are partitioned over EP, replicas of one expert synchronize gradients through their data group, and TP can split each expert. Do not reduce gradients of distinct experts as if they were replicas.

Lab: two attention layouts

The next code simulates ranks in NumPy: Q remains local for ring; Ulysses exchanges sequence for heads and then reassembles output. It compares both outputs with full float64 causal attention. FLOPs are useful causal pairs times 4Hd4Hd for QK and PV; NumPy does not necessarily avoid masked operations. Bytes are a BF16 forward model, not a measurement of the dtype used in computation.

[ ]Ring and Ulysses in NumPyBrowser
import numpy as np

def zigzag_partition(T, p):
    assert T % (2*p) == 0
    chunks = np.split(np.arange(T),2*p)
    return [np.concatenate((chunks[r],chunks[2*p-1-r])) for r in range(p)]

def step(q,k,v,qi,ki,m,l,acc):
    # q/k/v: (tokens, heads, head_dim); m,l: (tokens, heads).
    scores=np.einsum('qhd,khd->qhk',q,k)/np.sqrt(q.shape[-1])
    scores=np.where(ki[None,None,:] <= qi[:,None,None],scores,-np.inf)
    blockmax=scores.max(axis=-1)
    newmax=np.maximum(m,blockmax)
    valid=np.isfinite(newmax)
    safe=np.where(valid,newmax,0.)
    oldscale=np.where(np.isfinite(m),np.exp(m-safe),0.)
    weights=np.exp(scores-safe[:,:,None])
    new_l=l*oldscale+weights.sum(axis=-1)
    acc=acc*oldscale[:,:,None]+np.einsum('qhk,khd->qhd',weights,v)
    return newmax,new_l,acc

def full(q,k,v):
    T=q.shape[0]; scores=np.einsum('qhd,khd->qhk',q,k)/np.sqrt(q.shape[-1])
    scores=np.where(np.arange(T)[None,None,:]<=np.arange(T)[:,None,None],scores,-np.inf)
    weights=np.exp(scores-scores.max(axis=-1,keepdims=True)); weights/=weights.sum(axis=-1,keepdims=True)
    return np.einsum('qhk,khd->qhd',weights,v)

def ring(q,k,v,parts):
    p=len(parts); out=np.zeros_like(q); pairs=[]
    for rank,qi in enumerate(parts):
        m=np.full((len(qi),q.shape[1]),-np.inf); l=np.zeros_like(m); acc=np.zeros_like(q[qi]); work=0
        for turn in range(p):
            ki=parts[(rank-turn)%p]
            m,l,acc=step(q[qi],k[ki],v[ki],qi,ki,m,l,acc)
            work+=int((ki[None,:]<=qi[:,None]).sum())
        assert np.all(l>0)
        out[qi]=acc/l[:,:,None]; pairs.append(work)
    return out,pairs

def ulysses(q,k,v,parts):
    # Primer all-to-all: secuencia local/cabezas completas a secuencia
    # completa/subconjunto de cabezas. El segundo devuelve el layout inicial.
    p=len(parts); heads=q.shape[1]; assert heads%p==0
    received=[]
    for dst in range(p):
        sl=slice(dst*heads//p,(dst+1)*heads//p)
        order=np.concatenate(parts); inverse=np.argsort(order)
        Q=np.concatenate([q[ids,sl] for ids in parts])[inverse]
        K=np.concatenate([k[ids,sl] for ids in parts])[inverse]
        V=np.concatenate([v[ids,sl] for ids in parts])[inverse]
        received.append(full(Q,K,V))
    result=np.empty_like(q)
    for rank,ids in enumerate(parts):
        result[ids]=np.concatenate([x[ids] for x in received],axis=1)
    return result

rng=np.random.default_rng(42); T,H,D,p=16,4,4,4
q=rng.normal(size=(T,H,D)); k=rng.normal(size=q.shape); v=rng.normal(size=q.shape)
ref=full(q,k,v)
for name,parts in [('contiguo',list(np.split(np.arange(T),p))),('zigzag',zigzag_partition(T,p))]:
    out,pairs=ring(q,k,v,parts); np.testing.assert_allclose(out,ref,rtol=1e-12,atol=1e-12)
    np.testing.assert_allclose(ulysses(q,k,v,parts),ref,rtol=1e-12,atol=1e-12)
    print(name,'pares causales por rango',pairs,'FLOPs útiles QK+PV', [4*H*D*x for x in pairs])
bytes_per=2  # BF16 hipotético, no dtype de la simulación float64
print('bytes BF16 enviados por rango en forward: ring',2*(T//p)*H*D*bytes_per*(p-1),
      'Ulysses',4*(T//p)*H*D*bytes_per*(p-1)//p)
print('Salidas equivalentes con tolerancia numérica, para ambas particiones')

Lab: experts across four processes

The example layer uses eight deterministic experts, top-2, and 16 tokens distributed over four Gloo processes. To simplify the reference, each process generates the same global data and gates but dispatches only its own tokens; a real implementation must also send necessary gates or apply them at the origin. Counts are exchanged first, then metadata and activations with all_to_all_single and variable sizes. The owner applies per-expert capacity and the inverse exchange returns contributions, including rejected ones as zero. Outputs and load are checked against a monolithic reference with the same policy. This is a CPU forward test; it does not measure performance or verify distributed backward.

[ ]Dispatch and combine with GlooLocal GPU
import subprocess, sys, tempfile
from pathlib import Path
script = '''
import os, socket, math
import torch
import torch.distributed as dist
import torch.multiprocessing as mp

P, E, N, D, K = 4, 8, 4, 3, 2
CAPACITY_FACTOR = 0.75

def data():
    generator=torch.Generator().manual_seed(123)
    x=torch.randn(P*N,D,generator=generator)
    logits=torch.randn(P*N,E,generator=generator)
    scores, ids=torch.topk(logits,K,dim=-1)
    gates=scores.softmax(dim=-1)
    return x, ids, gates

def expert(x, e):
    return torch.tanh(x*(e+1)/E + (e-3)/10)

def reference(x, ids, gates, cap):
    out=torch.zeros_like(x); used=[0]*E
    # El orden total (token, posición top-k) define qué asignaciones caben.
    for token in range(P*N):
        for slot in range(K):
            e=int(ids[token,slot])
            if used[e]<cap:
                out[token]+=gates[token,slot]*expert(x[token],e)
                used[e]+=1
    return out, used

def worker(rank, port):
    os.environ['MASTER_ADDR'],os.environ['MASTER_PORT']='127.0.0.1',str(port)
    torch.set_num_threads(1)
    dist.init_process_group('gloo',rank=rank,world_size=P)
    x, ids, gates=data(); cap=math.ceil(CAPACITY_FACTOR*(P*N*K)/E)
    expected,used=reference(x,ids,gates,cap)
    routes=[]
    for token in range(rank*N,(rank+1)*N):
        for slot in range(K):
            e=int(ids[token,slot]); routes.append((e//(E//P),token,slot,e))
    routes.sort(key=lambda z:z[0])
    send_counts=torch.tensor([sum(route[0]==r for route in routes) for r in range(P)],dtype=torch.int64)
    recv_counts=torch.empty_like(send_counts)
    dist.all_to_all_single(recv_counts,send_counts)
    ins=send_counts.tolist(); outs=recv_counts.tolist()
    meta=torch.tensor([[token,slot,e] for _,token,slot,e in routes],dtype=torch.int64)
    payload=torch.stack([x[token] for _,token,_,_ in routes])
    recv_meta=torch.empty((sum(outs),3),dtype=torch.int64)
    recv_x=torch.empty((sum(outs),D))
    dist.all_to_all_single(recv_meta,meta,output_split_sizes=outs,input_split_sizes=ins)
    dist.all_to_all_single(recv_x,payload,output_split_sizes=outs,input_split_sizes=ins)
    # Los recibidos están agrupados por origen; el límite usa orden global.
    result=torch.zeros_like(recv_x); counts={e:0 for e in range(rank*(E//P),(rank+1)*(E//P))}
    order=sorted(range(len(recv_meta)),key=lambda j:(int(recv_meta[j,0]),int(recv_meta[j,1])))
    for j in order:
        token,slot,e=map(int,recv_meta[j]); assert e in counts
        if counts[e] < cap:
            result[j]=gates[token,slot]*expert(recv_x[j],e); counts[e]+=1
    returned=torch.empty((sum(ins),D))
    dist.all_to_all_single(returned,result,output_split_sizes=ins,input_split_sizes=outs)
    local=torch.zeros((N,D))
    for j,(_,token,slot,e) in enumerate(routes): local[token-rank*N]+=returned[j]
    torch.testing.assert_close(local,expected[rank*N:(rank+1)*N],rtol=1e-6,atol=1e-7)
    local_count=torch.tensor([sum(counts.values())]); all_counts=[torch.zeros_like(local_count) for _ in range(P)]
    dist.all_gather(all_counts,local_count)
    if rank==0: print('Capacidad por experto:',cap,'carga aceptada por rango:',[int(a) for a in all_counts], 'descartadas:',P*N*K-sum(used),flush=True)
    print('Rango',rank,'envios',ins,'recepciones',outs,'coincide con referencia',flush=True)
    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) / "experts.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)
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 that symmetric partitioning equalizes useful causal pairs.
The proof will appear here as you work.

Step 1 of 2. How many keys does query i see, including the diagonal?

Numeric
For 16 Ki tokens per rank, top-8, h=7168 and BF16, how many MiB enter dispatch per rank before excluding local destinations and drops?
Numeric
For T=128 Ki, 32 heads of dimension 128, p=8 and BF16, how many MiB does each rank send in ring forward, counting K and V?
Numeric
In the same multi-head attention example, how many MiB does each rank send outside itself in Ulysses's two forward all-to-alls?
Code
Implement zigzag_partition(T, p), returning p lists of global positions; T is divisible by 2p and each rank receives chunks r and 2p−1−r.
def zigzag_partition(T,p):
  ...
Shift+Enter to run
Code
Implement merge(m, l, a, scores, values) for one query. scores has shape (n,), values (n,d), with masked scores at −inf. Return maximum, exponential sum, and unnormalized accumulator. Preserve state for a fully masked block.
import numpy as np
def merge(m,l,a,scores,values):
  ...
Shift+Enter to run
Quiz
With few KV heads and more context ranks than KV heads, what follows for simple Ulysses without replication?
Key idea
Context shards positions and experts shard conditional parameters. K/V or token movement, masking, and effective load determine communication and balance.