AI Logic

Attention Mechanisms

Ring Attention

Updated๏ผš

Structure of Ring Attention. The left side shows the computation of one layer on one host: Q, K, and V are produced from the input block, block attention and sending/receiving K and V run simultaneously N_h times, and a blockwise feed-forward layer is applied. The right side shows K and V blocks moving to the next host on a ring of 4 hosts, and which host computes each tile of the 4 ร— 4 block attention matrix at which step.

What is Ring Attention?

Ring Attention is a method that splits a long sequence into blocks, gives one block to each of several GPUs or TPUs (hosts), and computes attention while passing the key and value blocks around a ring of hosts. Liu, Zaharia, and Abbeel at UC Berkeley proposed it in 2023 in the paper "Ring Attention with Blockwise Transformers for Near-Infinite Context."

Computing attention block by block, as FlashAttention does, avoids keeping the Nร—NN \times N matrix in memory. Even so, each layer's output (activations as long as the sequence) must still fit in the memory of a single device. By the paper's estimate, even a modest model with a hidden size of 1,024 needs more than 1,000 GB of memory to process 100 million tokens, which does not fit on a single GPU or TPU with less than 100 GB.

Ring Attention splits the sequence itself across the NhN_h hosts. Each host keeps its own query block, and only the key and value blocks travel around the ring. The next block is sent and received while the current block is being computed, so communication latency is almost entirely hidden. As a result, the sequence length that can be handled grows in proportion to the number of hosts.

As a conveyor-belt sushi analogy: the customers (query blocks) stay in their seats while the plates (key and value blocks) travel around the belt. Each customer receives the next plate while eating the one in front of them, so no one has to wait.

In the figure at the top of the article, the left side shows the computation on one host, and the right side shows the ring of hosts and which host computes which tile of the attention matrix at which step.

Theory

For Q,K,VโˆˆRsร—dQ, K, V \in \mathbb{R}^{s \times d} (ss is the sequence length), standard attention softmax(QKโŠค/d)V\mathrm{softmax}(QK^\top/\sqrt{d})V is computed. Following Algorithm 1 in the paper, Ring Attention computes it in these steps.

  1. Split the sequence: Divide the input sequence into NhN_h blocks and give one to each host.
  2. Compute Q, K, V on each host: Each host computes Qi,Ki,ViQ_i, K_i, V_i for its own block.
  3. Compute block attention: Using its own QiQ_i and the K,VK, V block currently on hand, each host computes memory-efficient blockwise attention and updates its partial results and statistics.
  4. Pass K and V at the same time: While computing, each host sends the K,VK, V block on hand to the next host on the ring and receives the next block from the previous host.
  5. Repeat steps 3โ€“4: Repeat until all NhN_h blocks have been processed (Nhโˆ’1N_h - 1 send/receive rounds).
  6. Compute the feed-forward layer: Apply a blockwise feed-forward layer to the attention output. Because it is a per-position computation, no communication with other hosts is needed.
  7. Move on to the next layer: Repeat steps 3โ€“6 for each layer. Backpropagation overlaps computation and communication in the same way.

In step 3, the order in which key and value blocks arrive differs from host to host. The result is still correct because blockwise attention gives the same result in any order, as long as the scale is corrected with the statistics. As in FlashAttention, keeping the row-wise maximum mm and sum โ„“\ell lets the results for blocks x(1),x(2)x^{(1)}, x^{(2)} be combined as follows.

m=maxโก(m(1),m(2)),โ„“=em(1)โˆ’mโ€‰โ„“(1)+em(2)โˆ’mโ€‰โ„“(2)m = \max\bigl(m^{(1)}, m^{(2)}\bigr), \qquad \ell = e^{m^{(1)} - m}\,\ell^{(1)} + e^{m^{(2)} - m}\,\ell^{(2)}

This formula is unchanged when the order of addition is swapped, so even though host ii receives the K,VK, V blocks in the order i,iโˆ’1,iโˆ’2,โ€ฆi, i-1, i-2, \dots, it ends up with the same value as softmax(QiKโŠค/d)V\mathrm{softmax}(Q_i K^\top/\sqrt{d})V. No approximation is involved.

When communication can be hidden, and memory

When communication can be hidden: Let FF be each host's compute speed (FLOPS), BB the bandwidth between hosts (bytes/s), cc the block size (number of tokens), and dd the hidden size. Attention for one block costs 2dc22dc^2 FLOPs for the scores and 2dc22dc^2 for the product with the values, 4dc24dc^2 FLOPs in total. The key and value blocks sent and received total 4cd4cd bytes. If the compute time is at least the communication time, communication can be hidden behind computation.

4dc2Fโ‰ฅ4cdBโŸบcโ‰ฅFB\frac{4dc^2}{F} \ge \frac{4cd}{B} \quad\Longleftrightarrow\quad c \ge \frac{F}{B}

In other words, if the block size is at least "compute speed รท bandwidth," communication latency disappears. The paper notes that this inequality leaves out the Q, K, V projections and the feed-forward computation, so the condition is looser in practice.

Memory needed per device: Each host holds one query block, two key and value blocks currently in use, two key and value blocks being received, and one output block: 6 blocks in total. The maximum activation size per layer is therefore 6bch6bch bytes (bb is the batch size, hh the hidden size; in bfloat16). Table 1 in the paper compares this with other methods as follows.

MethodAttentionFeed-forwardTotal
Standard Transformer2bns22bns^28bsh8bsh2bhs22bhs^2
Memory-efficient attention2bsh+4bch2bsh + 4bch8bsh8bsh8bsh8bsh
Memory-efficient attention and feed-forward (BPT)2bsh2bsh2bsh2bsh2bsh2bsh
Ring Attention6bch6bch2bch2bch6bch6bch

(nn is the number of heads and ss the sequence length.) The other methods still depend on the sequence length ss, but Ring Attention depends only on the block size cc and does not depend on the sequence length. To handle longer sequences, simply add more hosts.

The sequence length each host needs is six times the minimum block size (s=6cs = 6c). An excerpt from Table 2 in the paper follows.

DeviceCompute (TFLOPS)Bandwidth (GB/s)Minimum block (tokens)Minimum length per device (tokens)
A100 (NVLink)312300~1,000~6,200
A100 (InfiniBand)31212.5~24,500~149,500
TPU v4275268~1,000~6,200

With GPUs connected by NVLink or with TPUs, 6Kโ€“10K tokens per device are enough to hide communication. With slower interconnects such as InfiniBand, the condition becomes stricter.

Experimental results

Maximum sequence length: These are the maximum sequence lengths achieved when training models with the LLaMA architecture using batches of the same number of tokens (in thousands of tokens; excerpted from Table 3 in the paper). The baselines are the standard Transformer, memory-efficient attention, and memory-efficient attention and feed-forward (BPT).

HardwareModelStandardMemory-efficient attentionBPTRing Attention
8ร— A100 (NVLink)7B21632256 (8ร—)
32ร— A100 (InfiniBand)7B4641284,096 (32ร—)
TPU v3-5127B1482,048 (256ร—)
TPU v4-10243B8163216,384 (512ร—)
TPU v4-102430B2482,048 (256ร—)

The numbers in parentheses are the factor relative to BPT. With 8 A100s it is 8ร—, and with 32 it is 32ร—: the maximum length grows in proportion to the number of hosts. With 32 A100s, a 7B model could be trained on sequences longer than 1 million tokens. The paper also states that compute efficiency (model FLOPs utilization) barely dropped.

Reinforcement learning: In the Agentic Transformer (AT), which learns from sequences of trial-and-error experience, the number of trajectories used for conditioning could be increased from 32 to 128, raising the average cumulative return over six ExoRL tasks from 111.13 to 113.66 (Table 5 in the paper). With BPT, 128 trajectories did not fit in memory.

Language models: LLaMA-13B was fine-tuned on 32 A100s up to a context length of 512K tokens, and on a task of accurately retrieving numbers from long documents it kept high accuracy even at lengths that short-context models cannot handle (Figure 3 in the paper).

Practical considerations

Ring Attention computes attention by splitting the sequence across multiple hosts without changing the attention formula.

To hide communication behind computation, each host's block must be large enough (block size cโ‰ฅF/Bc \ge F/B). Slow communication between hosts makes this condition stricter. By the paper's estimate, A100s connected with NVLink need about 6,200 tokens per device, but with InfiniBand about 149,500 tokens are needed. With short sequences or slow interconnects, communication latency shows up.

Keep the following points in mind when using it.

  • The amount of computation itself is not reduced: Attention still costs time proportional to the square of the sequence length; Ring Attention divides that work among the hosts. Doubling the sequence roughly quadruples the total computation.
  • Combine it with other forms of parallelism: The paper's experiments combine it with FSDP, which shards the model weights, and tensor parallelism. Since Ring Attention splits only along the sequence dimension, it can be used independently of data parallelism and similar methods.
  • Use a memory-efficient implementation for the computation on each host: Ring Attention calls whatever memory-efficient blockwise attention is available on each host (such as FlashAttention) and rotates the blocks around it.
  • The paper's experiments use gradient checkpointing on every layer and full precision rather than mixed precision: Check these conditions when comparing numbers.

Comparison with other methods

Methods for handling long sequences are compared below by "what they split and what they reduce."

MethodWhat it doesMemory per device (in sequence length ss)Computed result
FlashAttention, FlashAttention-2Splits attention into blocks within one device and never builds the Nร—NN \times N matrixProportional to ss for layer outputsSame
BPT (Liu and Abbeel, 2023)Computes both attention and the feed-forward layer block by blockProportional to ss (2bsh2bsh)Same
Ring Attention (Liu et al., 2023)Splits the sequence across hosts and passes K/V blocks around a ring, overlapping communication with computationDetermined only by the block size cc (6bch6bch)Same
Sparse attention, Linformer, etc.Reduce the pairs computed or shrink the matrixProportional to ssApproximate

Sequence-parallel methods that split attention in a ring existed before, but they could not fully overlap communication with computation, so communication time became a problem for long sequences. Ring Attention differs in hiding communication by combining it with blockwise computation.

As a rough guide to choosing among them:

  • Lengths that fit in one device's memory: FlashAttention-2 alone is enough.
  • Training or inference without approximation on sequences too long for one device's memory (hundreds of thousands to millions of tokens): Split the sequence across multiple hosts with Ring Attention.
  • Reducing the amount of computation itself: Consider approximation methods that compute fewer pairs.

PyTorch example

Show code
python
import torch


def ring_attention_simulated(q_blocks, k_blocks, v_blocks):
    """Simulate Ring Attention on a single device (Algorithm 1 of the paper; a small implementation for checking the mechanism).
    q_blocks[i], k_blocks[i], v_blocks[i]: blocks held by host i [c, d].
    In practice each host computes in parallel and overlaps sending/receiving K, V with computation"""
    n_hosts = len(q_blocks)
    d = q_blocks[0].shape[-1]
    kv = list(zip(k_blocks, v_blocks))           # K, V currently on each host
    outs = []
    state = [None] * n_hosts                       # (o, m, l) for each host
    for step in range(n_hosts):
        for i in range(n_hosts):                   # done simultaneously on every host
            k, v = kv[i]
            s = q_blocks[i] @ k.T / d ** 0.5
            m_blk = s.max(dim=1, keepdim=True).values
            p = torch.exp(s - m_blk)
            o_blk, l_blk = p @ v, p.sum(dim=1, keepdim=True)
            if state[i] is None:
                state[i] = (o_blk, m_blk, l_blk)
            else:                                  # rescale with the statistics and combine (order-independent)
                o, m, l = state[i]
                m_new = torch.maximum(m, m_blk)
                a, b = torch.exp(m - m_new), torch.exp(m_blk - m_new)
                state[i] = (a * o + b * o_blk, m_new, a * l + b * l_blk)
        # send/receive: host i sends K, V to i + 1 and receives from i โˆ’ 1 (rotate the ring by one)
        kv = [kv[(i - 1) % n_hosts] for i in range(n_hosts)]
    return torch.cat([o / l for o, _, l in state])


n_hosts, c, d = 4, 128, 64
x = [torch.randn(c, d) for _ in range(n_hosts)]
q, k, v = x, [t * 0.5 for t in x], [t + 1 for t in x]
out = ring_attention_simulated(q, k, v)
Q, K, V = torch.cat(q), torch.cat(k), torch.cat(v)
print(torch.allclose(out, torch.softmax(Q @ K.T / d ** 0.5, dim=-1) @ V, atol=1e-5))  # True

# On real multi-GPU setups, torch.distributed send/receive (isend / irecv) passes K, V to the neighboring rank,
# and computation on the local block starts before waiting for the transfer to finish, overlapping communication with computation.

FAQ

Q. Is Ring Attention an approximation?
A.

No. Blockwise attention results are combined while rescaling with the row-wise maximum and sum, so the result equals standard attention no matter in which order the blocks are computed. The only thing that changes is which host performs which computation and when.

Q. How long a sequence can be handled by adding hosts?
A.

The memory needed per device depends only on the block size, so the manageable length grows in proportion to the number of hosts. In the paper's experiments, sequences 8ร— longer than BPT could be trained with 8 A100s, 32ร— longer with 32, and up to 512ร— longer on TPU v4-1024. However, computation grows with the square of the sequence length, so training also takes longer.

Q. How should it be used alongside FlashAttention?
A.

FlashAttention computes attention efficiently within a single GPU, while Ring Attention splits the sequence across multiple devices. The two can be combined: a memory-efficient implementation like FlashAttention is used for the block computation inside each Ring Attention host.

References

  1. H. Liu, M. Zaharia, and P. Abbeel, "Ring Attention with Blockwise Transformers for Near-Infinite Context," arXiv:2310.01889, 2023.
  2. T. Dao, D. Y. Fu, S. Ermon, A. Rudra, and C. Rรฉ, "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness," NeurIPS, 2022.
  3. Official implementation of Ring Attention (lhao499/llm_large_context)