AI State of the Art
SOTA/Advanced Attention Mechanisms/21 min
Section 78

Ring Attention: Ultra-long Contexts

Listen as a podcast →

The problem: a huge sequence, a tiny GPU

You want to process 1 million tokens. Your A100 GPU has 80 GB of memory. Even using Flash Attention and all possible optimizations, the memory required for the KV cache of a million tokens far exceeds the capabilities of a single GPU.

The classic solution: distribute the sequence across multiple GPUs. Each GPU takes a chunk. But the problem with standard distributed attention is that each token must potentially interact with all other tokens. That means each GPU must send its data to all others (all-to-all communication), which is extremely expensive in network bandwidth.

Ring Attention proposes an elegant solution: instead of sending everything to everyone at once, circulate the data in a ring.

Ring Attention with Blockwise Transformers for Near-Infinite Context

The ring algorithm

The most apt analogy: imagine 8 people sitting in a circle, each holding a sheet with notes. Each person needs to read the notes of all the others to write their summary. Instead of everyone photocopying and distributing their notes to everyone (chaos), you circulate the sheets around the circle. Each person reads the sheet in front of them, takes notes, then passes it to their left neighbor. After 7 rounds, everyone has read all the sheets.

Concretely, arrange the GPUs in a logical circle. Each GPU holds a chunk of the sequence (its queries Q) and initially a chunk of keys/values (K/V).

Step 1: GPU #0 computes attention of its Q with its current K/V. In parallel, it sends its K/V to GPU #1 and receives K/V from GPU #7.

Step 2: GPU #0 redoes the computation with the newly received K/V (those from GPU #7). Sends this block to #2, receives the one from #6.

And so on for P-1 steps (for P GPUs). At the end, each GPU has seen all the K/V from the complete sequence and has computed exact attention for its tokens.

Hand-drawn diagram. Four green rectangles labelled GPU 1, GPU 2, GPU 3 and GPU 4 sit at the four cardinal points of a circle. Each GPU carries a yellow tag on its outer side reading Q1, Q2, Q3 or Q4 that stays attached, and towards the inside of the circle a pair of blocks K and V numbered K1 V1, K2 V2, K3 V3, K4 V4. Curved arrows link each GPU's K/V pair to the next one clockwise, forming a closed ring.
What moves and what stays. The queries Q (in yellow, on the outside) never leave their GPU: each GPU always computes attention for its own tokens. Only the key-value pairs K/V travel around the ring, one hop per step. After four steps, every K/V block has passed in front of every GPU.Source : Coconut Mode blog

The clever trick: overlapping compute and communication

The secret of Ring Attention's efficiency: while GPU #0 computes attention with the current K/V chunk, it sends and receives the next chunk in parallel on the communication bus (NVLink).

It's like reading a book while reaching out to grab the next one from the shelf, you don't waste any waiting time between the two operations.

Figure 2 from the Ring Attention paper, in two panels. Panel a: two dashed frames labelled Device 1 and Device 2, each containing a Blockwise Attention block topped by a Blockwise FeedForward block with residual connections; a query block enters from the bottom of each device. Large horizontal grey arrows labelled Key Value Block cross the devices from right to left. Panel b: on the left a column Query1 to Query4 with a vertical arrow Query Outer Loop; on the right four Blockwise Attention columns topped by Blockwise FeedForward, fed by the pairs Key1 Value1 through Key4 Value4; the two middle columns are boxed and annotated compute, send to next device and receive from previous device; a horizontal arrow at the bottom reads Key and Value Inner Loop.
The lower panel shows the overlap in practice. The two boxed columns are annotated compute, send to next device and receive from previous device: while one key-value block is being used for computation, the next one is already in transit. The outer loop walks over the queries, the inner loop rotates keys and values around the ring.Source : Ring Attention paper by Liu et al. (figure 2), via Semantic Scholar
Efficient overlapping

As long as the computation time for a block > network transfer time for a block, communication is effectively "free", it happens in the background during computation. Flash Attention makes local computation fast, NVLink links (900 GB/s on H100) make transfers fast too. The two overlap perfectly in the vast majority of configurations.

Integration with Flash Attention

Softmax in attention poses a challenge for distributed computation: it normally requires knowing all values to compute the denominator. How do you compute a correct softmax if each GPU only sees part of the K/V at a time?

Flash Attention solves this problem with a progressive online softmax. Ring Attention pushes this technique one step further by accumulating softmax statistics across blocks received from different GPUs.

At each step j, when GPU #0 receives a new K/V chunk, it updates:

max_new=max⁡(max_old, maxj)\text{max\_new} = \max(\text{max\_old},\ \text{max}_j)

norm_new=emax_old−max_new×norm_old+normj\text{norm\_new} = e^{\text{max\_old} - \text{max\_new}} \times \text{norm\_old} + \text{norm}_j

output_new=accumulation of outputs with normalized weights\text{output\_new} = \text{accumulation of outputs with normalized weights}

The exponential factor emax_old−max_newe^{\text{max\_old} - \text{max\_new}} corrects previous statistics when the maximum changes. This is numerically stable and exact, no approximation.

Result: the attention is exact, identical to what you'd get computing on a single giant GPU. Ring Attention makes no compromise on mathematical quality.

Online softmax math

This is exactly the same technique Flash Attention uses to avoid materializing the full attention matrix. Ring Attention simply applies this idea across distributed GPUs rather than across blocks in local memory. The principle is identical: you can compute a global softmax by seeing only one block at a time, thanks to accumulating the max and the norm.

Memory per GPU

Instead of a single GPU storing everything (O(L * d)), each GPU stores:

  • Its Q: (L/P) * d (its portion of queries)
  • The current K/V and the receive buffer: ~2 chunks of (L/P) * d
  • Temporary output and accumulators

Total per GPU: O(L * d / P). For 8 GPUs and 1M tokens, it's like a single GPU storing 125K tokens. That's very manageable on an A100 with 80 GB. And it scales linearly: 16 GPUs = 62.5K per GPU, 64 GPUs = ~15K per GPU. You can go almost arbitrarily far.

Optimization for causal attention

With causal masking (each token can only see previous tokens), about 50% of pairs (i, j) where i < j are already masked and don't contribute to the computation.

Ring Attention exploits this intelligently: when a GPU detects that an entire K/V chunk contains only "future" tokens relative to its queries, it completely skips the computation for that chunk. This frees up compute time during which communication of the next chunk can happen.

Causal Ring Attention

In the causal configuration, the last GPU (holding the most recent tokens) only needs previous chunks, it skips all "future" chunks. The first GPU (oldest tokens) only computes with its own K/V. This asymmetry considerably improves efficiency, reducing effective compute work by nearly 50% in the ideal case.

Real-world results

The paper shows that the tractable context length grows in proportion to the number of GPUs: every device added to the ring contributes its share of memory, with no structural limit. Using the arithmetic from the previous section: 8 GPUs share 1M tokens the way a single GPU would handle 125K; doubling the GPUs doubles the reachable context. On large clusters, the authors process sequences of several million tokens.

Concrete applications: entire books in context (a novel = ~100-200K tokens), complete legal case files, long videos converted to tokens, entire codebases for analysis.

Practical limitations

NVLink is essential

Ring Attention relies on overlapping compute and communication. If communication is slow, it no longer hides behind the computation and becomes a bottleneck. NVLink (900 GB/s on H100) = perfect. PCIe Gen 4, a server's standard bus (~64 GB/s counting both directions, i.e. ~32 GB/s per direction, the convention is explained in Bits and bytes) = more than ten times slower, it no longer works well. InfiniBand between servers (400 Gbit/s, i.e. ~50 GB/s) = usable but watch the compute/transfer ratio. Bottom line: Ring Attention is at its best between GPUs within the same server connected by NVLink.

Variants and improvements:

  • Striped Attention: distribute tokens in an interleaved manner (1, 9, 17... on GPU #0, 2, 10, 18... on GPU #1) instead of contiguous chunks. Better load balancing for causal attention, since each GPU has tokens from different positions.
  • Ring Flash Attention: CUDA kernels specifically optimized for the ring, fusing local attention computation and communication into a single operation.
Side-by-side comparison. On the left, titled Ring Attention (Liu et al., 2023): a 16-position sequence numbered 0 to 15 is coloured in four contiguous blocks (dark red 0 to 3, olive 4 to 7, green 8 to 11, cyan 12 to 15), for both KV and Q; four arrows lead down to four devices, each receiving one contiguous block, for example the first device receives positions 0, 1, 2, 3. On the right, titled Striped Attention (Ours): the same sequence goes through a grey Stripe Permutation box, and the devices receive interleaved positions: 0, 4, 8, 12 for the first, 1, 5, 9, 13 for the second, 2, 6, 10, 14 for the third, 3, 7, 11, 15 for the fourth; each KV and Q block therefore shows all four colours.
The two splitting schemes side by side. On the left each GPU gets a contiguous slice: the one holding positions 0 to 3 has almost nothing to compute under causal masking, the one holding 12 to 15 has to look at everything. On the right, the interleaved permutation gives each GPU positions spread across the whole sequence, so roughly the same amount of work.Source : Striped Attention paper by Brandon et al., via Christian Mills's GPU MODE lecture notes
Conclusion

Ring Attention makes possible what seemed impossible: processing millions of tokens without deleting or compressing them, with exact attention. It's a key element for models with ultra-long contexts. The algorithm is elegant, mathematically pure, and proven in production. Its legacy goes beyond the technique: it showed that the "context too long" barrier is fundamentally an engineering problem, not a theoretical one.

Check your understanding0 / 5

1. In the Ring Attention ring, what circulates from GPU to GPU, and what stays put?

2. Under what condition does the communication between GPUs become effectively free in Ring Attention?

3. Each GPU only sees part of the K/V at a time. Is the final result approximate?

4. What do you gain by adding GPUs to the ring?

5. The callout compares NVLink (900 GB/s) with InfiniBand (400 Gbit/s). Why do the units deserve attention?