Pidoku

Sequence and Context Parallelism

Module 14 Lesson 14.f 1h Difficulty 4/5

Prerequisites 14.c, 12.h, 10.g, 13.l


Before you start: words you need#

WordPlain meaning
Sequence dimensionThe “which token” axis of a tensor. Splitting along it means each GPU gets some of the tokens, rather than some of the weights.
Context parallelism (CP)Splitting one request’s tokens, and their KV cache, across GPUs so attention over a very long context is shared out.
Sequence parallelism (SP)An older, narrower idea from Megatron: inside a TP group, run the norms and other per-token work on 1/N of the tokens each (14.c). Often confused with CP.
Online softmaxComputing softmax piece by piece while keeping a running maximum and running sum, so partial results from different blocks of keys can be merged exactly (10.g). FlashAttention is built on it (13.l).
Ring attentionA CP method: GPUs pass blocks of keys and values around a ring, each adding its share to an online-softmax accumulator.
Causal maskIn a decoder, token t may only attend to tokens 0…t. Later tokens therefore do more attention work than earlier ones.
LSE (log-sum-exp)The running softmax denominator, in log form. GPUs exchange it to merge partial attention results.

1. What is it?#

Tensor parallelism splits the weights. Context parallelism splits the tokens of one sequence.

TP:   every GPU sees every token, holds 1/N of each weight (and 1/N of the KV heads)
CP:   every GPU holds the weights it would hold anyway, but only 1/N of this request's tokens
      and their KV cache
flowchart LR
  subgraph REQ["One 1M-token request"]
    T0["tokens 0-250k"] --- T1["250k-500k"] --- T2["500k-750k"] --- T3["750k-1M"]
  end
  T0 --> G0["GPU 0<br/>KV for its tokens"]
  T1 --> G1["GPU 1<br/>KV for its tokens"]
  T2 --> G2["GPU 2<br/>KV for its tokens"]
  T3 --> G3["GPU 3<br/>KV for its tokens"]
  G0 -->|"K,V blocks"| G1 -->|"K,V blocks"| G2 -->|"K,V blocks"| G3 -->|"K,V blocks"| G0

  class T0,T1,T2,T3 neutral
  class G0,G1,G2,G3 memory

There are two separate uses, and engines expose them separately:

  • Prefill CP shortens time to first token for a huge prompt by sharing the quadratic attention work (ring attention and its relatives).
  • Decode CP shards one sequence’s KV cache by token so a single long conversation fits, and so KV is not duplicated when the TP group is wider than the number of KV heads.

Facts checked on 12 November 2026.


2. Why does it exist?#

PROBLEM   1M-token contexts are now standard on frontier open models (DeepSeek-V4, Kimi K3,
          GLM-5.3, Qwen3.6 extended). One request's prefill takes minutes on one TP group, and
          its KV cache can exceed one GPU's free memory.
WHY       Attention work grows with S² in prefill (12.h). TP cannot split attention further
          than the number of KV heads (14.c); MLA models have effectively one.
FIX       Split the sequence. Each GPU owns a slice of the tokens; attention is computed
          piece by piece and merged exactly with online softmax.

TRADE-OFFS
  ✓ prefill latency falls nearly linearly with CP size for long prompts
  ✓ one sequence's KV can exceed one GPU
  ✓ removes KV duplication when TP > number of KV heads
  ✗ attention itself now communicates, every layer
  ✗ causal masking makes naive splits badly unbalanced
  ✗ only pays off for very long contexts; below ~32k tokens it is overhead

3. Simple analogy#

Four people each hold one chapter of a long book, and each must write a summary of the whole book from their chapter’s point of view.

Instead of photocopying the whole book for everyone (an all-gather: expensive), they pass the chapters around the table. Each reads the chapter in front of them, updates their notes, and passes it on. After one full lap, everyone has seen every chapter and their notes are complete. Online softmax is the note-taking method that makes “update as you go” give exactly the same summary as reading everything at once.


4. Tiny example: why a contiguous split is unfair#

16 tokens on 4 GPUs, causal mask. Count the query–key pairs each GPU must compute:

contiguous split   GPU 0: tokens 0-3    GPU 1: 4-7    GPU 2: 8-11    GPU 3: 12-15
work (pairs)              10                 26            42             58

GPU 3’s tokens attend to almost everything; GPU 0’s attend to almost nothing. The ring takes as long as GPU 3, so the group runs at 59% efficiency.

Zigzag (also called striped or load-balanced) assignment cuts the sequence into 2N chunks and gives GPU g chunk g and chunk 2N−1−g: one early chunk and one late chunk each. Now every GPU does 34 pairs. Section 6 runs both layouts and checks that the answer is exact.


5. Technical explanation#

Ring attention (prefill)#

Each GPU i holds Q_i, K_i, V_i for its own tokens.
for step r in 0 .. N-1:
    compute attention of Q_i against the K,V block it holds now   (FlashAttention, 13.l)
    merge into the running (max, sum, output) — online softmax       (10.g)
    send that K,V block to GPU i+1, receive one from GPU i-1        (overlapped with compute)
after N steps every query has seen every key: the result is exact
  • Traffic per GPU per layer is about the size of the whole sequence’s K and V for that layer, independent of N, and it overlaps with the attention compute of the current block.
  • The overlap only works when the block is big enough. Compute per block grows with (S/N)²; the transfer grows with S/N. Long prompts hide the transfer completely; short ones do not.
  • Pass-KV versus pass-Q. When a large KV cache already exists (a follow-up turn on a cached 1M-token document) and the new tokens are few, it is cheaper to circulate the small Q block and the partial outputs instead. Meta’s context-parallelism paper uses both variants and reports 1M-token prefill of Llama 3 405B in 77 s on 128 H100s, at 93% parallel efficiency (paper’s own result).

Ulysses (all-to-all) attention#

DeepSpeed-Ulysses swaps axes instead of passing blocks: an all-to-all turns “each GPU has some tokens, all heads” into “each GPU has all tokens, some heads”, standard attention runs locally, and a second all-to-all turns it back.

RingUlysses
Communicationpoint-to-point, overlappedtwo all-to-alls per layer, harder to hide
Kernelneeds a merge stepordinary attention kernel
Limitnone from headsCP size ≤ number of heads (KV heads with GQA)
Good forvery long prompts, many GPUs, MLAGQA/MHA models inside one NVLink domain

Many systems combine them: Ulysses inside a server, ring across servers.

Decode context parallelism#

Decode has one new query per sequence. Splitting the KV cache by token still helps, because the cost of a long-context decode step is reading that KV (12.h):

each GPU: attention of the one query against ITS slice of the KV
          → a partial output and an LSE value
merge:    exchange (output, LSE) pairs, rescale, add      (FlashDecoding's split-K, across GPUs)

The bytes exchanged are tiny (one output vector per head), but it is one more collective per layer, so it costs latency.

Why vLLM added it: KV duplication. Under TP, attention is split by KV head. When TP is wider than the number of KV heads, heads are copied (14.c). DeepSeek-style MLA has a single latent “head”, so at TP=8 every GPU stores the whole latent cache: 8 copies. vLLM’s decode context parallelism reuses the same GPUs and shards that cache by token instead:

Shell
# TP=8 for the weights, KV sharded by token over 8 ranks instead of copied 8 times
vllm serve deepseek-ai/DeepSeek-V4-Flash --tensor-parallel-size 8 --decode-context-parallel-size 8

vLLM documents the useful range as 1 to tp_size / H (H = number of KV heads), so for an MLA model at TP=8 it can go to 8, and for a GQA model with 4 KV heads at TP=8, to 2. Related flags in v0.32.0: --dcp-kv-cache-interleave-size (how many tokens go to one rank before moving to the next) and --dcp-comm-backend (ag_rs or a2a). Prefill CP is --prefill-context-parallel-size (-pcp); the vLLM documentation still describes the prefill strategies as under active development. SGLang has --attn-cp-size and a prefill CP mode for DeepSeek’s sparse attention.

Helix: different splits for attention and FFN#

At multi-million-token contexts, a decode step has two big reads: the FFN (or expert) weights and the KV cache. TP helps the first and fails the second past the KV-head count. Helix parallelism (NVIDIA, 2025) uses the same GPUs twice per layer: KV-parallel (CP) for attention, then TP or TP×EP for the FFN, with a small exchange between. The paper reports up to 1.5x lower token-to-token latency, or up to 32x larger batches at the same latency, for DeepSeek-R1 on Blackwell (paper’s own simulation results). Engines’ DCP plus attention-DP layouts are moving in the same direction.

Sequence parallelism (the Megatron kind)#

Not the same thing. Inside a TP group, each all-reduce can be split into a reduce-scatter and an all-gather, so the norms and residual adds in between run on 1/N of the tokens each (14.c). It saves activation memory and duplicated work, mostly in training and long prefills. It never lets one sequence’s KV exceed a GPU. vLLM removed its torch.compile sequence-parallel pass in v0.32.0.

Where CP fits with the others#

Long-context MoE deployment (illustrative):
  attention:  DP across requests  × CP=4 inside a request (long ones only)
  experts:    EP across all GPUs
  KV:         sharded by token over the CP group, FP8 or FP4 (13.h)

CP multiplies GPUs per request. Only requests that need it should get it: route long-context traffic to a dedicated pool (14.i).


6. Under the hood#

Ring attention on 4 simulated GPUs, in plain Go. Each “GPU” keeps an online-softmax state for its own queries; the K/V blocks move one step around the ring per round. The program checks that the result equals single-GPU causal attention, and counts the work per GPU for the contiguous and zigzag layouts.

Go
// ring.go — ring attention on simulated GPUs: exact result, and the causal load imbalance.
package main

import (
	"fmt"
	"math"
	"math/rand"
)

const (
	seq  = 16 // tokens
	dim  = 4  // head dimension
	gpus = 4
)

// state is the online-softmax accumulator for one query (10.g).
type state struct {
	m, l float64 // running max and running sum of exp
	o    [dim]float64
}

func (s *state) add(q, k, v []float64) {
	var score float64
	for i := range q {
		score += q[i] * k[i]
	}
	score /= math.Sqrt(dim)
	mNew := math.Max(s.m, score)
	scale := math.Exp(s.m - mNew) // rescale what we had
	w := math.Exp(score - mNew)
	s.l = s.l*scale + w
	for i := range s.o {
		s.o[i] = s.o[i]*scale + w*v[i]
	}
	s.m = mNew
}

func (s *state) out() [dim]float64 {
	var r [dim]float64
	for i := range r {
		r[i] = s.o[i] / s.l
	}
	return r
}

func newState() state { return state{m: math.Inf(-1)} }

func main() {
	rng := rand.New(rand.NewSource(1))
	Q, K, V := make([][]float64, seq), make([][]float64, seq), make([][]float64, seq)
	for t := 0; t < seq; t++ {
		Q[t], K[t], V[t] = make([]float64, dim), make([]float64, dim), make([]float64, dim)
		for i := 0; i < dim; i++ {
			Q[t][i], K[t][i], V[t][i] = rng.NormFloat64(), rng.NormFloat64(), rng.NormFloat64()
		}
	}

	// Reference: causal attention on one GPU.
	ref := make([][dim]float64, seq)
	for q := 0; q < seq; q++ {
		s := newState()
		for k := 0; k <= q; k++ {
			s.add(Q[q], K[k], V[k])
		}
		ref[q] = s.out()
	}

	layouts := map[string][]int{} // token -> GPU
	contig, zigzag := make([]int, seq), make([]int, seq)
	chunk := seq / (2 * gpus)
	for t := 0; t < seq; t++ {
		contig[t] = t / (seq / gpus)
		c := t / chunk // 2*gpus chunks; GPU g gets chunk g and chunk 2*gpus-1-g
		if c < gpus {
			zigzag[t] = c
		} else {
			zigzag[t] = 2*gpus - 1 - c
		}
	}
	layouts["contiguous"], layouts["zigzag"] = contig, zigzag

	for _, name := range []string{"contiguous", "zigzag"} {
		owner := layouts[name]
		states := make([]state, seq)
		for t := range states {
			states[t] = newState()
		}
		work := make([]int, gpus) // query-key pairs each GPU computes
		// Ring: at step r, GPU g holds the K/V block that started on GPU (g-r) mod gpus.
		for r := 0; r < gpus; r++ {
			for g := 0; g < gpus; g++ {
				src := ((g-r)%gpus + gpus) % gpus
				for q := 0; q < seq; q++ {
					if owner[q] != g {
						continue
					}
					for k := 0; k <= q; k++ { // causal mask
						if owner[k] == src {
							states[q].add(Q[q], K[k], V[k])
							work[g]++
						}
					}
				}
			}
		}
		var maxErr float64
		for q := 0; q < seq; q++ {
			o := states[q].out()
			for i := range o {
				maxErr = math.Max(maxErr, math.Abs(o[i]-ref[q][i]))
			}
		}
		maxW, sum := 0, 0
		for _, w := range work {
			sum += w
			if w > maxW {
				maxW = w
			}
		}
		fmt.Printf("%-10s matches one GPU: %v   work per GPU %v   balance %.0f%%\n",
			name, maxErr < 1e-12, work, 100*float64(sum)/float64(maxW*gpus))
	}
}

Output:

contiguous matches one GPU: true   work per GPU [10 26 42 58]   balance 59%
zigzag     matches one GPU: true   work per GPU [34 34 34 34]   balance 100%

How to read it:

  • “matches one GPU: true”: merging partial results with online softmax is exact, not an approximation. The order in which blocks arrive does not matter.
  • Contiguous split: the last GPU does almost 6x the work of the first, so the group is 41% idle. With more GPUs it gets worse.
  • Zigzag: every GPU gets one early and one late chunk, and the work is perfectly even.
  • A real implementation also overlaps each round’s send with the current block’s compute and works on blocks of thousands of tokens, not single tokens.

7. Performance implications#

  • Prefill CP scales well for long prompts: published results reach 75–93% parallel efficiency at 128k–1M tokens, because quadratic attention compute hides the linear communication.
  • It does not help short prompts. Below roughly 16–32k tokens the blocks are too small to hide the transfers; TP or plain chunked prefill is better.
  • Decode CP trades latency for memory. It removes KV duplication (more concurrent sequences or longer ones fit) but adds a merge collective per layer. Check ITL before and after.
  • Ulysses is capped by heads. A GQA model with 8 KV heads cannot go past Ulysses-8.
  • Causal balance matters: contiguous splits waste up to half the group at CP=4 and more beyond.

8. Production implications#

  • You probably need CP only for 128k+ contexts. Below that, TP, FP8 KV and chunked prefill are simpler.
  • Give CP only to long requests. A separate long-context pool (14.i) with CP enabled, normal pools without it.
  • For MLA models at TP=8, try decode CP. It can multiply KV capacity several-fold by removing copies; measure the ITL cost.
  • Price by GPU-seconds. A 1M-token prefill on 32 GPUs for 30 seconds costs as much as thousands of ordinary requests (23.c).
  • Check the alternatives first: prefix caching of the shared document (12.m), retrieval, and models with sparse or hybrid attention that need far less KV per token (12.g).

9. Common mistakes#

  1. Confusing Megatron sequence parallelism with context parallelism. Only CP lets one sequence’s KV exceed a GPU.
  2. Contiguous token assignment with a causal model. The last rank does most of the work.
  3. Turning on CP for every request. Short prompts get slower.
  4. Expecting decode CP to speed up decode. It mainly saves memory; it adds a collective.
  5. Ulysses beyond the head count. It cannot split further.
  6. No overlap. Ring attention without overlapping send and compute loses most of its gain.

10. Hands-on exercise#

  1. Run ring.go. Change gpus to 8 (and seq to 32). What balance does contiguous assignment give now?
  2. Modify the program to pass Q instead of K/V. What has to travel back to the query’s owner?
  3. Count the bytes one GPU sends per layer in ring attention for a 1M-token prompt on CP=8, with one MLA latent of 576 values per token at FP8. How long does that take over NVLink (700 GB/s) and over 400 Gb/s RDMA?
  4. Serve an MLA model with --tensor-parallel-size 8 and then add --decode-context-parallel-size 8. Compare the KV cache size reported at start-up and ITL at 64k context.
  5. Implement two-GPU ring attention with torch.distributed (isend/irecv) and check it against scaled_dot_product_attention.

11. Interview questions#

  1. What is the difference between tensor, sequence and context parallelism?
  2. Explain ring attention. Why is the result exact?
  3. Why does a contiguous split unbalance a causal model, and how does zigzag fix it?
  4. Compare ring attention and Ulysses. What limits Ulysses?
  5. Why does decode CP help MLA models at TP=8?
  6. When would you use pass-Q instead of pass-KV?
  7. Why should CP be enabled only for some requests?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in