advanced27 min studyLesson 555 in Engineering

Context parallel attention: exchange keys and merge softmax globally

Compute attention over remote token chunks using correct global normalization rather than averaging independently normalized outputs.

On this page

What you’ll understand

  • Explain why local queries need remote keys and values under full attention.
  • Merge stable blockwise softmax summaries exactly in real arithmetic.
  • Preserve global masks, positions, and backward contributions across context owners.

Context parallelism partitions token positions through more of the model, so each rank can keep a smaller sequence activation slice. Attention is the important cross-token exception: a local query may need keys and values owned elsewhere. Gathering or exchanging KV chunks supplies those dependencies. Correctness also requires one normalization over all permitted keys, not a separate softmax per chunk followed by an unweighted average. We use the Ring Attention principle and Megatron Core 0.15.0’s documented context-parallel boundary.

Local queries do not imply local-only attention

For full attention, each query compares against all valid keys in its sequence; for causal attention, it compares against the permitted global prefix. A rank owning token positions must still access remote KV needed by those queries. Implementations can all-gather, exchange chunks in a ring, or use other supported strategies. The exact traffic and overlap depend on placement, head sharing, chunk size, and algorithm. There is no universal collective count implied by saying context parallel.

Global token positions determine causal masks and positional encodings. Treating each local chunk as a new sequence can expose future keys or hide required earlier keys. Packed variable-length sequences also need boundaries that prevent attention across different examples. GQA can reduce the number of KV features exchanged but does not remove the remote-key dependency. Backward must return and combine contributions to the owners of K and V; a correct forward result alone does not establish correct parameter training.

o=∑jesj−mvj∑jesj−m,m=max⁡j∈Jsjo=\frac{\sum_j e^{s_j-m}v_j}{\sum_j e^{s_j-m}},\qquad m=\max_{j\in J}s_j
J contains all globally permitted keys for one query, scores s_j include the intended scaling and mask, and v_j are value vectors. Scores are dimensionless; o has the value-vector units. At least one permitted finite score is assumed.↔ Scroll wide equations horizontally.

Merge unnormalized summaries, not local averages

A chunk can summarize its maximum score m, scaled exponential denominator ℓ, and scaled value numerator z. To combine two chunks, rescale both summaries to the larger maximum before adding denominator and numerator. Divide only after all required contributions are included. This produces the same mathematical attention as a global softmax in exact arithmetic while avoiding overflow from unshifted exponentials. Floating-point rounding still depends on block order and accumulation precision.

An all-masked chunk needs a defined neutral-summary handling so expressions such as minus-infinity minus minus-infinity do not create NaNs. A query with no permitted keys requires the model’s explicit convention rather than this ordinary positive-denominator formula. Dropout and backward intermediates also need matching global randomness and reconstruction rules. Do not reuse a simplified scalar summary as if it specified every implementation detail of a production fused attention kernel.

m=max⁡(ma,mb),ℓ=ema−mℓa+emb−mℓb,z=ema−mza+emb−mzbm=\max(m_a,m_b),\quad \ell=e^{m_a-m}\ell_a+e^{m_b-m}\ell_b,\quad z=e^{m_a-m}z_a+e^{m_b-m}z_b
Each nonempty chunk summary uses its own maximum, ℓ=sum exp(score−maximum), and z=sum exp(score−maximum)×value. The merged output is z/ℓ. Empty or all-masked chunks need explicit neutral handling, and ℓ must be positive before division.↔ Scroll wide equations horizontally.

Balance work without changing the visible context

A simple contiguous causal partition can make early query chunks do less attention work than later ones. A supported zigzag or balanced layout can redistribute that work while preserving global positions. Such a layout changes ownership, not the allowed attention relation. Record both the logical token order and the physical chunk assignment. Memory savings depend on retained KV, intermediate summaries, communication buffers, and backward recomputation; exchanging chunks does not imply that every rank stores every full-sequence activation permanently.

The network lab shows only one local computation. Reset, set x=2 and w=1, predict sigmoid(1.5)≈0.818, then Step. Its single scalar graph has no attention softmax, KV exchange, masking, or distributed summary merge. It helps distinguish an inspectable computation from the additional dependencies a distributed version must preserve. The worked summary arithmetic, rather than the diagram, proves the correct normalization across the two chunks.

Two key chunks produce one globally normalized answer

One query has scores [0,ln 2,ln 3,ln 4] and scalar values [1,2,3,4]. Rank 0 owns the first two keys and rank 1 the last two. Every key is permitted.

  1. Rank 0 uses ma=ln 2, giving ℓa=1/2+1=1.5 and za=(1/2)×1+1×2=2.5. Rank 1 uses mb=ln 4, giving ℓb=3/4+1=1.75 and zb=(3/4)×3+1×4=6.25.

  2. The merged maximum is ln 4. Rank 0’s rescale factor is 1/2 and rank 1’s is 1, so ℓ=0.5×1.5+1.75=2.5 and z=0.5×2.5+6.25=7.5.

  3. The global output is 7.5/2.5=3, matching weights[1,2,3,4]/10 applied to values[1,2,3,4]. Averaging the independently normalized local outputs would use the wrong chunk weights.

The result

Stable unnormalized summaries preserve the global softmax denominator. Local normalized answers cannot generally be averaged equally.

Explore the model

Interactive lab

Interactive lab · network

Local computation still needs complete dependencies

Reset, set x=2 and w=1, predict σ(1.5)≈0.818, then Step. This scalar sigmoid graph does not model attention, softmax chunks, KV exchange, masks, or backward collectives.

Local computation still needs complete dependenciesOne inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. Current readings: Product · wx: 1.2; Logit · wx − 0.5: 0.7; Sigmoid output: 0.6682. All parameters are adjustable with the labeled controls below.One input. One weight. One sigmoid.x1.20× w1.20+ b0.70σ0.668output0.668w = 1.00b = −0.50σ(z) = 1 / (1 + exp(−z))
Computation graphSignal trace
Product · wx
1.2
Logit · wx − 0.5
0.7
Sigmoid output
0.6682
t = 0 s

One inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forDistributing a calculation adds ownership and dependency obligations beyond executing a local formula.

Check your understanding

Why is the unweighted average of two chunk-local attention outputs generally wrong?

Try it yourself

Two already-common-scaled chunks have denominators 2 and 3 and scalar numerators 4 and 12. Compute the merged output, then compare with the equal average of local outputs.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Add unnormalized quantities before dividing.

Compare with the solution

The merged output is(4+12)/(2+3)=16/5=3.2. The equal average of local outputs is(4/2+12/3)/2=(2+4)/2=3, which differs because denominator masses are unequal. If chunk maxima differed, rescale before adding these quantities.

Take it with you

  • Local queries require all globally permitted KV dependencies.
  • Merge stable softmax numerators and denominators before division.
  • Global positions, masks, owner gradients, and memory lifetimes remain part of equivalence.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.