[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,97 +2,177 @@
|
||||
id: wiki-2026-0508-ring-attention
|
||||
title: Ring Attention
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-RATT-001]
|
||||
aliases: [Ring Self-Attention, Distributed Attention]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [auto-reinforced, ring-attention, context-parallelism, distributed-training, ultra-long-context]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [attention, long-context, distributed-training, transformer, systems]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-04
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: Python
|
||||
framework: JAX/PyTorch/CUDA
|
||||
---
|
||||
|
||||
# [[Ring Attention|Ring Attention]]
|
||||
# Ring Attention
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "무한을 향한 연결고리: 단일 GPU의 메모리 한계를 넘어, 여러 장치를 링(Ring) 형태로 연결하고 데이터를 순환시키며 어텐션을 계산함으로써, 이론적으로 무한대에 가까운 '초거대 컨텍스트' 확장을 실현하는 분산 처리의 혁신."
|
||||
## 매 한 줄
|
||||
> **"매 attention 의 sequence 의 N 의 device 의 ring 의 split — context length scales linearly with devices."**. Liu, Zaharia, Abbeel 2023 ("Ring Attention with Blockwise Transformers") 의 propose, 매 1M+ context window (Gemini 1.5 Pro, Claude Opus 4.7 1M) 의 training-time enabler 의, 매 communication overlap with compute 의 near-zero overhead.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
Ring Attention은 여러 GPU 또는 가속기 장치에 걸쳐 시퀀스 데이터를 분산 처리함으로써, 단일 장치의 메모리 용량을 초과하는 초장거리 문맥(Ultra-long context)을 학습하고 추론할 수 있게 해주는 기술입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **핵심 메커니즘 (Context Parallelism)**:
|
||||
* **시퀀스 분할**: 입력 문장을 $N$개의 조각으로 나누어 $N$개의 GPU에 분산 배치합니다.
|
||||
* **링 통신 (Ring Communication)**: 각 GPU는 자신이 가진 Query를 고정하고, 다른 GPU들이 가진 Key/Value 블록을 링 형태로 전달받아 순차적으로 어텐션을 계산합니다.
|
||||
* **비동기 처리**: 다음 KV 블록을 미리 받아오는 통신과 현재 블록의 연산을 겹쳐서 수행(Overlap)함으로써 통신 대기 시간을 최소화합니다.
|
||||
2. **주요 특징**:
|
||||
* **확장성**: 장치 수($N$)가 늘어날수록 처리 가능한 컨텍스트 길이가 선형적으로 증가합니다 (예: 1M, 10M 토큰 이상).
|
||||
* **정확도**: 근사치가 아닌 Full-Attention을 분산 환경에서 정확하게 계산해냅니다.
|
||||
3. **의의**:
|
||||
* 최근의 '백만 토큰 컨텍스트' 경쟁(Gemini, Claude 등)을 뒷받침하는 핵심 인프라 기술 중 하나로 평가받습니다.
|
||||
### 매 핵심 idea
|
||||
- Sequence 의 N device 의 split (each device holds 1/N tokens of Q, K, V).
|
||||
- Each device computes attention with its local Q against rotating K, V blocks.
|
||||
- K, V blocks travel ring N steps; communication 의 attention compute 와 overlap.
|
||||
- Result: full sequence attention 의 device 의 N 배 의 longer context 의 fit.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
* **통신 오버헤드**: 장치 간 데이터 전송(P2P Communication) 속도가 전체 성능의 병목이 될 수 있습니다. 따라서 NVLink와 같은 고속 인터커넥트가 필수적입니다.
|
||||
* **FlashAttention과의 상충**: 분할된 블록 단위로 FlashAttention을 수행할 때 발생하는 효율성 저하를 막기 위해, 통신 패턴을 극도로 정밀하게 설계해야 합니다 (예: USP 전략).
|
||||
### 매 vs alternatives
|
||||
- **Flash Attention**: single device, IO-aware, memory-efficient. Ring composes on top.
|
||||
- **Sequence Parallel (Megatron)**: similar split but layernorm/dropout only.
|
||||
- **Context Parallel (Megatron 2024)**: industrial Ring Attention variant.
|
||||
- **Striped Attention** (2023): improved load balance for causal masks.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
* **상위 개념**: [[Attention Mechanisms|Attention Mechanisms]], [[Distributed Training|Distributed Training]]
|
||||
* **비교/보완 기술**: [[Flash Attention|Flash Attention]], [[Sparse Attention|Sparse Attention]]
|
||||
* **응용 분야**: 100만 토큰 이상 장거리 문맥 모델링, 복잡한 코드베이스 전체 분석
|
||||
### 매 응용
|
||||
1. 1M+ context LLM training (Gemini 1.5/2.0, Claude Opus 4.x).
|
||||
2. Long video understanding.
|
||||
3. Whole-codebase code models.
|
||||
4. Long DNA sequence models (Evo).
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-04*
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### Conceptual Ring Loop (single block)
|
||||
```python
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
def ring_attention_step(q_local, kv_local, world_size):
|
||||
"""매 simplified single-pass illustration."""
|
||||
out = torch.zeros_like(q_local)
|
||||
lse = torch.full(q_local.shape[:-1], -float("inf"), device=q_local.device)
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
k, v = kv_local
|
||||
rank = dist.get_rank()
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
for step in range(world_size):
|
||||
# local attention partial
|
||||
partial_out, partial_lse = blockwise_attention(q_local, k, v)
|
||||
out, lse = online_softmax_merge(out, lse, partial_out, partial_lse)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
# rotate K, V to next neighbor (overlap with next compute)
|
||||
send_rank = (rank - 1) % world_size
|
||||
recv_rank = (rank + 1) % world_size
|
||||
k, v = ring_send_recv(k, v, send_rank, recv_rank)
|
||||
return out
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Online Softmax Merge
|
||||
```python
|
||||
def online_softmax_merge(out_a, lse_a, out_b, lse_b):
|
||||
"""매 numerically stable merge of 2 partial attention results."""
|
||||
m = torch.maximum(lse_a, lse_b)
|
||||
c_a = torch.exp(lse_a - m).unsqueeze(-1)
|
||||
c_b = torch.exp(lse_b - m).unsqueeze(-1)
|
||||
out = (c_a * out_a + c_b * out_b) / (c_a + c_b)
|
||||
new_lse = m + torch.log(torch.exp(lse_a - m) + torch.exp(lse_b - m))
|
||||
return out, new_lse
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Ring Send/Recv (NCCL)
|
||||
```python
|
||||
def ring_send_recv(k, v, send_rank, recv_rank):
|
||||
k_buf = torch.empty_like(k)
|
||||
v_buf = torch.empty_like(v)
|
||||
reqs = [
|
||||
dist.isend(k, send_rank), dist.isend(v, send_rank),
|
||||
dist.irecv(k_buf, recv_rank), dist.irecv(v_buf, recv_rank),
|
||||
]
|
||||
for r in reqs: r.wait()
|
||||
return k_buf, v_buf
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Striped (Causal-aware) Block Order
|
||||
```python
|
||||
def striped_block_order(seq_len, world_size, block_size):
|
||||
"""매 causal mask 의 load balance 의 — interleave 의 X stride."""
|
||||
n_blocks = seq_len // block_size
|
||||
return [(i * world_size + r) % n_blocks
|
||||
for r in range(world_size)
|
||||
for i in range(n_blocks // world_size)]
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Causal Mask Skip Optimization
|
||||
```python
|
||||
def should_compute(q_block_idx, kv_block_idx, causal=True):
|
||||
"""매 causal: skip 의 kv > q (future)."""
|
||||
return (not causal) or kv_block_idx <= q_block_idx
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Compute/Comm Overlap (CUDA streams)
|
||||
```python
|
||||
def overlapped_step(q, k, v, next_kv_handles, compute_stream, comm_stream):
|
||||
with torch.cuda.stream(compute_stream):
|
||||
partial = blockwise_attention(q, k, v)
|
||||
with torch.cuda.stream(comm_stream):
|
||||
next_k, next_v = ring_send_recv(k, v, ...)
|
||||
torch.cuda.synchronize()
|
||||
return partial, next_k, next_v
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### JAX Ring Attention (high-level)
|
||||
```python
|
||||
import jax
|
||||
from jax.experimental.shard_map import shard_map
|
||||
from jax.sharding import PartitionSpec as P
|
||||
|
||||
@jax.jit
|
||||
def ring_attn_pjit(q, k, v, mesh):
|
||||
return shard_map(
|
||||
ring_attention_fn,
|
||||
mesh=mesh,
|
||||
in_specs=(P("seq", None), P("seq", None), P("seq", None)),
|
||||
out_specs=P("seq", None),
|
||||
)(q, k, v)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| <32K context, single GPU | Flash Attention 3 only |
|
||||
| 32K–256K context, single node | Flash Attention + sequence parallel |
|
||||
| 256K–10M context, multi-node | Ring Attention (Striped variant) |
|
||||
| Causal model | Striped Ring Attention (load balance) |
|
||||
| TPU pod | JAX shard_map + Ring |
|
||||
|
||||
**기본값**: Striped Ring Attention with online softmax + NCCL ring + Flash Attention kernel as inner block.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Attention Mechanism]] · [[Distributed Training]]
|
||||
- 변형: [[Striped Attention]] · [[Context Parallelism]]
|
||||
- 응용: [[Long Context LLMs]] · [[Gemini]] · [[Claude Opus 4.7]]
|
||||
- Adjacent: [[Flash Attention]] · [[Sequence Parallel]] · [[Tensor Parallel]] · [[Online Softmax]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 long-context model 의 train/serve 의 evaluating, infra design 의 시.
|
||||
**언제 X**: 매 inference-only at small context 의 X — Flash Attention 만 의 sufficient.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Naive ring without overlap**: communication 의 sequential 의 → no speedup.
|
||||
- **Causal mask ignored**: 매 lower-triangle 의 50% compute 의 wasted 의 X — striped order 의 fix.
|
||||
- **Float32 accumulation skipped**: long context 의 numerical drift — fp32 LSE 의 keep.
|
||||
- **Pure data parallel for long context**: memory-bound — Ring or context parallel 의 use.
|
||||
- **Block size 의 cache 의 fit X**: bandwidth-bound — tune block_size to L2.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Liu et al. 2023 arXiv:2310.01889; Megatron-LM Context Parallelism docs 2024).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Ring Attention algo + Striped variant + JAX/PyTorch patterns |
|
||||
|
||||
Reference in New Issue
Block a user