RingAttention addresses the quadratic memory complexity of standard self-attention by partitioning sequence length S across N devices in a 1D ring topology. It achieves exact attention computation with O(S/N) per-device memory scaling by circulating Key-Value blocks asynchronously while computing blockwise attention using running online softmax normalizers. This architecture allows clusters to scale context lengths indefinitely without being bound by single-accelerator High Bandwidth Memory (HBM) capacity.
Scaling context windows from thousands to millions of tokens has transformed large language models from localized sequence processors into comprehensive repository analyzers, long-form document synthesizers, and multi-modal world simulators. However, standard self-attention exhibits quadratic computational and memory complexity with respect to sequence length . While IO-aware memory optimizations like FlashAttention eliminate intermediate attention matrix materialization in High Bandwidth Memory (HBM), the per-device key-value (KV) activations and query tensors for a multi-million-token sequence rapidly exceed the physical memory capacity of any single accelerator.
Distributed sequence scaling requires partitioning the sequence dimension across clusters of GPUs. Traditional distributed training paradigms—such as Tensor Parallelism (TP) and Pipeline Parallelism (PP)—cannot scale context length indefinitely. Tensor Parallelism partitions model weights and activations along hidden and head dimensions, bounding the maximum parallel degree by the number of attention heads (typically 32 to 128) while imposing high all-reduce communication overheads. Pipeline Parallelism partitions layers across devices, leaving the per-device activation memory for long sequences unchanged.
Context Parallelism (CP) addresses this fundamental limitation by sharding the sequence dimension across devices. Among context-parallel paradigms, RingAttention, introduced by Liu et al. (2023) building upon Blockwise Parallel Transformers (Liu & Abbeel, 2023), organizes GPUs into a logical 1D ring network. By circulating Key-Value blocks asynchronously along the ring while computing blockwise attention with running online softmax normalizers, RingAttention achieves exact attention computation with per-device memory scaling and near-complete communication-compute overlap.
+---------------------------------------------------------------------------------------------------+
| DISTRIBUTED SEQUENCE PARALLELISM SPECTRUM |
+---------------------------------------------------------------------------------------------------+
| Paradigm | Sharding Dimension | Communication Type | Max Scaling Limit |
+--------------------+--------------------+--------------------------+------------------------------+
| Tensor Parallelism | Head / Hidden ($d$) | Intra-node All-Reduce | Bound by Attention Heads $H$ |
| DeepSpeed-Ulysses | Sequence ($S$) | All-to-All (Heads <-> S) | Bound by Attention Heads $H$ |
| RingAttention | Sequence ($S$) | Ring P2P Asynchronous | Arbitrary Cluster Scale $N$ |
| 2D Hybrid (USP) | Sequence ($S$) | Intra-All2All + Inter-P2P| Massive Hybrid Scale ($N*M$) |
+--------------------+--------------------+--------------------------+------------------------------+1. The Sequence Length Bottleneck in Distributed Systems
Standard Multi-Head Attention (MHA) projects an input sequence into Query (), Key (), and Value () tensors:
where , is sequence length, and is hidden dimension. For attention heads with head dimension , attention output for a single head is evaluated as:
where denotes an optional causal mask.
Memory and Activation Scaling
In standard backpropagation, calculating gradients with respect to , , and requires storing intermediate activations. For a sequence of length with layers, heads, and in 16-bit precision ( bytes):
- KV Activation Footprint per Layer:
- Total Model Activation Footprint across 32 Layers:
Even before accounting for attention score logits, optimizer states, and model parameters, a 1-million-token sequence exceeds the 80 GB or 141 GB HBM capacity of modern NVIDIA H100 or H200 accelerators by nearly an order of magnitude.
Failure Modes of Standard 3D Parallelism for Long Contexts
- Data Parallelism (DDP / FSDP / ZeRO-3): Replicates or shards weights across GPUs, but each GPU must still execute the forward and backward pass for a full sequence slice of length . Per-device activation memory remains .
- Tensor Parallelism (Megatron-LM): Splits along head or column dimensions. The sequence dimension remains unpartitioned within each GPU. Furthermore, the maximum TP degree is physically capped by ( or ). Beyond single-node NVLink domains, TP communication latency degrades throughput catastrophically.
- Pipeline Parallelism (PP): Distributes layers across pipeline stages. Activations for sequence must still reside in stage memory, creating severe bubble overheads () when microbatch counts are small due to memory constraints.
Context Parallelism is therefore essential: it shards the sequence length into equal chunks of size , distributing the memory burden such that each device stores only tokens.
2. Mathematical Foundations: Exact Online Softmax Across Distributed Blocks
The core mathematical enabler of blockwise attention without full sequence materialization is the Online Softmax algorithm (Milakov & Gimelshein, 2018; Dao et al., 2022). RingAttention generalizes online softmax from single-GPU SRAM tiling to multi-node distributed network topologies.

The Classical Online Softmax Formulation
Given a query vector and key vectors partitioned into sequential blocks with , we define intermediate pre-softmax logits for block as:
To avoid numerical overflow when computing , standard softmax subtracts the global maximum . In a sequential streaming setting, the running maximum and running denominator normalizer are updated iteratively:
The unnormalized output accumulator is updated by rescaling the previous accumulator and adding the contribution of the current Value block :
After processing all blocks, the exact attention output vector is recovered via normalization:
This decomposition is mathematically identical to computing softmax over the fully concatenated sequence:
+---------------------------------------------------------------------------------------------------+
| ONLINE SOFTMAX STATE TRANSITION STEP |
+---------------------------------------------------------------------------------------------------+
| Previous State: (m^(i-1), l^(i-1), O^(i-1)) |
| |
| 1. Compute Local Block Logits: S^(i) = q (K^(i))^T / sqrt(d_k) |
| 2. Update Running Maximum: m^(i) = max(m^(i-1), max(S^(i))) |
| 3. Compute Rescaled Exponentials: P_tilde^(i) = exp(S^(i) - m^(i)) |
| 4. Rescale & Accumulate Normalizer: l^(i) = exp(m^(i-1) - m^(i)) * l^(i-1) + sum(P_tilde^(i)) |
| 5. Rescale & Accumulate Output: O^(i) = exp(m^(i-1) - m^(i)) * O^(i-1) + P_tilde^(i)*V^(i) |
| |
| Final Normalized Output: A = O^(T) / l^(T) |
+---------------------------------------------------------------------------------------------------+3. Distributed Ring Topology and Overlapped Communication
RingAttention maps this blockwise recurrence onto a 1D logical ring of physical devices (indexed ).
Initial Sequence Allocation
The full sequence of length is partitioned into contiguous blocks of size :
Each GPU computes and permanently retains its local Query block , while initializing its local Key and Value buffers with and . Each GPU also initializes its local online softmax statistics:
+---------------------------------------------------------------------------------------------------+
| RINGATTENTION 1D LOGICAL RING ROTATION |
+---------------------------------------------------------------------------------------------------+
| |
| [ GPU 0 ] ---- Send (K_0, V_0) ---> [ GPU 1 ] |
| (Holds Q_0) (Holds Q_1) |
| ^ | |
| | | |
| Send (K_3, V_3) Send (K_1, V_1) |
| | | |
| | v |
| [ GPU 3 ] <--- Send (K_2, V_2) ---- [ GPU 2 ] |
| (Holds Q_3) (Holds Q_2) |
| |
| Step t=0: Local Attention (Q_k, K_k, V_k) |
| Step t=1: Rotated Attention (Q_k, K_(k-1), V_(k-1)) |
| Step t=2: Rotated Attention (Q_k, K_(k-2), V_(k-2)) |
| Step t=3: Rotated Attention (Q_k, K_(k-3), V_(k-3)) |
+---------------------------------------------------------------------------------------------------+The -Step Ring Schedule
The computation executes across discrete steps :
- Local Computation: In step , GPU holds the key-value block corresponding to rank . It evaluates blockwise attention between static local queries and current key-value pair using an optimized FlashAttention kernel, updating local state .
- Asynchronous Peer-to-Peer Transfer: Concurrently with step 1 computation, GPU issues non-blocking peer-to-peer (P2P) transfers:
- Asynchronously sends to its downstream neighbor .
- Asynchronously receives from its upstream neighbor .
- Synchronization & State Swap: Once both local GEMM execution and P2P communication complete, GPU swaps buffers and advances to step .
At the end of ring steps, key-value blocks have traversed the complete ring and returned to their origin devices. Each GPU normalizes its local accumulator , producing the exact mathematical output corresponding to full sequence attention.
4. Communication vs. Compute Roofline Overlap Analysis
The core efficiency requirement of RingAttention is hiding communication latency behind block computation time ().
Arithmetic and Communication Formulations
For a sequence chunk of size , hidden dimension , and number of heads :
- Computation per Ring Step:
Evaluating attention between and requires two matrix multiplications ( and ): Given a GPU with peak dense compute throughput (e.g., 989 TFLOP/s FP16/BF16 on NVIDIA H100 SXM5) and kernel execution efficiency :
- Communication per Ring Step:
Each step transfers key and value blocks in 16-bit precision ( bytes per element): Given bidirectional inter-GPU interconnect bandwidth (e.g., 900 GB/s for NVLink 4, or 50 GB/s for 400 Gbps InfiniBand) with communication efficiency :
Overlap Condition and Critical Block Size
To achieve 100% communication overlap (), the per-device block size must satisfy:
+---------------------------------------------------------------------------------------------------+
| CRITICAL BLOCK SIZE (B_crit) FOR FULL OVERLAP |
+---------------------------------------------------------------------------------------------------+
| Hardware Interconnect | Peak FP16 FLOPs | Net Bandwidth | Critical Block Size (B_crit) |
+--------------------------+-----------------+---------------+--------------------------------------+
| Intra-Node NVLink 4 | 989 TFLOP/s | 900 GB/s | ~775 tokens |
| Inter-Node InfiniBand | 989 TFLOP/s | 50 GB/s (400G)| ~13,960 tokens |
| Inter-Node Multi-Rail IB | 989 TFLOP/s | 400 GB/s (8x) | ~1,745 tokens |
+--------------------------+-----------------+---------------+--------------------------------------+In typical multi-node clusters with 8x 400 Gbps InfiniBand rails (3.2 Tbps aggregate bandwidth), the critical block size is approximately 1,745 tokens. Because long-context training tasks operate with per-device sequence chunks of to tokens, , ensuring that communication is fully hidden behind compute.
5. Causal Masking and Load Balancing: Striped vs. Zigzag Ring Attention
In autoregressive language models, attention is strictly causal: token can only attend to tokens , producing a lower-triangular attention matrix.
+---------------------------------------------------------------------------------------------------+
| CAUSAL ATTENTION MATRIX LOAD IMBALANCE |
+---------------------------------------------------------------------------------------------------+
| Block 0 Block 1 Block 2 Block 3 |
| Block 0 [ /\ ] [ ] [ ] [ ] <- GPU 0 (Computes 1 block, idles 3) |
| Block 1 [ Full ] [ /\ ] [ ] [ ] <- GPU 1 (Computes 2 blocks, idles 2) |
| Block 2 [ Full ] [ Full ] [ /\ ] [ ] <- GPU 2 (Computes 3 blocks, idles 1) |
| Block 3 [ Full ] [ Full ] [ Full ] [ /\ ] <- GPU 3 (Computes 4 blocks, idles 0) |
+---------------------------------------------------------------------------------------------------+The Causal Bubble Problem
In naive sequential partitioning, GPU holds queries for tokens in range . When key-value blocks from ranks arrive, they reside entirely in the masked upper-triangular region (), requiring zero computation. Consequently:
- GPU 0 computes only 1 step and idles for steps.
- GPU computes for all steps.
- Total Compute Efficiency: Exactly , wasting half of the cluster's processing power.
Solution 1: Striped Attention
Brandon et al. (2023) proposed Striped Attention, which shards tokens across GPUs round-robin rather than contiguously:
Because each GPU holds an identical distribution of early, middle, and late tokens across the entire sequence length , the causal mask ratio for every GPU at every ring step is identical (). While Striped Attention perfectly eliminates load imbalance, it introduces token permutation overheads for subsequent operations like Rotary Position Embeddings (RoPE) and LayerNorm.
Solution 2: Zigzag Ring Attention
The zigzag variant in the open-source ring-flash-attention project gives each device one chunk from the front of the sequence and its mirror chunk from the back, which preserves contiguous local chunks and balances causal work.
+---------------------------------------------------------------------------------------------------+
| ZIGZAG SEQUENCE ALLOCATION |
+---------------------------------------------------------------------------------------------------+
| Sequence is divided into 2N chunks: [c_0, c_1, ..., c_(2N-1)] |
| |
| GPU 0 holds: [ c_0 , c_7 ] (First chunk + Last chunk) |
| GPU 1 holds: [ c_1 , c_6 ] |
| GPU 2 holds: [ c_2 , c_5 ] |
| GPU 3 holds: [ c_3 , c_4 ] (Middle chunks) |
+---------------------------------------------------------------------------------------------------+Each GPU is assigned two blocks: one from the front of the sequence () and one from the back (). By alternating transmission directions and executing two sub-steps per ring iteration, Zigzag Ring Attention balances the number of active lower-triangular blocks across all GPUs at every ring step, achieving:
- 100% Compute Load Balance: Zero idle bubbles during causal decoding and training.
- Zero Permutation Overhead: Preserves contiguous tensor layouts for standard FlashAttention-2/3 kernels.
- Exact Causal Equivalence: Generates identical output to single-GPU causal attention.
6. Architectural Comparison: RingAttention vs. DeepSpeed-Ulysses vs. USP
Context Parallelism implementations diverge in their network communication topologies and scaling constraints.
+---------------------------------------------------------------------------------------------------+
| CONTEXT PARALLELISM ARCHITECTURAL COMPARISON |
+---------------------------------------------------------------------------------------------------+
| Dimension | DeepSpeed-Ulysses | RingAttention | Unified Sequence Parallel (USP) |
+--------------------------+------------------------------+-----------------------------+---------------------------------+
| Network Topology | All-to-All Collective | 1D Ring P2P Asynchronous | Hierarchical (All2All + Ring) |
| Scaling Bound | $N \le H$ (Attention Heads) | Arbitrary $N$ ($N \le S$) | $N \cdot M$ (Arbitrary Hybrid) |
| Communication Volume | $2 \times \frac{S \cdot d}{N}$ (All-to-All) | $2 \times S \cdot d$ (Total P2P) | Optimized 2D Grid |
| Comm-Compute Overlap | Difficult (Blocking All2All) | Natural (Double Buffering) | Full Inter-Node Overlap |
| Latency Sensitivity | High (Requires NVLink) | Low (InfiniBand Tolerant) | Robust across Heterogeneous Nets|
| Causal Mask Handling | Native (No Imbalance) | Requires Zigzag / Striped | Native within Node, Zigzag Ring |
+--------------------------+------------------------------+-----------------------------+---------------------------------+DeepSpeed-Ulysses
Jacobs et al. (2023) introduced DeepSpeed-Ulysses, which uses two all-to-all collective communication operations per attention layer:
- Input is projected into local .
- An All-to-All collective transposes the tensor layout from sequence-partitioned to head-partitioned .
- Standard local attention is executed over the full sequence length across a subset of heads.
- A second All-to-All transposes the output back to .
Limitation: Ulysses requires that the context parallel degree divide the number of attention heads (). For models with Grouped-Query Attention (GQA) where , pure Ulysses cannot scale beyond 8 GPUs.
Unified Sequence Parallelism (USP)
Fang et al. (2024) unified Ulysses and RingAttention into a 2D hybrid layout:
- Intra-Node (NVLink): Runs DeepSpeed-Ulysses with All-to-All across the 8 GPUs within a single server node, maximizing high-bandwidth interconnect utilization.
- Inter-Node (InfiniBand): Runs RingAttention with asynchronous P2P ring transfers across nodes, bypassing the head-count constraint while completely hiding inter-node network latency behind computation.
7. Memory and Backward Pass Complexity
During the backward pass of RingAttention, gradients , , and are computed via reverse ring rotation.
+---------------------------------------------------------------------------------------------------+
| RINGATTENTION BACKWARD PASS LOGIC |
+---------------------------------------------------------------------------------------------------+
| 1. Forward Activation Storage: |
| - Retain local Q_k and final logsumexp statistics: L_k = m_k^(N) + ln(l_k^(N)) |
| - Discard intermediate P_tilde and attention score matrices (Standard FlashAttention) |
| |
| 2. Backward Ring Recomputation: |
| - Rotate K and V blocks through the ring in reverse order |
| - Recompute local block attention scores S^(t) on SRAM using stored Q_k and arriving (K, V) |
| - Accumulate gradients dQ_k locally; accumulate dK and dV into rotating ring buffers |
| - Overlap dK, dV gradient buffer communication with backward GEMM execution |
+---------------------------------------------------------------------------------------------------+Complete Activation Footprint Comparison
The table below summarizes per-device memory allocation across parallel training strategies for an token sequence on a model with , , and :
+---------------------------------------------------------------------------------------------------+
| PER-DEVICE MEMORY FOOTPRINT (S = 1M, N = 64 GPUs) |
+---------------------------------------------------------------------------------------------------+
| Parallel Strategy | Layer Activation Memory | Communication Buffers | Peak Attention Memory |
+------------------------+-------------------------+-----------------------+------------------------+
| Megatron TP (TP=8) | ~65.5 GB (OOM Risk) | ~0.5 GB (All-Reduce) | > 80 GB (OOM) |
| DeepSpeed-Ulysses (CP=8)| ~8.2 GB | ~2.1 GB (All-to-All) | ~14.5 GB |
| RingAttention (CP=64) | ~1.02 GB | ~0.25 GB (Double Buf) | ~2.8 GB |
| Hybrid USP (U8 x R8) | ~1.02 GB | ~0.35 GB | ~2.6 GB |
+------------------------+-------------------------+-----------------------+------------------------+8. Real-World Applications and Ecosystem Integration
RingAttention and hybrid context parallelism are implemented in major open-source training and serving stacks:
- Large World Model (LWM): Liu et al. (2024) trained 7B and 34B multimodal models on sequence lengths of 1,000,000 tokens (representing full-length movies and podcast audio) using RingAttention on TPU v4/v5e and GPU clusters.
- NVIDIA Megatron-LM & TransformerEngine: Context Parallelism in Megatron-LM integrates RingAttention and Ulysses with native FP8 FlashAttention-3 kernels via
AttnFuncWithCPAndKVP2P. - vLLM & SGLang Long-Context Serving: For multi-turn agentic workflows and repository retrieval, inference engines deploy RingAttention during prefill to process 128k to 1M prompt tokens across distributed nodes without hitting single-node HBM ceilings.
Update (Oct 19, 2026)
- Ring Attention passes key-value blocks around a ring of devices while each device computes blockwise attention for its resident queries, overlapping the transfer with compute. Context length scales with the number of devices without approximation (Liu et al., 2023).
- When the transfer is hidden: each step computes about 4B^2 d FLOPs for a block of B tokens and sends one key block and one value block, 4Bd bytes in BF16. Compute covers communication when B is at least F/W, peak FLOPs over link bandwidth (Liu et al., 2023). For an H100 SXM at 989 dense BF16 TFLOPS and 450 GB/s per direction of its 900 GB/s NVLink (NVIDIA H100 specs), B needs to be about 2,200 tokens or more per device.
- Causal masks unbalance a contiguous ring, because early devices have little to compute. Striped Attention spreads each device's tokens uniformly through the sequence and reports up to 1.45x end-to-end throughput at 256K tokens on A100 GPUs and TPUv4, and 1.65x at 786K tokens on 16 TPUv4 chips (Brandon et al., 2023).
- With zigzag placement on P devices and 2P chunks, device p holds chunks p and 2P-1-p. For P = 4, every device then computes 9 causal block-attentions (for example 1 + 8 on device 0 and 4 + 5 on device 3). LoongTrain combines head and context parallelism to scale this further (Gu et al., 2024).
For production trade-offs and serving costs, read Context Parallelism in Production: Comparing DeepSpeed Ulysses, Megatron Sequence Parallelism, Ring Attention, and Unified Sequence Parallelism (USP) Architecture, Communication Overhead, and Scale-Out Economics. For a less mathematical introduction to the same idea, read Sequence Parallelism in Large Language Models: How Megatron-SP, DeepSpeed Ulysses, and RingAttention Distribute Long Contexts.
Sources
- Liu, H., Zaharia, M., & Abbeel, P. (2023). Ring Attention with Blockwise Transformers for Near-Infinite Context. arXiv:2310.01889.
- Liu, H., & Abbeel, P. (2023). Blockwise Parallel Transformer for Large Context Models. Advances in Neural Information Processing Systems (NeurIPS 2023). arXiv:2305.19370.
- Dao, T., Fu, D. Y., Ermon, S., Rudra, A., & Ré, C. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. Advances in Neural Information Processing Systems (NeurIPS 2022). arXiv:2205.14135.
- Jacobs, S. A., Tanaka, M., Zhang, C., et al. (2023). DeepSpeed Ulysses: System Optimizations for Enabling Training of Extreme Long Sequence Transformer Models. arXiv:2309.14509.
- Zhu, Z. ring-flash-attention: zigzag and striped ring attention implementations on FlashAttention. GitHub.
- Fang, J., & Zhao, H. (2024). USP: Unified Sequence Parallelism for Long-Context Transformer Model Training and Inference. arXiv:2405.07719.
- Liu, H., et al. (2024). World Model on Million-Length Video And Language With RingAttention. arXiv:2402.08268.
- Milakov, M., & Gimelshein, N. (2018). Online normalizer calculation for softmax. arXiv:1805.02867.
- Striped Attention: Faster Ring Attention for Causal Transformers
- LoongTrain: Efficient Training of Long-Sequence LLMs with Head-Context Parallelism
Frequently asked questions
How does RingAttention handle causal masking load imbalance?
Naive contiguous partitioning creates 'causal bubbles' where early GPUs idle because they compute zero work on upper-triangular masked blocks. RingAttention resolves this using Striped Attention, which distributes tokens round-robin, or Zigzag Ring Attention, which assigns front and back chunks to each device to ensure 100% compute load balance.
What is the critical block size for communication overlap on H100?
To fully hide communication latency behind compute, the per-device block size B must be at least equal to peak FLOPs divided by link bandwidth. For an NVIDIA H100 SXM with 989 TFLOP/s and 450 GB/s bidirectional NVLink, the critical block size is approximately 2,200 tokens.
How does RingAttention differ from Tensor Parallelism?
Tensor Parallelism partitions model weights along hidden and head dimensions, capping maximum parallel degree by the number of attention heads (typically 32-128). In contrast, Context Parallelism via RingAttention shards the sequence dimension S across arbitrary cluster scales N, removing the ceiling imposed by head count.
Can RingAttention be used during inference serving?
Yes, inference engines like vLLM and SGLang deploy RingAttention during the prefill phase. This allows them to process prompt tokens ranging from 128k to 1 million across distributed nodes without hitting single-node HBM ceilings.
