Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Ring attention,
explained.
There's a hard ceiling on context: a sequence's attention has to fit in one accelerator's memory, and past a point it simply won't. Ring Attention removes the ceiling with a systems trick, not an approximation. Lay the devices in a circle, give each one a slice of the sequence, and pass the keys and values around the ring like a bucket brigade — so every slice eventually sees every other, and no device ever holds more than its share. Context then scales with how many devices you have. Here's the rotation, and why it's nearly free.
What changes against Longformer: the attention stays exact
Rung 2 buys length by computing something other than attention. This rung buys length while computing exactly the same attention, by changing where the computation lives. The insight it builds on is that attention does not actually need the whole key-value set in memory at once: the softmax can be accumulated block by block, carrying a running normaliser, so a query can be scored against the sequence in pieces and the result is the full attention, exact up to floating-point rounding.
Given that, the change is a distribution strategy. Shard the sequence across a ring of devices, so each device holds one block of queries and one block of keys and values. Every device computes the attention of its queries against the block it currently holds, then passes its key-value block to the next device and receives one from the previous. After a full rotation, every query has been scored against every key, and no device ever held more than its own slice.
Stated in units the ladder can compare: memory per device becomes proportional to sequence length divided by device count, so maximum context scales with the number of devices — add hardware, get length, with no change to the model or the mathematics. And the block hand-off is a communication that can be overlapped with the arithmetic of the current block, so on a fast interconnect the transfer is close to hidden behind compute it would otherwise wait for. This is what puts million-token contexts within reach.
The memory ceiling
FlashAttention already made attention memory-linear in sequence length on a single device — a huge win. But "linear on one device" still has a ceiling: eventually the sequence's activations, keys, and values won't fit in one accelerator's memory, no matter how clever the kernel. If you want a context of millions of tokens, one chip is simply not enough memory.
The natural move is to use more devices — but attention is all-to-all: every query must see every key, and naively that means every device needs all the keys, which puts you right back at the memory wall. Ring Attention's insight is that a device doesn't need all the keys at once. It can see them one block at a time, as long as, over the course of the computation, each block passes by. Arrange that traffic as a ring, and you get exact full attention with per-device memory that shrinks as you add devices.
Split the sequence across a ring of devices and rotate the key/value blocks around it, so every query sees every key without any device holding the whole sequence — context scales with device count.
Shard the sequence
Take a sequence of N tokens and P devices. Split the sequence into P contiguous blocks and give one block to each device — so each holds N/P tokens' worth of queries, keys, and values. This is sequence parallelism: the sequence dimension itself is distributed, unlike the more common splitting of the model's layers or tensors.
Each device is responsible for computing the attention output for its own query block. To do that correctly, its queries must attend to the keys and values of every block, including those living on other devices. The question is how to bring those remote keys and values to each device without anyone having to store them all. The answer is the ring.
The ring rotation
Connect the devices in a circle. Each device starts by attending its query block to its own key/value block, then passes its key/value block to the next device and receives one from the previous device. Repeat. After P such rotations, every key/value block has visited every device, so every query block has attended to the entire sequence — and the attention outputs, accumulated blockwise with an online softmax (the FlashAttention trick), are exact.
The key property is the memory: at any instant a device holds only its own block plus the one rotating block — memory of order N/P, not N. So with twice the devices you can handle twice the context at the same per-device memory. Nothing is approximated: it computes the same exact dense attention a single giant device would, just spread out in space and time. The runnable version below makes the scaling and step count concrete.
Hidden communication
Passing blocks around a ring means network traffic, and network traffic is usually the enemy of distributed speed. Ring Attention's second trick is to make that traffic free by overlapping it with computation. While a device computes attention between its queries and the current key/value block, it is simultaneously sending that block onward and receiving the next one. The transfer happens in the shadow of the math.
Because attention compute per block grows with the block size while the transfer is a fixed data movement, you can choose a block large enough that computation dominates — and then the ring's communication costs nothing in wall-clock time. That overlap is what makes scaling context across many devices practical rather than bottlenecked on the network.
How Ring Attention distributes exact attention, step by step
Ring Attention, from Liu, Zaharia and Abbeel at UC Berkeley, runs exact attention, and the rest of each transformer block, over a sequence too long for any one accelerator. It builds on their Blockwise Parallel Transformer, which computes attention and the feed-forward network block by block so that full-length activations are never materialized.
- Shard the sequence. Split N tokens into P contiguous blocks of c = N/P tokens and give one block to each of P hosts arranged in a ring. Each host computes the queries, keys and values for its own block.
- Start with the local block. Each host computes attention between its query block and its own key-value block, keeping running statistics per query row in the FlashAttention style: the running maximum score, the running softmax denominator and the running weighted sum of values.
- Rotate and overlap. While it computes, each host sends its current key-value block to the next host and receives one from the previous host. On the next step it folds the new block into its running statistics. After P steps every query block has met every key-value block.
- Normalize. Dividing the running sum by the running denominator gives the attention output. It equals full attention up to floating-point rounding: the same terms are added, only in a different order.
- Keep the feed-forward local. The feed-forward network is position-wise, so each host applies it blockwise to its own tokens with no communication at all.
- Run the backward pass on the same ring. Gradients use the same rotation, with key-value blocks and their gradient accumulators passed between neighbours, so per-host memory stays proportional to the block size rather than the sequence length.
- Size the block so communication hides. A block's attention costs about 4dc² floating-point operations, while sending its keys and values moves about 4cd bytes at 16-bit precision. The transfer is hidden when the computation takes longer, which reduces to c ≥ F/B, where F is a host's FLOP rate and B its link bandwidth. It is an arithmetic-intensity condition: work grows with c², traffic only with c.
The causal-mask catch
In a decoder, the causal mask means a query block needs only the key blocks at or before it. With a contiguous split, the host holding the first block has almost nothing to compute, while the host holding the last block attends to every block. Because the ring advances in lockstep, every step waits for the busiest host, and roughly half of all compute slots sit idle. Striped Attention (Brandon et al., 2023) fixes this by dealing tokens to hosts round-robin, so each host holds a mix of early and late positions. The zigzag split used in later context-parallel training, including the scheme described for Llama 3, gives each host one early chunk and its mirror-image late chunk.
How it differs from DeepSpeed-Ulysses
DeepSpeed-Ulysses (Jacobs et al., Microsoft, 2023) also shards the sequence, but before attention it runs an all-to-all exchange that re-shards by attention head, so each device computes full-length attention for a subset of heads, then exchanges back. Its parallelism is capped by the number of heads, and each attention still spans the whole sequence on one device. Ring Attention has no head limit and never gathers the full sequence anywhere, at the cost of P sequential steps that depend on the overlap condition.
The blockwise softmax accumulation and the overlap condition
S = QiKb^⊤ / √d, m′ = max(m, rowmax S)
ℓ ← e^m − m′ ℓ + rowsum(e^S − m′), O ← e^m − m′ O + e^S − m′ Vb, m ← m′
Attention(Qi, K, V) = O / ℓ
4dc² / F ≥ 4cd / B ⇔ c ≥ F / B
Qi— this host's query block, c rows of dimension d; it never moves.Kb, Vb— the key-value block passing through this host at step s.m— the running maximum score per row, starting at −∞; subtracting it keeps every exponential bounded.ℓ,O— the running softmax denominator and the running unnormalized output, rescaled by e^m − m′ whenever the maximum rises.F,B— a host's FLOP rate and its link bandwidth in bytes per second.c— the block size in tokens, the one knob the overlap condition constrains.
At the extremes: with P = 1 the loop runs once and this is ordinary blockwise attention on one device. With c below F/B, every step waits on the network and the ring runs at link speed. Far above it, communication is fully hidden but each host needs more memory. Taking an A100 at 312 teraFLOP/s with about 300 GB/s of NVLink bandwidth, c ≥ about 1,000 tokens; over a 12.5 GB/s network the same chip needs about 25,000.
What Liu, Zaharia and Abbeel ran, and what Ring Attention showed
The authors trained LLaMA-architecture models of several billion to tens of billions of parameters on A100 GPU clusters, connected by NVLink within a node and InfiniBand across nodes, and on TPU v3, v4 and v5e slices. The main comparison is the longest context each method can train at a given model size and hardware: a vanilla transformer, memory-efficient attention, and memory-efficient attention plus a blockwise feed-forward network, which is their earlier Blockwise Parallel Transformer.
| What was tested | Reported outcome |
|---|---|
| Longest trainable context against the best memory-efficient baseline | up to P times longer on P devices, with no approximation |
| Training efficiency as context grows | model FLOPs utilization stays close to the blockwise baseline |
| LLaMA-13B fine-tuned to a 512K-token context, line retrieval | stays accurate at lengths beyond the 16K- and 100K-context models compared |
| In-context reinforcement learning with long trajectory histories | more trajectories fit in context, with higher returns |
| Overlap condition, A100 with NVLink (computed from c ≥ F/B) | blocks of about 1,000 tokens or more |
| Overlap condition, 12.5 GB/s network (computed) | blocks of about 25,000 tokens or more |
The headline claim is a scaling law in hardware: the maximum context is proportional to the number of devices, because each device's memory depends on the block size, not on the total length. That is how the authors reach contexts in the millions of tokens.
Three negatives are worth stating. Total arithmetic is unchanged and still quadratic in sequence length; the ring removes the memory ceiling, not the FLOPs. The overlap argument is a hardware precondition, and on slow interconnects the block size it demands can exceed what fits on a device. And the original paper does not address the causal-mask load imbalance; Striped Attention and zigzag splits came afterwards to recover the roughly half of compute a contiguous causal split leaves idle.
What the authors admit, and what happened next
The clearest thing to be honest about is what this does not buy. Total arithmetic is unchanged and still quadratic — the ring distributes and overlaps the work, it does not reduce it. What it removes is the memory ceiling, which was the binding constraint, and that is a genuine and large win, but a million-token forward pass remains a million-token forward pass in FLOPs.
The overlap argument also carries a hardware precondition: it holds when inter-device bandwidth is high enough that a block transfer fits inside a block of compute. On a weaker interconnect the ring stalls and the elegance evaporates, which makes this a technique whose value depends on the cluster it runs on rather than a property of the algorithm.
How it held up: as infrastructure rather than as a paper people cite in product copy. Sequence and context parallelism of this shape is standard in frontier training stacks, and it is part of why long-context models became trainable at all rather than merely fine-tunable. Read alongside rung 2, the pair make the ladder's central engineering point: the two techniques that actually delivered long context both kept attention exact and changed how it meets the memory hierarchy, while the one that changed the mathematics to save operations did not survive.
Context that scales with devices
Ring Attention's scaling is arithmetic on blocks. This shows the sequence sharded N/P across devices, the ring completing in P steps so every query block meets every key block, and — the payoff — the maximum context growing linearly with the device count (8 devices → ~1M tokens, 16 → ~2M). Per-device memory stays O(N/P) and shrinks as you add devices, and the communication overhead is zero whenever compute time meets or beats transfer time. Change N, the device count, or the compute/comm balance and watch the ceiling lift.
Write the body of ring_plan. Everything else in the file is
already written; this is the function the paper is about. Press ▶ Run to check it against
the 7 assertions below — they start red.
- The sequence is sharded N/P across devices
- Max context scales linearly with device count
- The ring completes in P steps
- Overlapped communication is free when compute >= comm
- Per-device memory shrinks with more devices
- Ring_plan reports the shard, the rotations and the memory together
- A sequence larger than the ring can hold does not fit
Million-token context
The consequence is a context length that grows with your hardware budget, not your single chip:
| Property | Ring Attention |
|---|---|
| Exact attention | No approximation, no sparsity, no dropped tokens — the same result as full attention. |
| Context ∝ devices | Per-device memory is O(N/P), so more devices → proportionally longer context. |
| Near-zero comm overhead | Block transfer overlaps compute, so scaling stays efficient. |
| Enables 1M+ tokens | Combined with big device counts, it pushed context into the millions — used in long-context models and beyond. |
Ring Attention (and its blockwise-transformers foundation) is a big part of why million-token context windows became feasible. It reframed long context as a distributed-systems problem with a clean solution, rather than a hard architectural limit — you buy context length with devices.
Where it fits
Long context has been pursued along different axes, and Ring Attention occupies the systems one. Longformer changes what's attended to (sparsity); Transformer-XL adds recurrence and memory; FlashAttention reorganizes the computation on one device. Ring Attention keeps the attention exact and dense and instead distributes it — and it composes with FlashAttention, using the same online-softmax accumulation blockwise across the ring.
Its lasting idea is that some ceilings are about where computation happens, not what it computes. The attention that wouldn't fit on one device fits fine when spread across many, if you route the data cleverly and hide the movement. That "distribute the sequence, rotate the state, overlap the transfer" pattern is now a standard tool for scaling context, and a reminder that a memory wall is often a systems problem in disguise.
Ring Attention builds directly on "blockwise parallel transformers," which applies the same block-by-block, online-softmax idea to the feed-forward layers too — so the whole transformer block, not just attention, can run at long context without materializing full-length activations.
Questions people ask about Ring Attention
What is the difference between Ring Attention and DeepSpeed-Ulysses?
Both are sequence parallelism: each device starts with a slice of the tokens. DeepSpeed-Ulysses, from Microsoft, uses an all-to-all exchange before attention to re-shard the data by attention head, so each device computes ordinary full-length attention for a subset of heads, then a second all-to-all restores the sequence split. It is simple and fast on good networks, but the number of devices is capped by the number of heads, and each device still holds full-length keys and values for its heads. Ring Attention keeps the sequence split throughout and passes key-value blocks around a ring of neighbours, overlapping the transfer with compute. It has no head limit. Hybrids combine the two, using Ulysses within a node and a ring across nodes.
Why does the causal mask cause load imbalance in Ring Attention, and how is it fixed?
With a causal mask a query only attends to keys at or before it. If the sequence is split into contiguous blocks, the device holding the first block has only its own diagonal block to compute, while the device holding the last block must attend to every block. The ring advances in lockstep, so each step lasts as long as the busiest device, and roughly half the total compute capacity is wasted. Striped Attention (Brandon et al., 2023) deals tokens to devices round-robin so every device holds early and late positions and does about the same work. The zigzag split gives each device chunk i together with its mirror chunk from the other end, the scheme described for Llama 3's context parallelism.
How large must the blocks be for Ring Attention to hide communication?
Large enough that computing attention on a block takes longer than sending the next one. Attention between a query block and a key-value block of c tokens costs about 4 times d times c squared floating-point operations, while sending a key block and a value block costs about 4 times c times d bytes at 16-bit precision. Dividing by a host's FLOP rate F and bandwidth B, the transfer is hidden when c is at least F divided by B. For an A100 at about 312 teraFLOP/s with roughly 300 GB/s of NVLink, that is about 1,000 tokens per block. Over a 12.5 GB/s network it is about 25,000, which is why the technique depends on fast interconnects.
Is Ring Attention exact attention or an approximation?
It computes exact attention, the same result as full dense softmax attention, up to floating-point rounding. Nothing is sparsified, sampled or dropped. Each host scores its queries against every key-value block in turn and combines the partial results with the online-softmax rescaling used by memory-efficient and FlashAttention kernels: a running maximum, a running denominator and a running weighted sum, rescaled whenever a larger score appears. Because floating-point addition is not associative, summing blocks in a different order can change the last bits of the result, so outputs are numerically equivalent rather than bitwise identical to a single-device computation. In practice that difference is the same kind as between two attention kernels.
How does Ring Attention relate to FlashAttention and blockwise transformers?
They are layers of the same idea. Memory-efficient attention and FlashAttention compute exact attention on one device without materializing the full score matrix, by processing key-value blocks one at a time with an online softmax. Liu and Abbeel's Blockwise Parallel Transformer applied that blockwise computation to the feed-forward network as well, so whole transformer blocks run without full-length activations. Ring Attention distributes the blockwise loop across devices: instead of reading the next key-value block from slower memory on the same chip, a host receives it from its neighbour in the ring while computing. On each host the inner computation can use a FlashAttention-style kernel.
4 questions to test what you just read
Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.
A 1,048,576-token sequence is split over 64 hosts. How many tokens does each hold, how many ring steps does one attention layer take, and what happens to per-host memory if both length and hosts double?
Show answer
1,048,576 / 64 = 16,384 tokens per host, and one layer takes 64 steps, one per key-value block. Doubling both keeps the block at 16,384, so per-host memory is unchanged; only the step count doubles.
Over a 12.5 GB/s link with 312 teraFLOP/s chips, F/B ≈ 25,000 tokens. With blocks of 4,096 tokens, how long does each transfer take relative to each block's compute?
Show answer
Communication over compute is (4cd/B) / (4dc²/F) = F / (B · c) ≈ 25,000 / 4,096 ≈ 6.1. Each step waits about six times longer for the network than it computes, so the ring runs at link speed and the overlap argument fails at this block size.
With 4 hosts, a causal mask and a contiguous split, the hosts do 0.5, 1.5, 2.5 and 3.5 blocks of work. Ignoring transfers, what fraction of compute capacity is used, and what would a balanced split give?
Show answer
Step 1 is diagonal blocks everywhere (0.5 time); steps 2 to 4 each wait on the last host's full block (1.0 each), so the ring takes 3.5 block-times. Work is 8 blocks over 4 × 3.5 = 14 slots: about 57%. Balanced, each host does 2 blocks, so it takes 2 block-times, about 1.75× faster.
Why does the feed-forward half of each block need no communication at all in Ring Attention?
Show answer
The feed-forward network is position-wise: each token's output depends only on that token's own vector. A host already holds the vectors for its block, so it applies the network locally, blockwise, without data from any other host. Only attention mixes positions, so only attention needs the ring.
Making the context long
Attention costs quadratic in sequence length. Six attempts to escape that, ending with two 2026 papers that give the model a memory instead.
- 1Transformer-XL2019
- 2Longformer2020
- 3Ring Attention2023
- 4Mamba2023
- 5Titans2025
- 6Engram2026
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Paper Breakdowns
- Attention Is All You NeedThe paper that introduced the Transformer — the architecture underneath GPT, BERT, Claude, and Gemini. Self-attention, Query/Key/Value, multi-head attention, positional encoding, and the real BLEU results, explained in depth with analogies and animated visuals, not just equations.Read →
- BERTThe paper that made "pre-train once, fine-tune anywhere" the default for NLP. Bidirectional context, masked language modeling, next-sentence prediction, the [CLS]/[SEP] tokens, and the GLUE sweep — explained with analogies, not just equations.Read →
- Chain-of-Thought PromptingShow a model a few worked examples with their reasoning and it starts solving problems it used to fail. Why reasoning emerges only at scale, the GSM8K jump, zero-shot "Let's think step by step", and how CoT seeded modern reasoning models.Read →
- LoRAThe paper that made fine-tuning affordable. Freeze the giant pretrained model and train two tiny low-rank matrices instead — up to 10,000x fewer trainable parameters, no extra inference latency, and swappable per-task adapters. The road to QLoRA and PEFT.Read →
- Direct Preference OptimizationRLHF without the RL. Align a model to human preference pairs with one simple classification-style loss — no separate reward model, no unstable reinforcement learning. Why "your LM is secretly a reward model", and how DPO became the default alignment method.Read →
- ChinchillaThe compute-optimal scaling law that said models were too big. Parameters and training tokens should scale together — ~20 tokens per parameter — so a 70B model trained on 1.4T tokens beat the 280B giants. Why every model since trains on trillions of tokens.Read →