Track VIII · Inference & Optimisation · 08/09

긴 문맥 서빙Long-context serving

1M 토큰에서 무엇이 터지는지(KV 저장 O(T), prefill attention O(T²), decode KV 읽기 O(T))를 계산하고, attention이 선형 부분을 넘는 교차점 T*를 유도한다. chunked prefill, context parallelism(ring attention, pass-KV vs pass-Q, zigzag 샤딩), sparse·linear·SWA attention 모델의 서빙 문제(상태 스냅샷, indexer 스캔), KV 압축과 offload의 손익분기를 다루고, ring attention이 full attention과 정확히 같음을 NumPy로 확인한다.Work out what breaks at 1M tokens (KV storage O(T), prefill attention O(T²), decode KV reads O(T)) and derive the crossover T* where attention overtakes the linear layers. Then chunked prefill, context parallelism (ring attention, pass-KV vs pass-Q, zigzag sharding), the serving problems of sparse, linear and sliding-window attention models (state snapshots, indexer scans), and the break-even of KV compression and offload — with a NumPy check that ring attention equals full attention exactly.

A 128K context is now table stakes, and the frontier releases of 2026 advertise 1M (DeepSeek-V4, Nemotron 3 Ultra, Qwen3.5). Serving that is not “the same thing, longer”. Three costs scale with the context length TT, at different rates, and each one breaks a different part of the serving stack:

CostScales asWhat it breaks
KV storage per sequenceO(T)O(T)memory, batch size, prefix caching
Prefill attention FLOPsO(T2)O(T^2)time to first token (TTFT)
KV read per decoded tokenO(T)O(T) per tokentime per output token (TPOT)

This lesson computes all three for real designs, then goes through the tools: chunked prefill (memory), context parallelism (prefill latency), sparse, linear and windowed attention (the architecture’s answer), and KV compression and offload (the storage answer). The basics of the KV cache and of decode being bandwidth-bound are in LLM inference and the roofline; paged KV and prefix caching in KV cache; the online-softmax trick in attention kernels.

The arithmetic of a million tokens

Storage. For a GQA layer the KV of one token is 2⋅nkv⋅dh⋅b2 \cdot n_{kv} \cdot d_h \cdot b bytes. A 70B-class dense model (80 layers, 8 KV heads of 128 dims, bf16) stores 80⋅2⋅8⋅128⋅2=327,68080 \cdot 2 \cdot 8 \cdot 128 \cdot 2 = 327{,}680 B = 320 KiB per token, so one 1M-token sequence needs 320 GiB of KV — four 80 GB GPUs before a single weight is loaded. The architectures of the last two years attack this number on different axes:

  • MLA (DeepSeek-V3) caches one 576-dim latent per layer: 61×576×2=70,27261 \times 576 \times 2 = 70{,}272 B/token, 68.6 GiB at 1M (V3 lesson, attention & KV).
  • DSA (V3.2) keeps that storage (plus a small indexer key) and only reads the top-2048 entries per query (V3.2 lesson).
  • CSA/HCA (V4) compresses along the sequence: 4 tokens → 1 entry (read sparsely) or 128 → 1 (read densely), plus a 128-token window per layer. The V4 lesson reproduces ≈ 4,970 B/token for V4-Pro, about 2% of a bf16 GQA8 stack of the same depth (V4 report §2.3.4).
  • Hybrids drop KV from most layers. Qwen3.5-397B keeps full attention in 15 of 60 layers (15×2⋅2⋅256⋅2=3015 \times 2 \cdot 2 \cdot 256 \cdot 2 = 30 KiB/token) and carries a fixed recurrent state in the other 45 (Qwen3-Next lesson). Nemotron 3 Ultra has 12 attention layers, 12,288 B/token, plus ≈ 403 MB of FP32 Mamba state per sequence; the two are equal at 32,768 tokens (Nemotron lesson).

Prefill FLOPs. Processing a token through the linear layers costs 2N2N FLOPs (NN = active parameters). Attention of the query at position tt against tt keys costs 2dattnt2 d_{\text{attn}} t for QK⊤QK^\top and the same for PVPV, per layer, where dattn=nhdhd_{\text{attn}} = n_h d_h is the query width. Summed over a causal prefill of length TT:

Fprefill(T)=2NT⏟linear+4L dattn∑t=1Tt⏟attention≈2NT+2L dattn T2.F_{\text{prefill}}(T) = \underbrace{2NT}_{\text{linear}} + \underbrace{4 L\, d_{\text{attn}} \sum_{t=1}^{T} t}_{\text{attention}} \approx 2NT + 2 L\, d_{\text{attn}}\, T^2 .

The two terms are equal at

T∗=NL dattn.T^* = \frac{N}{L\, d_{\text{attn}}} .

For the 70B-class model (L=80L = 80, dattn=64×128=8192d_{\text{attn}} = 64 \times 128 = 8192) that is T∗≈107T^* \approx 107K tokens. Below it you are paying for the weights; above it you are paying for attention, and at 1M attention is ≈ 90% of the prefill. A useful sanity check against published numbers: for Llama3 405B (L=126L = 126, dattn=16384d_{\text{attn}} = 16384) the formula gives 4.9×10184.9 \times 10^{18} FLOPs for a 10610^6-token prefill, which is exactly the total Yang et al. state in their Appendix A — and it is consistent with their measured 77 s on 128 H100s at ≈ 502 TFLOP/s each (77×128×5.02×1014≈4.9×101877 \times 128 \times 5.02 \times 10^{14} \approx 4.9 \times 10^{18}).

Decode reads. Each new token reads the whole KV of its own sequence. Unlike weights, this read is not shared across the batch: every sequence has its own KV. So the arithmetic intensity of the attention read is fixed by the architecture, not by the batch size. Per key and layer, GQA does 4nhdh4 n_h d_h FLOPs on 4nkvdh4 n_{kv} d_h bytes (bf16), i.e. nh/nkvn_h/n_{kv} FLOP/byte — 8 for the 70B-class model, far below any GPU’s ridge point of a few hundred. MLA in its absorbed (MQA) decode mode does 2⋅128⋅(576+512)=278,5282 \cdot 128 \cdot (576 + 512) = 278{,}528 FLOPs per 1,152-byte entry, ≈ 242 FLOP/byte — one reason MLA decode is cheap in bandwidth but not in compute, and why DSA’s top-kk matters for decode too. A dense 70B at 1M would read 320 GiB per decoded token: ≈ 0.1 s per token at 3.35 TB/s if it fitted on one GPU.

128K 문맥은 이제 기본이고, 2026년의 frontier 모델들은 1M을 내세운다(DeepSeek-V4, Nemotron 3 Ultra, Qwen3.5). 이것을 서빙하는 일은 “같은 일을 더 길게”가 아니다. 문맥 길이 TT에 따라 세 가지 비용이 서로 다른 속도로 커지고, 각각 서빙 스택의 다른 부분을 부순다.

비용증가 속도무엇이 깨지나
시퀀스당 KV 저장O(T)O(T)메모리, 배치 크기, prefix caching
prefill attention FLOPsO(T2)O(T^2)첫 토큰까지의 시간(TTFT)
decode 토큰당 KV 읽기토큰마다 O(T)O(T)출력 토큰당 시간(TPOT)

이 레슨은 실제 설계들에 대해 이 셋을 계산한 다음, 도구들을 차례로 다룬다. chunked prefill(메모리), context parallelism(prefill 지연), sparse·linear·window attention(아키텍처의 답), KV 압축과 offload(저장의 답). KV cache와 decode가 대역폭에 묶인다는 기본은 LLM 추론과 roofline에, paged KV와 prefix caching은 KV cache에, online softmax는 attention 커널에 있다.

백만 토큰의 산수

저장. GQA 층에서 토큰 하나의 KV는 2⋅nkv⋅dh⋅b2 \cdot n_{kv} \cdot d_h \cdot b 바이트다. 70B급 dense 모델(80층, 128차원 KV head 8개, bf16)은 토큰당 80⋅2⋅8⋅128⋅2=327,68080 \cdot 2 \cdot 8 \cdot 128 \cdot 2 = 327{,}680 B = 320 KiB를 저장하므로 1M 토큰 시퀀스 하나에 KV만 320 GiB가 든다. 가중치를 올리기도 전에 80 GB GPU 네 장이다. 지난 2년의 아키텍처들은 이 숫자를 서로 다른 축에서 공격했다.

  • MLA(DeepSeek-V3)는 층마다 576차원 latent 하나를 캐시한다. 61×576×2=70,27261 \times 576 \times 2 = 70{,}272 B/토큰, 1M에서 68.6 GiB(V3 레슨, attention과 KV).
  • DSA(V3.2)는 그 저장량을 그대로 두고(작은 indexer key 추가) query마다 top-2048 항목만 읽는다(V3.2 레슨).
  • CSA/HCA(V4)는 시퀀스 방향으로 압축한다. 4토큰 → 항목 1개(희소하게 읽음) 또는 128 → 1(전부 읽음)에, 층마다 128토큰 window를 더한다. V4 레슨은 V4-Pro의 약 4,970 B/토큰을 재현하는데, 같은 깊이의 bf16 GQA8의 약 2%다(V4 보고서 §2.3.4).
  • Hybrid는 대부분의 층에서 KV를 없앤다. Qwen3.5-397B는 60층 중 15층만 full attention이고(15×2⋅2⋅256⋅2=3015 \times 2 \cdot 2 \cdot 256 \cdot 2 = 30 KiB/토큰) 나머지 45층은 고정 크기 recurrent 상태를 갖는다(Qwen3-Next 레슨). Nemotron 3 Ultra는 attention 12층, 12,288 B/토큰에 시퀀스당 FP32 Mamba 상태 약 403 MB를 더하며, 둘은 32,768토큰에서 같아진다(Nemotron 레슨).

Prefill FLOPs. 토큰 하나를 선형층에 통과시키는 비용은 2N2N FLOPs다(NN = 활성 파라미터). 위치 tt의 query가 key tt개와 하는 attention은 층마다 QK⊤QK^\top에 2dattnt2 d_{\text{attn}} t, PVPV에 같은 만큼이 든다(dattn=nhdhd_{\text{attn}} = n_h d_h는 query 폭). 길이 TT의 causal prefill 전체로 더하면

Fprefill(T)=2NT⏟선형+4L dattn∑t=1Tt⏟attention≈2NT+2L dattn T2.F_{\text{prefill}}(T) = \underbrace{2NT}_{\text{선형}} + \underbrace{4 L\, d_{\text{attn}} \sum_{t=1}^{T} t}_{\text{attention}} \approx 2NT + 2 L\, d_{\text{attn}}\, T^2 .

두 항은 다음에서 같아진다.

T∗=NL dattn.T^* = \frac{N}{L\, d_{\text{attn}}} .

70B급 모델(L=80L = 80, dattn=64×128=8192d_{\text{attn}} = 64 \times 128 = 8192)이면 T∗≈107T^* \approx 107K 토큰이다. 그보다 짧으면 가중치 값을 치르고, 길면 attention 값을 치른다. 1M에서는 prefill의 약 90%가 attention이다. 공개된 숫자로 검산해 볼 수 있다. Llama3 405B(L=126L = 126, dattn=16384d_{\text{attn}} = 16384)에 대해 이 식은 10610^6토큰 prefill에 4.9×10184.9 \times 10^{18} FLOPs를 주는데, Yang et al.이 부록 A에 적은 총량과 정확히 같고, 그들이 잰 128장 H100에서 77초, 장당 약 502 TFLOP/s와도 맞는다(77×128×5.02×1014≈4.9×101877 \times 128 \times 5.02 \times 10^{14} \approx 4.9 \times 10^{18}).

Decode 읽기. 새 토큰마다 자기 시퀀스의 KV 전체를 읽는다. 가중치와 달리 이 읽기는 배치끼리 나눠 갖지 못한다. 시퀀스마다 자기 KV가 있기 때문이다. 그래서 attention 읽기의 arithmetic intensity는 배치 크기가 아니라 아키텍처가 정한다. key 하나, 층 하나에 GQA는 4nkvdh4 n_{kv} d_h 바이트(bf16)에 대해 4nhdh4 n_h d_h FLOPs를 하므로 nh/nkvn_h/n_{kv} FLOP/byte, 70B급 모델이면 8이다. 어떤 GPU의 ridge point(수백)보다도 한참 낮다. MLA는 흡수(MQA) decode 모드에서 1,152바이트 항목 하나에 2⋅128⋅(576+512)=278,5282 \cdot 128 \cdot (576 + 512) = 278{,}528 FLOPs, 약 242 FLOP/byte를 한다. MLA decode가 대역폭으로는 싸지만 계산으로는 싸지 않은 이유이고, DSA의 top-kk가 decode에서도 중요한 이유다. 1M에서 dense 70B는 decode 토큰마다 320 GiB를 읽는다. GPU 한 장에 들어간다 해도 3.35 TB/s에서 토큰당 약 0.1초다.

Left: KV cache (plus fixed recurrent/window state) of one sequence, log–log, against an 80 GB line. Right: the share of prefill FLOPs spent in attention (vs the 2·Nactive linear part); where a curve crosses 50% is the crossover T*. The selected design is bold. Slide T to 1M and switch designs: dense GQA needs ~320 GiB per sequence and spends 90% of prefill in attention; MLA shrinks the bytes but not the FLOPs; DSA and V4 cut the FLOPs; the hybrid and SWA designs cut both by removing KV from most layers. Per-pair FLOP counts (MLA and DSA prefill in MHA mode, decode in the absorbed MQA mode) and V4's layer split are our estimates. 왼쪽: 시퀀스 하나의 KV cache(고정 크기 recurrent/window 상태 포함), log–log 축, 80 GB 기준선. 오른쪽: prefill FLOPs 중 attention이 차지하는 비율(나머지는 2·Nactive 선형 부분). 곡선이 50%를 지나는 곳이 교차점 T*다. 고른 설계가 굵은 선이다. T를 1M으로 밀고 설계를 바꿔 보라. dense GQA는 시퀀스당 약 320 GiB, prefill의 90%를 attention에 쓴다. MLA는 바이트를 줄이지만 FLOPs는 못 줄이고, DSA와 V4는 FLOPs를 줄이며, hybrid와 SWA는 대부분의 층에서 KV를 없애 둘 다 줄인다. 쌍당 FLOP 수(MLA와 DSA의 prefill은 MHA 모드, decode는 흡수된 MQA 모드)와 V4의 층 배분은 이 레슨의 추정이다.

Things to check in the figure:

  1. At 1M, dense GQA sits two orders of magnitude above the 80 GB line, and its attention share is ≈ 90%. Its T* (≈ 107K) is where the right-hand curve crosses 50%.
  2. MLA moves the left curve down by ≈ 4.7× but the right curve up: per (query, key) pair MLA’s attention is heavier than GQA’s, and the active parameters are smaller, so attention dominates earlier. Storage and compute are different axes.
  3. MLA + DSA keeps MLA’s storage but flattens the attention curve: main attention reads at most 2,048 entries, and what remains is the O(T)O(T) indexer scan per query. In the readout, at 1M the decode attention FLOPs drop by more than an order of magnitude compared to MLA.
  4. V4 (estimate) moves both curves down. Our crude count gives V4-Pro ≈ 26% of V3.2’s per-token FLOPs at 1M, close to the report’s 27% (V4 abstract); for KV our count gives ≈ 6% of V3.2 with a bf16 latent, against the report’s 10% — the gap depends on the storage format assumed for V3.2’s cache, which we did not verify.
  5. The hybrid and SWA designs start above some others at 4K (the fixed recurrent state or window costs something even for short contexts) but grow 4× (hybrid) or 2× (SWA
    1:1) more slowly.

Chunked prefill at 1M

A one-shot prefill of 1M tokens is impossible for a plainer reason than FLOPs: activations. The MLP intermediate of one layer alone is T×dff×2T \times d_{ff} \times 2 bytes, about 57 GB at T=220T = 2^{20} and dff=28,672d_{ff} = 28{,}672. So long prompts are processed in chunks of CC tokens (a few thousand): each chunk runs through all layers, appends its K and V to the cache, and its queries attend to the cache plus the causal part of the chunk. Because attention is causal, the result is the same computation as a one-shot prefill, up to floating-point reordering (the NumPy block below checks it).

What chunking does not do is reduce FLOPs. Chunk jj (starting at position jCjC) costs

Fj=2NC+4Ldattn(C⋅jC+C(C+1)2),F_j = 2NC + 4 L d_{\text{attn}} \Big( C \cdot jC + \tfrac{C(C+1)}{2} \Big),

linear in jj: for the 70B-class model with C=8192C = 8192, the first chunk is ≈ 1.2 PFLOP and the 128th ≈ 23.6 PFLOP, 95% of it attention. Chunking bounds memory and lets a scheduler interleave the chunks with other requests’ decode steps (batching & scheduling), but the TTFT of the long request is still ≈1.6×1018\approx 1.6 \times 10^{18} FLOPs ÷ your FLOP/s — over an hour on one GPU at 400 TFLOP/s effective. Only more GPUs on the same sequence shorten that, which is the next section.

Context parallelism

Which axis should be split to put many GPUs on one long sequence?

  • Tensor parallelism splits each matmul but needs an all-reduce of the activations after attention and after the MLP: about 2⋅T⋅nhdh2 \cdot T \cdot n_h d_h elements per block. Inside a node over NVLink that is fine; across nodes it is not.
  • Pipeline parallelism splits layers. It raises throughput with many requests in flight but does nothing for the latency of one prefill: the sequence still goes through every stage in order.
  • Context parallelism (CP) splits the sequence. Each rank holds the weights (CP does not shard them) and a slice of the tokens; everything except attention is token-local and needs no communication. Attention needs other ranks’ K and V, which travel around a ring: T⋅nkvdhT \cdot n_{kv} d_h elements per layer in total, nh/nkvn_h / n_{kv} times less than one TP all-reduce operand with GQA.

That communication gap is why Yang et al. (Meta) use TP8 inside a node and CP across nodes, and report that on their hosts the latency gap between CP2 and TP16 on 2 nodes is ≈ 15% and grows to ≈ 100% at 8 nodes.

Ring attention is exact

Rank rr holds queries QrQ_r and, at ring step ss, the KV block of rank (r−s) mod N(r - s) \bmod N. It never sees the whole score row, so it keeps the online-softmax state of FlashAttention: a running max mm, denominator ℓ\ell and unnormalised output aa. On a new block with scores SS and values VbV_b:

m′=max⁡(m,max⁡jS⋅j),ℓ′=em−m′ℓ+∑jeS⋅j−m′,a′=em−m′a+∑jeS⋅j−m′Vb,j,m' = \max(m, \max_j S_{\cdot j}), \quad \ell' = e^{m - m'} \ell + \sum_j e^{S_{\cdot j} - m'}, \quad a' = e^{m - m'} a + \sum_j e^{S_{\cdot j} - m'} V_{b,j},

and the output after the last block is a/ℓa/\ell. Since ∑jeSj−mVj/∑jeSj−m\sum_j e^{S_j - m} V_j / \sum_j e^{S_j - m} does not depend on mm or on the order of the blocks, the result is exactly softmax attention — no approximation, only floating-point reordering. While rank rr computes on block ss, it is already sending that block to r+1r+1 and receiving block s+1s+1.

When is the transfer hidden? With n=T/Nn = T/N tokens per rank, one step computes a n×nn \times n tile, ≈4n2nhdh\approx 4 n^2 n_h d_h FLOPs (full tile), and moves 2n nkvdh e2 n\, n_{kv} d_h\, e bytes (ee bytes per element). The transfer hides behind compute when

4n2nhdhF≥2n nkvdh eB  ⟺  n≥nkvnh⋅eF2B.\frac{4 n^2 n_h d_h}{F} \ge \frac{2 n\, n_{kv} d_h\, e}{B} \iff n \ge \frac{n_{kv}}{n_h} \cdot \frac{e F}{2B} .

With 128/8 heads, bf16, F=400F = 400 TFLOP/s and B=50B = 50 GB/s, n≥500n \ge 500 tokens per rank. Ring attention hides its communication easily at long context — the transfer is linear in nn, the compute quadratic. (The CP paper’s Algorithm 1 has the same form, T≥NCNKVe/(2NHB)T \ge N C N_{KV} e / (2 N_H B), with whole-sequence TT and node-level C,BC, B.)

The causal mask breaks the balance

With causal attention, a query block never needs KV blocks from later positions. If rank rr holds the rr-th contiguous block, at step ss it receives the block of rank r−sr - s: for r<sr < s that block lies in its future and the rank idles, while the last rank computes at every step. The step time is set by the busiest rank.

그림에서 확인할 것:

  1. 1M에서 dense GQA는 80 GB 선보다 두 자릿수 위에 있고 attention 비율은 약 90%다. T*(약 107K)는 오른쪽 곡선이 50%를 지나는 점이다.
  2. MLA는 왼쪽 곡선을 약 4.7배 내리지만 오른쪽 곡선은 올린다. (query, key) 쌍당 MLA의 attention이 GQA보다 무겁고 활성 파라미터는 더 작아서, attention이 더 일찍 지배한다. 저장과 계산은 다른 축이다.
  3. MLA + DSA는 MLA의 저장량을 유지하면서 attention 곡선을 눕힌다. 주 attention은 많아야 2,048개 항목을 읽고, 남는 것은 query마다의 O(T)O(T) indexer 스캔이다. 읽기 값에서 1M의 decode attention FLOPs가 MLA보다 한 자릿수 넘게 줄어든다.
  4. **V4(추정)**는 두 곡선을 모두 내린다. 우리의 거친 계산은 1M에서 V4-Pro의 토큰당 FLOPs를 V3.2의 약 26%로 주는데, 보고서의 27%(V4 초록)와 가깝다. KV는 bf16 latent 기준으로 V3.2의 약 6%가 나오는데 보고서는 10%라고 한다. 차이는 V3.2 캐시의 저장 형식을 무엇으로 가정하느냐에 달려 있고, 우리는 그것을 확인하지 않았다.
  5. hybrid와 SWA 설계는 4K에서는 일부 다른 설계보다 위에서 시작하지만(고정 크기 recurrent 상태나 window는 짧은 문맥에서도 비용이 있다), 4배(hybrid) 또는 2배(SWA
    1:1) 느리게 자란다.

1M에서의 chunked prefill

1M 토큰을 한 번에 prefill하는 것은 FLOPs보다 더 단순한 이유로 불가능하다. activation이다. 한 층의 MLP 중간값만 T×dff×2T \times d_{ff} \times 2바이트, T=220T = 2^{20}, dff=28,672d_{ff} = 28{,}672이면 약 57 GB다. 그래서 긴 프롬프트는 CC토큰(수천) 단위의 청크로 처리한다. 청크 하나가 모든 층을 지나며 자기 K, V를 캐시에 덧붙이고, 그 query는 캐시 전체와 청크 안의 causal 부분에 attention한다. attention이 causal이므로 결과는 부동소수 순서 차이를 빼면 한 번에 하는 prefill과 같은 계산이다(아래 NumPy 블록이 확인한다).

chunking이 하지 않는 일은 FLOPs를 줄이는 것이다. jj번째 청크(위치 jCjC에서 시작)의 비용은

Fj=2NC+4Ldattn(C⋅jC+C(C+1)2)F_j = 2NC + 4 L d_{\text{attn}} \Big( C \cdot jC + \tfrac{C(C+1)}{2} \Big)

로 jj에 선형이다. 70B급 모델, C=8192C = 8192에서 첫 청크는 약 1.2 PFLOP, 128번째 청크는 약 23.6 PFLOP이고 그중 95%가 attention이다. chunking은 메모리를 묶어 두고 스케줄러가 청크 사이에 다른 요청의 decode step을 끼워 넣게 해 주지만(배칭과 스케줄링), 긴 요청의 TTFT는 여전히 약 1.6×10181.6 \times 10^{18} FLOPs ÷ FLOP/s다. 실효 400 TFLOP/s GPU 한 장이면 한 시간이 넘는다. 그것을 줄이는 방법은 같은 시퀀스에 GPU를 더 붙이는 것뿐이고, 그것이 다음 절이다.

Context parallelism

긴 시퀀스 하나에 GPU 여러 장을 붙이려면 어느 축을 나눠야 할까?

  • Tensor parallelism은 각 matmul을 나누지만 attention 뒤와 MLP 뒤에 activation all-reduce가 필요하다. block마다 약 2⋅T⋅nhdh2 \cdot T \cdot n_h d_h개 원소다. 노드 안 NVLink에서는 괜찮지만 노드 사이에서는 아니다.
  • Pipeline parallelism은 층을 나눈다. 요청이 많이 떠 있으면 처리량을 올리지만 prefill 하나의 지연은 줄이지 못한다. 시퀀스는 여전히 모든 stage를 차례로 지나간다.
  • **Context parallelism(CP)**은 시퀀스를 나눈다. 각 rank는 가중치 전체(CP는 가중치를 나누지 않는다)와 토큰 일부를 갖는다. attention을 뺀 모든 것은 토큰별로 독립이라 통신이 없다. attention은 다른 rank의 K, V가 필요하고, 그것이 링을 돈다. 층마다 총 T⋅nkvdhT \cdot n_{kv} d_h개 원소로, GQA에서는 TP all-reduce 피연산자 하나보다 nh/nkvn_h / n_{kv}배 작다.

이 통신 차이 때문에 Yang et al.(Meta)은 노드 안은 TP8, 노드 사이는 CP를 쓰고, 그들의 장비에서 2노드 CP2와 TP16의 지연 차이가 약 15%, 8노드에서는 약 100%로 벌어진다고 보고한다.

Ring attention은 정확하다

rank rr는 query QrQ_r을 갖고, ring step ss에서 rank (r−s) mod N(r - s) \bmod N의 KV 블록을 갖는다. score 행 전체를 한 번에 보지 못하므로 FlashAttention의 online softmax 상태, 즉 현재까지의 최댓값 mm, 분모 ℓ\ell, 정규화 전 출력 aa를 유지한다. score SS와 value VbV_b를 가진 새 블록이 오면

m′=max⁡(m,max⁡jS⋅j),ℓ′=em−m′ℓ+∑jeS⋅j−m′,a′=em−m′a+∑jeS⋅j−m′Vb,j,m' = \max(m, \max_j S_{\cdot j}), \quad \ell' = e^{m - m'} \ell + \sum_j e^{S_{\cdot j} - m'}, \quad a' = e^{m - m'} a + \sum_j e^{S_{\cdot j} - m'} V_{b,j},

이고 마지막 블록 뒤의 출력은 a/ℓa/\ell이다. ∑jeSj−mVj/∑jeSj−m\sum_j e^{S_j - m} V_j / \sum_j e^{S_j - m}는 mm에도 블록 순서에도 의존하지 않으므로 결과는 softmax attention과 정확히 같다. 근사가 아니고 부동소수 순서만 바뀐다. rank rr가 블록 ss로 계산하는 동안 그 블록을 이미 r+1r+1로 보내고 블록 s+1s+1을 받고 있다.

전송은 언제 숨겨지나? rank당 n=T/Nn = T/N토큰이면 step 하나는 n×nn \times n 타일, 약 4n2nhdh4 n^2 n_h d_h FLOPs(꽉 찬 타일)를 계산하고 2n nkvdh e2 n\, n_{kv} d_h\, e바이트를 옮긴다(ee는 원소당 바이트). 전송이 계산 뒤에 숨는 조건은

4n2nhdhF≥2n nkvdh eB  ⟺  n≥nkvnh⋅eF2B\frac{4 n^2 n_h d_h}{F} \ge \frac{2 n\, n_{kv} d_h\, e}{B} \iff n \ge \frac{n_{kv}}{n_h} \cdot \frac{e F}{2B}

이다. head 128/8, bf16, F=400F = 400 TFLOP/s, B=50B = 50 GB/s이면 rank당 n≥500n \ge 500토큰이다. 긴 문맥에서 ring attention은 통신을 쉽게 숨긴다. 전송은 nn에 선형, 계산은 이차이기 때문이다. (CP 논문의 Algorithm 1도 같은 꼴, 시퀀스 전체 TT와 노드 단위 C,BC, B로 쓴 T≥NCNKVe/(2NHB)T \ge N C N_{KV} e / (2 N_H B)다.)

Causal mask가 균형을 깬다

causal attention에서 query 블록은 뒤쪽 위치의 KV 블록이 필요 없다. rank rr가 rr번째 연속 블록을 가지면 step ss에 rank r−sr - s의 블록을 받는데, r<sr < s이면 그 블록은 자기 미래라서 rank가 논다. 반면 마지막 rank는 모든 step에서 계산한다. step 시간은 가장 바쁜 rank가 정한다.

Left: the causal attention matrix cut into 2N × 2N chunks (rows = query chunks, columns = KV chunks; strips show which rank owns each chunk). A tile is coloured by the rank that computes it and filled once the KV chunk has reached that rank. Right: each ring step lasts as long as the busiest rank; grey is idle time. With contiguous sharding rank 0 only ever needs its own block and waits, while the last rank does almost everything. Switch to zigzag and every rank does the same work at every step. 왼쪽: causal attention 행렬을 2N × 2N 청크로 자른 그림(행 = query 청크, 열 = KV 청크, 띠는 각 청크를 가진 rank). 타일은 그것을 계산하는 rank의 색이고, 해당 KV 청크가 그 rank에 도착하면 채워진다. 오른쪽: ring step 하나는 가장 바쁜 rank만큼 걸리고, 회색은 노는 시간이다. 연속 샤딩에서는 rank 0이 자기 블록만 필요해 기다리고 마지막 rank가 거의 다 한다. zigzag로 바꾸면 모든 step에서 모든 rank의 일이 같아진다.

The fix is to give each rank tokens from both ends. Split the sequence into 2N2N chunks and give rank rr chunks rr and 2N−1−r2N-1-r (Yang et al. §3.5.1): every rank then has one “early” and one “late” chunk, and its causal work is the same at every step. Striped Attention (Brandon et al.) does the same with a finer stripe — each device holds tokens spread uniformly over the sequence — and reports up to 1.45× end-to-end over plain Ring Attention at 256K on A100s and TPUv4s, and 1.65× at 786K on 16 TPUv4 chips. In the figure, contiguous sharding with N = 4 runs at about 60% utilisation; zigzag at 100%.

Pass-KV or pass-Q

Nothing forces KV to be the thing that travels. In pass-Q, the KV stays put and the queries circulate; each rank returns a partial output and its log-sum-exp lse=m+log⁡ℓ\mathrm{lse} = m + \log \ell, and the owner merges the NN partials:

o=∑i=1Nelsei−lse oi,lse=log⁡∑ielsei,o = \sum_{i=1}^{N} e^{\mathrm{lse}_i - \mathrm{lse}} \, o_i, \qquad \mathrm{lse} = \log \sum_i e^{\mathrm{lse}_i},

which is the same online-softmax identity, applied once at the end (an all-to-all). Which one to ship depends on sizes. Per layer, the KV of T+PT + P tokens (PP = cached prefix) is 2(T+P) nkvdh2 (T+P)\, n_{kv} d_h elements; the queries of the TT new tokens are T nhdhT\, n_h d_h. Pass-Q sends less when

TT+P≤2 nkvnh,\frac{T}{T + P} \le \frac{2\, n_{kv}}{n_h} ,

i.e. when the KV-cache miss rate is low. With Llama3 405B’s 128 query and 8 KV heads the threshold is 12.5%: a full prefill (miss = 100%) ships KV 8× smaller than Q and uses pass-KV; a multi-turn follow-up with a long cached prefix and a short new message, and decode (one new token per sequence), use pass-Q. That is the paper’s summary: ring pass-KV for full prefill, ring pass-Q for decode and partial prefill with a high cache-hit rate. Their Appendix C refines the threshold by adding the cost of pass-Q’s final all-to-all, which the figure below also includes.

해법은 각 rank에 양쪽 끝의 토큰을 주는 것이다. 시퀀스를 2N2N개 청크로 나누고 rank rr에 청크 rr와 2N−1−r2N-1-r를 준다(Yang et al. §3.5.1). 그러면 모든 rank가 “앞쪽” 청크와 “뒤쪽” 청크를 하나씩 갖게 되어 step마다 causal 계산량이 같아진다. Striped Attention(Brandon et al.)은 같은 일을 더 잘게 한다. 각 장치가 시퀀스 전체에 고르게 퍼진 토큰을 갖는다. A100과 TPUv4에서 256K에 원래 Ring Attention 대비 최대 1.45배, TPUv4 16장에서 786K에 1.65배를 보고한다. 그림에서 N = 4의 연속 샤딩은 활용률이 약 60%이고 zigzag는 100%다.

Pass-KV냐 pass-Q냐

꼭 KV가 이동할 필요는 없다. pass-Q에서는 KV가 제자리에 있고 query가 돈다. 각 rank는 부분 출력과 그 log-sum-exp lse=m+log⁡ℓ\mathrm{lse} = m + \log \ell를 돌려주고, 주인 rank가 NN개의 부분을 합친다.

o=∑i=1Nelsei−lse oi,lse=log⁡∑ielseio = \sum_{i=1}^{N} e^{\mathrm{lse}_i - \mathrm{lse}} \, o_i, \qquad \mathrm{lse} = \log \sum_i e^{\mathrm{lse}_i}

같은 online softmax 항등식을 끝에서 한 번(all-to-all) 적용한 것이다. 무엇을 보낼지는 크기가 정한다. 층마다 T+PT + P토큰(PP = 캐시된 prefix)의 KV는 2(T+P) nkvdh2 (T+P)\, n_{kv} d_h개 원소, 새 토큰 TT개의 query는 T nhdhT\, n_h d_h개다. pass-Q가 덜 보내는 조건은

TT+P≤2 nkvnh\frac{T}{T + P} \le \frac{2\, n_{kv}}{n_h}

즉 KV cache miss 비율이 낮을 때다. Llama3 405B의 query head 128, KV head 8이면 기준은 12.5%다. full prefill(miss = 100%)은 Q보다 8배 작은 KV를 보내는 pass-KV를 쓰고, 캐시된 긴 prefix에 짧은 새 메시지가 붙는 멀티턴 후속 요청과 decode(시퀀스마다 새 토큰 하나)는 pass-Q를 쓴다. 논문의 요약 그대로다. full prefill에는 ring pass-KV, decode와 캐시 적중률이 높은 partial prefill에는 ring pass-Q. 부록 C는 pass-Q 마지막 all-to-all의 비용을 더해 기준을 다듬는데, 아래 그림도 그것을 포함한다.

One attention layer, total time vs the share of new (uncached) tokens T/(T+P). Grey: pure compute split over N ranks (the floor). Blue: pass-KV, each step ships a rank's K and V of the whole context. Red: pass-Q, each step ships the new queries, plus a final all-to-all of partial outputs. Where a curve leaves the grey line, communication is exposed. Full prefill (miss = 100%) favours pass-KV because KV is NH/(2NKV) = 8× smaller than Q; slide miss down (a long cached prefix, a few new tokens: multi-turn or decode) and pass-Q wins. The dashed line is the paper's rule T/(T+P) = 2NKV/NH. Lower the bandwidth to make the gap visible. Hardware values are illustrative. attention 층 하나의 총 시간을 새(캐시되지 않은) 토큰 비율 T/(T+P)에 대해 그렸다. 회색: 순수 계산을 N rank로 나눈 값(하한). 파랑: pass-KV, step마다 한 rank가 가진 전체 문맥의 K·V를 보낸다. 빨강: pass-Q, step마다 새 query를 보내고 마지막에 부분 출력을 all-to-all로 모은다. 곡선이 회색에서 떨어지는 곳은 통신이 드러난 것이다. full prefill(miss = 100%)에서는 KV가 Q보다 NH/(2NKV) = 8배 작아 pass-KV가 유리하다. miss를 낮추면(긴 캐시 prefix에 새 토큰 몇 개: 멀티턴이나 decode) pass-Q가 이긴다. 점선은 논문의 규칙 T/(T+P) = 2NKV/NH. 대역폭을 낮추면 차이가 잘 보인다. 하드웨어 값은 예시다.

Things to check:

  1. Defaults (128K, full prefill, 4 ranks, 100 GB/s): pass-KV sits on the grey floor while pass-Q is above it — Q is 8× bigger than KV, and pass-Q’s final all-to-all of partial outputs is not hidden. Raise the bandwidth to ~400 GB/s and pass-KV’s lead shrinks; at long context a ring hides its own transfers easily.
  2. Slide the miss rate down to a few percent: the compute shrinks (few new queries), pass-KV still ships the whole context’s KV every step and becomes exposed (the flat blue segment), while pass-Q’s messages shrink with TT. The curves cross somewhat left of the dashed 12.5% line because the all-to-all is charged to pass-Q — the correction of the paper’s Appendix C.
  3. Set NH/NKVN_H/N_{KV} to 1 (MHA): the threshold moves to 200% — pass-Q always ships less. With GQA16 it is 12.5%. The choice is a property of the attention architecture as much as of the workload.

The paper’s measurements show the other side of CP. Prefill latency falls nearly linearly (1M tokens in 77 s on 16 nodes, 93% parallel efficiency, ≈ 63% FLOPS utilisation; 128K in 3.8 s), but decode gets slower: at 128K and batch 1, CP2+TP8 halves TTFT (42,010 → 21,042 ms) and raises the time per output token from 46.26 to 60.23 ms, because each decode step now adds a ring of tiny transfers and an all-to-all to a step that was already latency-bound. Their suggested mitigation is to disaggregate prefill and decode (batching & scheduling): run long prefills on a CP group, ship the KV, and decode elsewhere.

Training-side relatives: Ulysses, dynamic CP, tiled MLP

The trainer that consumes long rollouts faces the same sequence axis, with backward passes on top; three tools are worth knowing by name (depth in training parallelism).

DeepSpeed-Ulysses (Jacobs et al.) also shards along the sequence but swaps the ring for two all-to-alls: before attention, Q, K and V are regrouped so that “each GPU receives the full sequence but only for a non-overlapping subset of the attention heads”; after attention a second all-to-all returns to sequence sharding. Each GPU then runs ordinary full attention on its heads.

Ring / pass-KV CPUlysses
What movesKV blocks around a ring, N−1N-1 steps, overlapped with computeQ, K, V all-to-all before attention, output all-to-all after
Volumeeach rank receives the other ranks’ KV: ≈2Tnkvdh\approx 2 T n_{kv} d_h elements per layer, grows with TT4Nh/P4Nh/P per link (NN sequence length, hh hidden, PP GPUs): constant when sequence and GPUs grow together
Degree limitnone from the modelat most the number of query heads; with GQA, KV heads are replicated when fewer than the degree (ALST §3.2.1)
Attention kernelblockwise with online-softmax mergeunchanged full attention per head

The paper reports training 2.5× faster with 4× longer sequences than the prior state of the art. The head limit is why ring-style CP is still needed at very large degrees.

Dynamic context parallelism. RL batches mix 1K- and 100K-token trajectories. With one fixed CP size, chosen for the longest sequence, short sequences are over-sharded and their communication is exposed, and packed micro-batches of equal token count still differ in quadratic attention cost. NVIDIA’s Dynamic-CP in Megatron Core picks the CP size per micro-batch with a cost model, solver and simulator, and reports 1.48× (GitHub data) and 1.25× (CommonCrawl) over pure packing for Llama 13B, and over 35% end to end in a multi-thousand-GPU setting (NVIDIA blog, Jan 2026).

Tiled MLP and tiled loss. Everything but attention is token-local, so it can run over sequence tiles — the training analogue of chunked prefill. Arctic Long Sequence Training (Bekman et al.) tiles the MLP into ⌈T/d⌉\lceil T/d \rceil shards (63 for TT = 256,000 and hidden 4096), reporting about 10× memory saved for one Llama MLP layer, and tiles the logits/loss, since one FP32 copy of the logits of 16K tokens over a 128,256-token vocabulary is already ≈ 7.65 GiB. Combined with Ulysses, it trains Llama 8B at 500K tokens on one H100, 3.7M on one 8×H100 node and over 15M on four nodes.

Implementation: ring attention equals full attention

The block below simulates N=4N = 4 CP ranks in one process. Pass-KV with contiguous and zigzag sharding, and pass-Q with an LSE merge, must all reproduce causal softmax attention to machine precision; it also counts per-rank work to show the imbalance.

NumPy Ring attention (pass-KV and pass-Q) vs full causal attention
import numpy as np

rng = np.random.default_rng(0)
T, d, N = 64, 16, 4                 # sequence length, head dim, CP ranks
q = rng.standard_normal((T, d))
k = rng.standard_normal((T, d))
v = rng.standard_normal((T, d))
scale = 1 / np.sqrt(d)

def full_attention(q, k, v):
    s = q @ k.T * scale
    s[np.triu_indices(len(q), 1)] = -np.inf           # causal mask
    p = np.exp(s - s.max(1, keepdims=True))
    return (p / p.sum(1, keepdims=True)) @ v

ref = full_attention(q, k, v)

C = T // (2 * N)                                     # 2N chunks of C tokens
def shard_positions(r, zigzag=True):
    chunks = [r, 2 * N - 1 - r] if zigzag else [2 * r, 2 * r + 1]
    return np.concatenate([np.arange(c * C, (c + 1) * C) for c in chunks])

def ring_pass_kv(zigzag=True):
    pos = [shard_positions(r, zigzag) for r in range(N)]
    out = np.zeros_like(q)
    work = np.zeros((N, N))                          # (rank, step) → unmasked score entries
    for r in range(N):                               # in reality all ranks run concurrently
        qp = pos[r]
        m = np.full(len(qp), -np.inf)               # running max
        l = np.zeros(len(qp))                       # running denominator
        acc = np.zeros((len(qp), d))                # running numerator
        for step in range(N):
            kp = pos[(r - step) % N]                 # KV block that arrived at this step
            mask = kp[None, :] <= qp[:, None]        # causal mask in GLOBAL positions
            work[r, step] = mask.sum()
            if not mask.any():
                continue                             # block lies entirely in the future
            s = np.where(mask, q[qp] @ k[kp].T * scale, -np.inf)
            m_new = np.maximum(m, s.max(1))
            m_safe = np.where(np.isinf(m_new), 0.0, m_new)
            p = np.exp(s - m_safe[:, None])
            corr = np.exp(np.where(np.isinf(m), -np.inf, m - m_safe))
            l = l * corr + p.sum(1)
            acc = acc * corr[:, None] + p @ v[kp]
            m = m_new
        out[qp] = acc / l[:, None]
    return out, work

for zz in (False, True):
    o, work = ring_pass_kv(zz)
    eff = work.sum() / (N * work.max(0).sum())       # each step waits for the busiest rank
    name = "zigzag    " if zz else "contiguous"
    print(f"pass-KV {name}: max|err| = {np.abs(o - ref).max():.1e}   "
          f"work per rank = {work.sum(1).astype(int)}   utilisation = {eff:.0%}")

# pass-Q: queries travel; each rank returns (partial output, log-sum-exp); the owner merges
def partial(qp, kp):
    s = np.where(kp[None, :] <= qp[:, None], q[qp] @ k[kp].T * scale, -np.inf)
    mx = s.max(1)
    ok = np.isfinite(mx)                             # rows with at least one visible key
    mx = np.where(ok, mx, 0.0)
    p = np.exp(s - mx[:, None])
    den = np.where(ok, p.sum(1), 1.0)
    o = np.where(ok[:, None], (p @ v[kp]) / den[:, None], 0.0)
    return o, np.where(ok, mx + np.log(den), -np.inf)

pos = [shard_positions(r) for r in range(N)]
out_q = np.zeros_like(q)
for r in range(N):
    parts = [partial(pos[r], pos[src]) for src in range(N)]
    lses = np.stack([lse for _, lse in parts])       # (N, n_local)
    w = np.exp(lses - np.logaddexp.reduce(lses, axis=0))   # each partial's share of the mass
    out_q[pos[r]] = sum(w[i][:, None] * parts[i][0] for i in range(N))
print(f"pass-Q  zigzag    : max|err| = {np.abs(out_q - ref).max():.1e}")
 

The error is at the level of float64 rounding (≈ 10−1610^{-16}) for all three, and the per-rank work is [136 392 648 904] for contiguous sharding versus four equal 520s for zigzag. Below is the same pass-KV loop with real point-to-point communication, for local use.

PyTorch PyTorch: causal ring attention with torch.distributed (contiguous sharding) 로컬에서 실행run locally (pip install torch)
# run: torchrun --nproc_per_node=4 ring_attn.py   (gloo on CPU; use nccl + one GPU per rank on GPUs)
import torch
import torch.distributed as dist

@torch.no_grad()
def ring_attention(q, k, v):
    """q, k, v: (heads, n_local, d), rank r holds positions [r*n, (r+1)*n). Returns causal attention output."""
    rank, world = dist.get_rank(), dist.get_world_size()
    H, n, d = q.shape
    scale = d ** -0.5
    m = torch.full((H, n), float("-inf"), device=q.device)   # running max (fp32)
    l = torch.zeros((H, n), device=q.device)                  # running denominator
    acc = torch.zeros((H, n, d), device=q.device)             # running numerator
    kv = torch.stack([k, v]).contiguous()                     # one buffer → one message per step
    diag = torch.ones(n, n, dtype=torch.bool, device=q.device).tril()
    for step in range(world):
        if step < world - 1:                                  # send the current block on while we compute
            nxt = torch.empty_like(kv)
            reqs = dist.batch_isend_irecv([
                dist.P2POp(dist.isend, kv, (rank + 1) % world),
                dist.P2POp(dist.irecv, nxt, (rank - 1) % world)])
        src = (rank - step) % world                           # owner of the block we now hold
        if src <= rank:                                       # later blocks are fully masked: skip
            s = torch.einsum("hqd,hkd->hqk", q.float(), kv[0].float()) * scale
            if src == rank:
                s = s.masked_fill(~diag, float("-inf"))
            m_new = torch.maximum(m, s.amax(-1))
            p = torch.exp(s - m_new[..., None])
            corr = torch.exp(m - m_new)                       # exp(-inf) = 0 on the first block
            l = l * corr + p.sum(-1)
            acc = acc * corr[..., None] + torch.einsum("hqk,hkd->hqd", p, kv[1].float())
            m = m_new
        if step < world - 1:
            for req in reqs:
                req.wait()
            kv = nxt
    return (acc / l[..., None]).to(q.dtype)

if __name__ == "__main__":
    dist.init_process_group("gloo")
    torch.manual_seed(0)                                      # identical full tensors on every rank
    H, T, d = 4, 256, 32
    Q, K, V = (torch.randn(H, T, d) for _ in range(3))
    r, w = dist.get_rank(), dist.get_world_size()
    sl = slice(r * T // w, (r + 1) * T // w)
    out = ring_attention(Q[:, sl], K[:, sl], V[:, sl])
    ref = torch.nn.functional.scaled_dot_product_attention(Q, K, V, is_causal=True)[:, sl]
    print(f"rank {r}: max|err| = {(out - ref).abs().max().item():.2e}")
    dist.destroy_process_group()
 

확인할 것:

  1. 기본값(128K, full prefill, rank 4개, 100 GB/s)에서 pass-KV는 회색 하한 위에 놓이고 pass-Q는 그보다 위에 있다. Q가 KV보다 8배 크고, pass-Q 마지막의 부분 출력 all-to-all은 숨겨지지 않는다. 대역폭을 약 400 GB/s로 올리면 pass-KV의 우위가 줄어든다. 긴 문맥에서 ring은 자기 전송을 쉽게 숨긴다.
  2. miss 비율을 몇 %로 내려 보라. 새 query가 적어 계산이 줄어드는데, pass-KV는 여전히 step마다 문맥 전체의 KV를 보내 통신이 드러나고(평평한 파란 구간), pass-Q의 메시지는 TT와 함께 줄어든다. 두 곡선은 점선 12.5%보다 조금 왼쪽에서 교차하는데, all-to-all을 pass-Q에 매겼기 때문이다. 논문 부록 C의 보정이 이것이다.
  3. NH/NKVN_H/N_{KV}를 1(MHA)로 두면 기준이 200%로 옮겨 가 pass-Q가 항상 덜 보낸다. GQA16이면 12.5%다. 선택은 workload만큼이나 attention 아키텍처의 성질이다.

논문의 측정은 CP의 다른 면도 보여 준다. prefill 지연은 거의 선형으로 줄어든다(16노드에서 1M 토큰 77초, 병렬 효율 93%, FLOPS 활용률 약 63%, 128K는 3.8초). 그러나 decode는 느려진다. 128K, 배치 1에서 CP2+TP8은 TTFT를 반으로 줄이지만(42,010 → 21,042 ms) 출력 토큰당 시간은 46.26에서 60.23 ms로 늘어난다. 이미 지연에 묶인 decode step 하나하나에 작은 전송의 링과 all-to-all이 더해지기 때문이다. 논문이 제안하는 완화책은 prefill과 decode의 분리다(배칭과 스케줄링). 긴 prefill은 CP 그룹에서 돌리고, KV를 넘기고, decode는 다른 곳에서 한다.

학습 쪽의 친척들: Ulysses, dynamic CP, tiled MLP

긴 rollout을 받아 학습하는 쪽도 같은 시퀀스 축을 마주하고, 거기에 backward가 더해진다. 이름 정도는 알아 둘 도구가 셋 있다(깊은 내용은 학습 병렬화).

DeepSpeed-Ulysses(Jacobs et al.)도 시퀀스를 나누지만 ring 대신 all-to-all 두 번을 쓴다. attention 전에 Q, K, V를 재배치해 “각 GPU가 시퀀스 전체를 받되 서로 겹치지 않는 attention head 일부만” 갖게 하고, attention 뒤 두 번째 all-to-all로 시퀀스 샤딩으로 돌아간다. 각 GPU는 자기 head들에 대해 보통의 full attention을 돌린다.

Ring / pass-KV CPUlysses
무엇이 이동하나KV 블록이 링을 N−1N-1 step 돌며 계산과 겹침attention 전 Q, K, V all-to-all, 후 출력 all-to-all
통신량각 rank가 다른 rank의 KV를 받음: 층마다 약 2Tnkvdh2 T n_{kv} d_h 원소, TT와 함께 증가링크당 4Nh/P4Nh/P(NN 시퀀스 길이, hh hidden, PP GPU 수): 시퀀스와 GPU를 함께 늘리면 일정
병렬도 한계모델에서 오는 한계 없음query head 수 이하. GQA에서 KV head가 병렬도보다 적으면 복제(ALST §3.2.1)
attention 커널online softmax 병합을 쓰는 blockwisehead별 full attention 그대로

논문은 기존 최고 방법보다 4배 긴 시퀀스를 2.5배 빠르게 학습한다고 보고한다. head 수 한계 때문에 아주 큰 병렬도에서는 여전히 ring 방식 CP가 필요하다.

Dynamic context parallelism. RL 배치에는 1K토큰과 100K토큰 궤적이 섞인다. 가장 긴 시퀀스에 맞춘 고정 CP 크기 하나를 쓰면 짧은 시퀀스는 지나치게 쪼개져 통신이 드러나고, 토큰 수가 같은 packed micro-batch끼리도 이차인 attention 비용은 다르다. Megatron Core의 NVIDIA Dynamic-CP는 비용 모델·solver·simulator로 micro-batch마다 CP 크기를 고르며, Llama 13B에서 순수 packing 대비 1.48배(GitHub 데이터), 1.25배(CommonCrawl), 수천 GPU 환경에서 end-to-end 35% 이상의 향상을 보고한다(NVIDIA 블로그, 2026년 1월).

Tiled MLP와 tiled loss. attention을 뺀 모든 것은 토큰별로 독립이라 시퀀스 타일 단위로 돌릴 수 있다. chunked prefill의 학습판이다. Arctic Long Sequence Training(Bekman et al.)은 MLP를 ⌈T/d⌉\lceil T/d \rceil개 조각으로 나누고(TT = 256,000, hidden 4096이면 63개) Llama MLP 층 하나에서 메모리를 약 10배 아꼈다고 보고하며, logits/loss도 타일로 나눈다. 128,256개 어휘에 대한 16K토큰의 logits는 FP32 한 벌만으로 약 7.65 GiB이기 때문이다. Ulysses와 합쳐 Llama 8B를 H100 한 장에서 500K토큰, 8×H100 노드 하나에서 3.7M, 노드 넷에서 15M 넘게 학습한다.

구현: ring attention은 full attention과 같다

아래 블록은 프로세스 하나에서 CP rank N=4N = 4개를 흉내 낸다. 연속·zigzag 샤딩의 pass-KV, LSE 병합의 pass-Q가 모두 causal softmax attention을 기계 정밀도로 재현해야 하고, rank별 일의 양을 세어 불균형도 보여 준다.

NumPy Ring attention(pass-KV, pass-Q)과 full causal attention 비교
import numpy as np

rng = np.random.default_rng(0)
T, d, N = 64, 16, 4                 # 시퀀스 길이, head 차원, CP rank 수
q = rng.standard_normal((T, d))
k = rng.standard_normal((T, d))
v = rng.standard_normal((T, d))
scale = 1 / np.sqrt(d)

def full_attention(q, k, v):
    s = q @ k.T * scale
    s[np.triu_indices(len(q), 1)] = -np.inf           # causal mask
    p = np.exp(s - s.max(1, keepdims=True))
    return (p / p.sum(1, keepdims=True)) @ v

ref = full_attention(q, k, v)

C = T // (2 * N)                                     # C토큰짜리 청크 2N개
def shard_positions(r, zigzag=True):
    chunks = [r, 2 * N - 1 - r] if zigzag else [2 * r, 2 * r + 1]
    return np.concatenate([np.arange(c * C, (c + 1) * C) for c in chunks])

def ring_pass_kv(zigzag=True):
    pos = [shard_positions(r, zigzag) for r in range(N)]
    out = np.zeros_like(q)
    work = np.zeros((N, N))                          # (rank, step) → mask되지 않은 score 개수
    for r in range(N):                               # 실제로는 모든 rank가 동시에 돈다
        qp = pos[r]
        m = np.full(len(qp), -np.inf)               # 현재까지의 최댓값
        l = np.zeros(len(qp))                       # 현재까지의 분모
        acc = np.zeros((len(qp), d))                # 현재까지의 분자
        for step in range(N):
            kp = pos[(r - step) % N]                 # 이번 step에 도착한 KV 블록
            mask = kp[None, :] <= qp[:, None]        # 전역 위치 기준 causal mask
            work[r, step] = mask.sum()
            if not mask.any():
                continue                             # 블록 전체가 미래에 있음
            s = np.where(mask, q[qp] @ k[kp].T * scale, -np.inf)
            m_new = np.maximum(m, s.max(1))
            m_safe = np.where(np.isinf(m_new), 0.0, m_new)
            p = np.exp(s - m_safe[:, None])
            corr = np.exp(np.where(np.isinf(m), -np.inf, m - m_safe))
            l = l * corr + p.sum(1)
            acc = acc * corr[:, None] + p @ v[kp]
            m = m_new
        out[qp] = acc / l[:, None]
    return out, work

for zz in (False, True):
    o, work = ring_pass_kv(zz)
    eff = work.sum() / (N * work.max(0).sum())       # step마다 가장 바쁜 rank를 기다린다
    name = "zigzag    " if zz else "contiguous"
    print(f"pass-KV {name}: max|err| = {np.abs(o - ref).max():.1e}   "
          f"rank별 일 = {work.sum(1).astype(int)}   활용률 = {eff:.0%}")

# pass-Q: query가 이동하고, 각 rank는 (부분 출력, log-sum-exp)를 돌려주며, 주인 rank가 합친다
def partial(qp, kp):
    s = np.where(kp[None, :] <= qp[:, None], q[qp] @ k[kp].T * scale, -np.inf)
    mx = s.max(1)
    ok = np.isfinite(mx)                             # 보이는 key가 하나라도 있는 행
    mx = np.where(ok, mx, 0.0)
    p = np.exp(s - mx[:, None])
    den = np.where(ok, p.sum(1), 1.0)
    o = np.where(ok[:, None], (p @ v[kp]) / den[:, None], 0.0)
    return o, np.where(ok, mx + np.log(den), -np.inf)

pos = [shard_positions(r) for r in range(N)]
out_q = np.zeros_like(q)
for r in range(N):
    parts = [partial(pos[r], pos[src]) for src in range(N)]
    lses = np.stack([lse for _, lse in parts])       # (N, n_local)
    w = np.exp(lses - np.logaddexp.reduce(lses, axis=0))   # 각 부분이 차지하는 softmax 질량
    out_q[pos[r]] = sum(w[i][:, None] * parts[i][0] for i in range(N))
print(f"pass-Q  zigzag    : max|err| = {np.abs(out_q - ref).max():.1e}")
 

세 경우 모두 오차는 float64 반올림 수준(약 10−1610^{-16})이고, rank별 일의 양은 연속 샤딩에서 [136 392 648 904], zigzag에서 520 네 개로 같다. 아래는 같은 pass-KV 루프를 실제 point-to-point 통신으로 쓴 것이다(로컬 실행용).

PyTorch PyTorch: torch.distributed로 쓴 causal ring attention (연속 샤딩) 로컬에서 실행run locally (pip install torch)
# 실행: torchrun --nproc_per_node=4 ring_attn.py   (CPU는 gloo, GPU에서는 nccl + rank당 GPU 1장)
import torch
import torch.distributed as dist

@torch.no_grad()
def ring_attention(q, k, v):
    """q, k, v: (heads, n_local, d), rank r는 위치 [r*n, (r+1)*n)을 가진다. causal attention 출력을 돌려준다."""
    rank, world = dist.get_rank(), dist.get_world_size()
    H, n, d = q.shape
    scale = d ** -0.5
    m = torch.full((H, n), float("-inf"), device=q.device)   # 현재까지의 최댓값 (fp32)
    l = torch.zeros((H, n), device=q.device)                  # 현재까지의 분모
    acc = torch.zeros((H, n, d), device=q.device)             # 현재까지의 분자
    kv = torch.stack([k, v]).contiguous()                     # 버퍼 하나 → step당 메시지 하나
    diag = torch.ones(n, n, dtype=torch.bool, device=q.device).tril()
    for step in range(world):
        if step < world - 1:                                  # 계산하는 동안 현재 블록을 넘긴다
            nxt = torch.empty_like(kv)
            reqs = dist.batch_isend_irecv([
                dist.P2POp(dist.isend, kv, (rank + 1) % world),
                dist.P2POp(dist.irecv, nxt, (rank - 1) % world)])
        src = (rank - step) % world                           # 지금 가진 블록의 주인
        if src <= rank:                                       # 뒤쪽 블록은 전부 mask: 건너뜀
            s = torch.einsum("hqd,hkd->hqk", q.float(), kv[0].float()) * scale
            if src == rank:
                s = s.masked_fill(~diag, float("-inf"))
            m_new = torch.maximum(m, s.amax(-1))
            p = torch.exp(s - m_new[..., None])
            corr = torch.exp(m - m_new)                       # 첫 블록에서는 exp(-inf) = 0
            l = l * corr + p.sum(-1)
            acc = acc * corr[..., None] + torch.einsum("hqk,hkd->hqd", p, kv[1].float())
            m = m_new
        if step < world - 1:
            for req in reqs:
                req.wait()
            kv = nxt
    return (acc / l[..., None]).to(q.dtype)

if __name__ == "__main__":
    dist.init_process_group("gloo")
    torch.manual_seed(0)                                      # 모든 rank에서 같은 전체 텐서
    H, T, d = 4, 256, 32
    Q, K, V = (torch.randn(H, T, d) for _ in range(3))
    r, w = dist.get_rank(), dist.get_world_size()
    sl = slice(r * T // w, (r + 1) * T // w)
    out = ring_attention(Q[:, sl], K[:, sl], V[:, sl])
    ref = torch.nn.functional.scaled_dot_product_attention(Q, K, V, is_causal=True)[:, sl]
    print(f"rank {r}: max|err| = {(out - ref).abs().max().item():.2e}")
    dist.destroy_process_group()
 

Serving sparse, windowed and linear attention

The architectures that shrink the three costs each move the problem somewhere else in the serving stack.

DSA (top-kk sparse attention). Storage is unchanged — every token’s MLA latent stays in the cache — so memory and prefix caching behave like MLA. What changes is the access pattern. Each query first runs the lightning indexer over all previous tokens (64×12864 \times 128 multiply-adds per pair in FP8, vs 128×(576+512)128 \times (576 + 512) for MLA’s main attention, ≈ 17× cheaper by the V3.2 lesson’s count), then gathers 2,048 scattered entries. So (1) the remaining O(T)O(T) term is the indexer, which at 1M dominates what is left — the reason V4 runs its indexer in FP4 over 4×-compressed entries; and (2) the main kernel is a gather over the paged cache rather than a streaming read, so token-granular addressing and gather bandwidth matter more than for dense attention. For RL there is one more catch: if training and inference select different top-kk sets, they compute different functions (GLM-5 switched to a deterministic top-kk for this reason; see inference for RL).

Sliding windows. A window layer keeps a ring buffer of its last ww tokens: constant memory, but a prefix cache becomes awkward. To resume from a cached prefix of length PP, a window layer needs exactly the KV of tokens P−w..PP-w..P, which a cache that stores full-attention KV per page does not naturally hold. The V4 report lists three strategies for its 128-token SWA KV on disk — store it all, store periodic checkpoints, or store none and recompute the last nwinn_{\text{win}} tokens through the layers (V4 §3.5.2) — and notes SWA KV is about 8× larger on disk than the compressed entries. V4.1 stopped writing SWA KV to SSD at all and keeps it in host memory with a short TTL, recomputing on a miss (V4 lesson).

Linear attention and SSM layers. A Gated DeltaNet or Mamba-2 layer has a fixed-size state StS_t that is overwritten at every token. This makes the long-context cost flat but breaks two things that KV caches get for free:

  • Prefix caching. With KV you can resume at any page boundary by truncating. With a state you can only resume where a snapshot was saved; Nemotron 3 Ultra snapshots the SSM state at fixed token intervals to implement prefix caching (report §5.1).
  • Speculative decoding. Rejecting draft tokens means rolling back. KV just truncates; the state has no past, so Ultra snapshots the state at every draft step (speculative decoding).

Snapshots cost memory: one Qwen3-Next GDN layer’s FP32 state is worth about 1K tokens of KV of one of its full-attention layers (Qwen3-Next lesson), so a snapshot every 1K tokens doubles the effective footprint of those layers. And prefill uses a chunkwise-parallel kernel while decode uses the recurrent form; they are mathematically equal but numerically different, a new source of train–inference mismatch.

KV compression and offload

When the architecture is fixed, the KV can still be made smaller or moved.

Quantisation (FP8 or lower) shrinks every entry; see KV cache and quantisation. Eviction keeps only some entries. StreamingLLM (Xiao et al., ICLR 2024) keeps the first few “sink” tokens plus a recent window and runs stable language modelling over 4M+ tokens, up to 22.2× faster than recomputing a sliding window. SnapKV (Li et al.) uses an observation window at the end of the prompt to choose, per head, which positions to keep, and reports 3.6× faster generation and 8.2× better memory efficiency at 16K, and up to 380K tokens on one A100-80GB. Both are lossy and query-dependent: a token evicted now cannot be recovered when a later turn needs it, which is exactly the access pattern of a long agent trajectory that re-reads an old file. Architectural compression (MLA, CSA/HCA) is trained in; eviction is applied after the fact.

Offload keeps everything but moves it down the hierarchy: HBM → host DRAM → local or distributed SSD. Whether reloading a cached prefix beats recomputing it is a one-line roofline. Recomputing PP tokens costs at least 2NP2NP FLOPs (ignore attention to be conservative); reloading costs P⋅bKVP \cdot b_{\text{KV}} bytes over a link of bandwidth BB. Reload wins when

B>bKV F2N,B > \frac{b_{\text{KV}} \, F}{2N} ,

the bytes of KV per FLOP of prefill, times FLOP/s. Architectures with small KV per active parameter can be served from slow storage: at an assumed 400 TFLOP/s the break-even is ≈ 0.94 GB/s for the dense 70B-class model, ≈ 0.38 GB/s for V3’s MLA and ≈ 0.02 GB/s for V4-Pro’s compressed cache (NumPy below). That is why an on-disk KV cache is economical at all: in DeepSeek’s published 24-hour production statistics, 56.3% of 608B input tokens hit the on-disk KV cache.

Sparse·window·linear attention 서빙

세 비용을 줄이는 아키텍처들은 각각 문제를 서빙 스택의 다른 곳으로 옮긴다.

DSA(top-kk sparse attention). 저장량은 그대로다. 모든 토큰의 MLA latent가 캐시에 남으므로 메모리와 prefix caching은 MLA처럼 동작한다. 바뀌는 것은 접근 패턴이다. 각 query는 먼저 앞선 모든 토큰에 lightning indexer를 돌리고(쌍당 FP8 64×12864 \times 128 곱셈-덧셈, MLA 주 attention의 128×(576+512)128 \times (576 + 512)보다 약 17배 쌈, V3.2 레슨의 계산), 흩어진 2,048개 항목을 모은다. 따라서 (1) 남는 O(T)O(T) 항은 indexer이고 1M에서는 남은 비용의 대부분이다. V4가 indexer를 FP4로, 4배 압축된 항목 위에서 돌리는 이유다. (2) 주 커널은 연속 읽기가 아니라 paged cache 위의 gather라서, dense attention보다 토큰 단위 주소 지정과 gather 대역폭이 더 중요하다. RL에서는 하나가 더 있다. 학습과 추론이 다른 top-kk 집합을 고르면 서로 다른 함수를 계산하는 셈이다(GLM-5는 그래서 결정적 top-kk로 바꿨다. RL을 위한 추론 참고).

Sliding window. window 층은 마지막 ww토큰의 ring buffer만 갖는다. 메모리는 고정이지만 prefix cache가 어색해진다. 길이 PP의 캐시된 prefix에서 이어 가려면 window 층은 정확히 토큰 P−w..PP-w..P의 KV가 필요한데, 페이지마다 full-attention KV를 저장하는 캐시는 그것을 자연스럽게 갖고 있지 않다. V4 보고서는 128토큰 SWA KV를 디스크에 두는 세 전략을 든다. 전부 저장, 주기적 checkpoint 저장, 아무것도 저장하지 않고 마지막 nwinn_{\text{win}}토큰을 층들에 다시 통과시키기(V4 §3.5.2). 그리고 디스크에서 SWA KV가 압축 항목보다 약 8배 크다고 적는다. V4.1은 SWA KV를 아예 SSD에 쓰지 않고 짧은 TTL의 host 메모리에만 두며, miss가 나면 다시 계산한다(V4 레슨).

Linear attention과 SSM 층. Gated DeltaNet이나 Mamba-2 층은 토큰마다 덮어쓰는 고정 크기 상태 StS_t를 갖는다. 긴 문맥 비용은 평평해지지만, KV cache가 공짜로 갖던 두 가지가 깨진다.

  • Prefix caching. KV는 아무 페이지 경계에서나 잘라서 이어 갈 수 있다. 상태는 스냅샷을 저장해 둔 곳에서만 이어 갈 수 있다. Nemotron 3 Ultra는 고정 토큰 간격으로 SSM 상태를 스냅샷해 prefix caching을 구현한다(보고서 §5.1).
  • Speculative decoding. draft 토큰을 거절하면 되돌려야 한다. KV는 자르면 되지만 상태에는 과거가 없으므로, Ultra는 draft step마다 상태를 스냅샷한다(speculative decoding).

스냅샷은 메모리를 먹는다. Qwen3-Next GDN 층 하나의 FP32 상태는 full-attention 층 하나의 KV 약 1K토큰어치다(Qwen3-Next 레슨). 1K토큰마다 스냅샷하면 그 층들의 실제 점유가 두 배가 된다. 또 prefill은 chunkwise 병렬 커널, decode는 recurrent 형태를 쓴다. 수학적으로는 같지만 수치는 다르고, 학습–추론 불일치의 새 원천이 된다.

KV 압축과 offload

아키텍처가 정해져 있어도 KV를 더 작게 만들거나 옮길 수는 있다.

양자화(FP8 이하)는 모든 항목을 줄인다. KV cache와 양자화 참고. Eviction은 일부 항목만 남긴다. StreamingLLM(Xiao et al., ICLR 2024)은 처음 몇 개의 “sink” 토큰과 최근 window만 남기고 4M 토큰 이상에서 안정적으로 언어 모델링을 하며, sliding window를 다시 계산하는 방식보다 최대 22.2배 빠르다. SnapKV(Li et al.)는 프롬프트 끝의 관찰 window로 head마다 남길 위치를 골라, 16K에서 생성 3.6배, 메모리 효율 8.2배를 보고하고 A100-80GB 한 장에서 최대 380K 토큰을 처리한다. 둘 다 손실이 있고 query에 의존한다. 지금 버린 토큰은 나중 턴이 필요로 할 때 되살릴 수 없고, 오래된 파일을 다시 읽는 긴 agent 궤적이 바로 그런 접근 패턴이다. 아키텍처 압축(MLA, CSA/HCA)은 학습으로 들어가 있고, eviction은 사후에 적용된다.

Offload는 전부 남기되 계층 아래로 옮긴다. HBM → host DRAM → 로컬 또는 분산 SSD. 캐시된 prefix를 다시 읽어 오는 것이 다시 계산하는 것보다 나은지는 한 줄짜리 roofline이다. PP토큰을 다시 계산하는 데는 적어도 2NP2NP FLOPs가 들고(보수적으로 attention은 무시), 다시 읽는 데는 대역폭 BB의 링크로 P⋅bKVP \cdot b_{\text{KV}}바이트가 든다. 다시 읽기가 이기는 조건은

B>bKV F2NB > \frac{b_{\text{KV}} \, F}{2N}

즉 prefill FLOP당 KV 바이트에 FLOP/s를 곱한 값이다. 활성 파라미터당 KV가 작은 아키텍처는 느린 저장소에서 서빙할 수 있다. 가정한 400 TFLOP/s에서 손익분기는 70B급 dense 모델이 약 0.94 GB/s, V3의 MLA가 약 0.38 GB/s, V4-Pro의 압축 캐시가 약 0.02 GB/s다(아래 NumPy). 디스크 KV cache가 애초에 경제적인 이유가 이것이다. DeepSeek이 공개한 24시간 실서비스 통계에서 입력 토큰 608B의 56.3%가 디스크 KV cache에 적중했다.

NumPy Chunked prefill = one-shot prefill; 1M-token FLOPs; reload-vs-recompute break-even
import numpy as np

# A 2-layer toy decoder (attention + MLP, residual). Chunked prefill with a per-layer KV cache
# must give the same hidden states as a one-shot prefill, because attention is causal.
rng = np.random.default_rng(1)
T, D = 96, 32
x0 = rng.standard_normal((T, D))
W = [dict(q=rng.standard_normal((D, D)) / np.sqrt(D), k=rng.standard_normal((D, D)) / np.sqrt(D),
          v=rng.standard_normal((D, D)) / np.sqrt(D), up=rng.standard_normal((D, 4 * D)) / np.sqrt(D),
          dn=rng.standard_normal((4 * D, D)) / np.sqrt(4 * D)) for _ in range(2)]

def layer(h, w, cache, start):
    """h: (c, D) new tokens at positions start..start+c-1; cache holds K, V of earlier tokens."""
    q, k, v = h @ w["q"], h @ w["k"], h @ w["v"]
    cache["K"] = np.vstack([cache["K"], k]); cache["V"] = np.vstack([cache["V"], v])
    K, V = cache["K"], cache["V"]
    qpos = start + np.arange(len(h))[:, None]
    s = np.where(np.arange(len(K))[None, :] <= qpos, q @ K.T / np.sqrt(D), -np.inf)
    p = np.exp(s - s.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
    h = h + p @ V
    return h + np.maximum(h @ w["up"], 0) @ w["dn"]

def prefill(x, chunk):
    caches = [dict(K=np.zeros((0, D)), V=np.zeros((0, D))) for _ in W]
    outs = []
    for start in range(0, len(x), chunk):
        h = x[start:start + chunk]
        for w, c in zip(W, caches):
            h = layer(h, w, c, start)
        outs.append(h)
    return np.vstack(outs)

one_shot = prefill(x0, T)
for chunk in (7, 16, 32):
    print(f"chunk={chunk:>2}: max|chunked - one-shot| = {np.abs(prefill(x0, chunk) - one_shot).max():.1e}")

# Chunked prefill of 1M tokens, 70B-class dense GQA (80 layers, 64 query heads x 128)
N_par, L, d_attn = 70e9, 80, 64 * 128
Tm, Cm = 2**20, 8192
starts = np.arange(0, Tm, Cm, dtype=np.float64)       # float: int32 would overflow in Pyodide
attn = 4 * L * d_attn * (Cm * starts + Cm * (Cm + 1) / 2)   # attention FLOPs of each chunk
lin = 2 * N_par * Cm
print(f"\n1M-token prefill in {len(starts)} chunks of {Cm}:")
print(f"  first chunk {(attn[0] + lin) / 1e15:5.2f} PFLOP, last chunk {(attn[-1] + lin) / 1e15:5.2f} PFLOP "
      f"(attention share {attn[-1] / (attn[-1] + lin):.0%})")
tot = attn.sum() + lin * len(starts)
one = 4 * L * d_attn * Tm * (Tm + 1) / 2 + 2 * N_par * Tm
print(f"  total {tot / 1e18:.3f} EFLOP vs one-shot {one / 1e18:.3f} EFLOP (chunking moves no FLOPs)")
print(f"  crossover T* = N / (L * d_attn) = {N_par / (L * d_attn):,.0f} tokens")

# Check against Yang et al.: Llama3 405B (126 layers, 128 heads x 128), 1e6 tokens, 77 s on 128 GPUs
F405 = 2 * 405e9 * 1e6 + 2 * 126 * (128 * 128) * 1e6**2
print(f"  Llama3-405B, 1e6 tokens: {F405:.2e} FLOPs; 77 s x 128 GPUs x 502 TFLOP/s = {77 * 128 * 502e12:.2e}")

# Reload a cached prefix or recompute it?  reload wins if  B > (KV bytes/token) * F / (2 N)
F = 400e12                                   # assumed effective FLOP/s of one GPU (illustrative)
cfg = {"dense GQA 70B-class (bf16 KV)": (327_680, 70e9), "MLA, V3 (bf16 latent)": (70_272, 37e9),
       "CSA/HCA, V4-Pro (estimate)": (4_970, 49e9)}
P = 64_000
print(f"\nprefix of {P:,} tokens — reload beats recompute above the break-even bandwidth:")
for name, (kvb, n_act) in cfg.items():
    print(f"  {name:<30} KV {kvb * P / 2**30:6.2f} GiB  recompute >= {2 * n_act * P / F:5.1f} s  "
          f"break-even = {kvb * F / (2 * n_act) / 1e9:5.2f} GB/s")
 
확인 문제Check yourself

A model has 128 query heads and 8 KV heads. A multi-turn request arrives with a 400K-token cached prefix and 20K new tokens, served with ring context parallelism. Which variant ships fewer bytes per ring step?

Per layer pass-KV moves the KV of all T+P=420T + P = 420K tokens, 2⋅420K⋅8⋅dh2 \cdot 420\text{K} \cdot 8 \cdot d_h elements; pass-Q moves the queries of T=20T = 20K new tokens, 20K⋅128⋅dh20\text{K} \cdot 128 \cdot d_h. The ratio is 2⋅420⋅820⋅128=2.6\frac{2 \cdot 420 \cdot 8}{20 \cdot 128} = 2.6, so pass-Q ships 2.6× less. Equivalently T/(T+P)≈4.8%≤2nkv/nh=12.5%T/(T+P) \approx 4.8\% \le 2 n_{kv}/n_h = 12.5\%. Pass-Q does add a final all-to-all of partial outputs, which shifts the threshold down a little (Appendix C of the CP paper), but not enough to change this case.

확인 문제Check yourself

You chunk a 1M-token prefill into 8K-token chunks instead of processing it at once. What happens to the total FLOPs and to the cost of the last chunk relative to the first?

Chunking reorders the same causal computation: every (query, key) pair with key ≤ query is still computed exactly once, so total FLOPs equal the one-shot prefill (the NumPy block prints both). Chunk jj costs 2NC+4Ldattn(C⋅jC+C2/2)2NC + 4Ld_{\text{attn}}(C \cdot jC + C^2/2), linear in jj: for the 70B-class model ≈ 1.2 PFLOP for the first chunk and ≈ 23.6 PFLOP for the last. Chunking buys bounded activation memory and interleaving with decode, not fewer FLOPs.

Summary

  • At context TT, KV storage and per-token decode reads grow as O(T)O(T) and prefill attention as O(T2)O(T^2). Attention overtakes the linear layers at T∗=N/(L dattn)T^* = N/(L\,d_{\text{attn}}) — ≈ 107K for a 70B-class dense model — and is ≈ 90% of a 1M prefill.
  • Decode’s KV read is not shared across the batch, so its arithmetic intensity is nh/nkvn_h/n_{kv} for GQA (8 for 64/8) whatever the batch; MLA’s absorbed mode raises it to ≈ 242 FLOP/byte.
  • Chunked prefill bounds activation memory and enables interleaving with decode but moves no FLOPs; the last chunk of 1M costs ~20× the first.
  • Context parallelism splits the sequence; ring attention with online-softmax merging is exact. Its transfer hides behind compute once each rank holds a few hundred to a few thousand tokens. Zigzag (2N-chunk) or striped sharding fixes the causal imbalance. Pass-KV suits full prefill, pass-Q (with an LSE all-to-all merge) suits decode and high-hit-rate partial prefill; the threshold is T/(T+P)=2nkv/nhT/(T+P) = 2n_{kv}/n_h. CP shortens TTFT but lengthens TPOT.
  • DSA keeps storage and adds an O(T)O(T) indexer scan plus a sparse gather; window and recurrent layers make memory flat but need state snapshots for prefix caching and speculative decoding.
  • Eviction (sinks + window, SnapKV) is lossy and query-dependent; offload is lossless and wins over recomputation when link bandwidth exceeds (KV bytes per token) × FLOP/s ÷ 2N2N — tiny for compressed-KV architectures.
NumPy Chunked prefill = 한 번에 하는 prefill, 1M 토큰 FLOPs, 다시 읽기 vs 다시 계산 손익분기
import numpy as np

# 2층짜리 장난감 decoder(attention + MLP, residual). 층별 KV cache를 쓰는 chunked prefill은
# attention이 causal이므로 한 번에 하는 prefill과 같은 hidden state를 내야 한다.
rng = np.random.default_rng(1)
T, D = 96, 32
x0 = rng.standard_normal((T, D))
W = [dict(q=rng.standard_normal((D, D)) / np.sqrt(D), k=rng.standard_normal((D, D)) / np.sqrt(D),
          v=rng.standard_normal((D, D)) / np.sqrt(D), up=rng.standard_normal((D, 4 * D)) / np.sqrt(D),
          dn=rng.standard_normal((4 * D, D)) / np.sqrt(4 * D)) for _ in range(2)]

def layer(h, w, cache, start):
    """h: 위치 start..start+c-1의 새 토큰 (c, D). cache에는 앞선 토큰의 K, V가 있다."""
    q, k, v = h @ w["q"], h @ w["k"], h @ w["v"]
    cache["K"] = np.vstack([cache["K"], k]); cache["V"] = np.vstack([cache["V"], v])
    K, V = cache["K"], cache["V"]
    qpos = start + np.arange(len(h))[:, None]
    s = np.where(np.arange(len(K))[None, :] <= qpos, q @ K.T / np.sqrt(D), -np.inf)
    p = np.exp(s - s.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
    h = h + p @ V
    return h + np.maximum(h @ w["up"], 0) @ w["dn"]

def prefill(x, chunk):
    caches = [dict(K=np.zeros((0, D)), V=np.zeros((0, D))) for _ in W]
    outs = []
    for start in range(0, len(x), chunk):
        h = x[start:start + chunk]
        for w, c in zip(W, caches):
            h = layer(h, w, c, start)
        outs.append(h)
    return np.vstack(outs)

one_shot = prefill(x0, T)
for chunk in (7, 16, 32):
    print(f"chunk={chunk:>2}: max|chunked - one-shot| = {np.abs(prefill(x0, chunk) - one_shot).max():.1e}")

# 70B급 dense GQA(80층, query head 64 x 128)로 1M 토큰을 chunked prefill
N_par, L, d_attn = 70e9, 80, 64 * 128
Tm, Cm = 2**20, 8192
starts = np.arange(0, Tm, Cm, dtype=np.float64)       # float: Pyodide의 int32는 넘친다
attn = 4 * L * d_attn * (Cm * starts + Cm * (Cm + 1) / 2)   # 청크별 attention FLOPs
lin = 2 * N_par * Cm
print(f"\n1M 토큰 prefill, {Cm}토큰 청크 {len(starts)}개:")
print(f"  첫 청크 {(attn[0] + lin) / 1e15:5.2f} PFLOP, 마지막 청크 {(attn[-1] + lin) / 1e15:5.2f} PFLOP "
      f"(attention 비율 {attn[-1] / (attn[-1] + lin):.0%})")
tot = attn.sum() + lin * len(starts)
one = 4 * L * d_attn * Tm * (Tm + 1) / 2 + 2 * N_par * Tm
print(f"  합계 {tot / 1e18:.3f} EFLOP vs 한 번에 {one / 1e18:.3f} EFLOP (chunking은 FLOPs를 옮기지 않는다)")
print(f"  교차점 T* = N / (L * d_attn) = {N_par / (L * d_attn):,.0f} 토큰")

# Yang et al. 검산: Llama3 405B(126층, head 128 x 128), 1e6 토큰, GPU 128장에서 77초
F405 = 2 * 405e9 * 1e6 + 2 * 126 * (128 * 128) * 1e6**2
print(f"  Llama3-405B, 1e6 토큰: {F405:.2e} FLOPs; 77 s x 128 GPU x 502 TFLOP/s = {77 * 128 * 502e12:.2e}")

# 캐시된 prefix를 다시 읽을까 다시 계산할까?  B > (토큰당 KV 바이트) * F / (2 N) 이면 다시 읽기가 이긴다
F = 400e12                                   # 가정한 GPU 한 장의 실효 FLOP/s (예시)
cfg = {"dense GQA 70B급 (bf16 KV)": (327_680, 70e9), "MLA, V3 (bf16 latent)": (70_272, 37e9),
       "CSA/HCA, V4-Pro (추정)": (4_970, 49e9)}
P = 64_000
print(f"\n{P:,}토큰 prefix — 손익분기 대역폭보다 빠르면 다시 읽기가 낫다:")
for name, (kvb, n_act) in cfg.items():
    print(f"  {name:<26} KV {kvb * P / 2**30:6.2f} GiB  재계산 >= {2 * n_act * P / F:5.1f} s  "
          f"손익분기 = {kvb * F / (2 * n_act) / 1e9:5.2f} GB/s")
 
확인 문제Check yourself

query head 128개, KV head 8개인 모델이다. 400K토큰짜리 캐시된 prefix에 새 토큰 20K가 붙은 멀티턴 요청을 ring context parallelism으로 서빙한다. ring step마다 더 적은 바이트를 보내는 쪽은?

층마다 pass-KV는 T+P=420T + P = 420K토큰 전체의 KV, 2⋅420K⋅8⋅dh2 \cdot 420\text{K} \cdot 8 \cdot d_h개 원소를 옮기고, pass-Q는 새 토큰 T=20T = 20K개의 query, 20K⋅128⋅dh20\text{K} \cdot 128 \cdot d_h개를 옮긴다. 비는 2⋅420⋅820⋅128=2.6\frac{2 \cdot 420 \cdot 8}{20 \cdot 128} = 2.6이므로 pass-Q가 2.6배 덜 보낸다. 같은 말로 T/(T+P)≈4.8%≤2nkv/nh=12.5%T/(T+P) \approx 4.8\% \le 2 n_{kv}/n_h = 12.5\%다. pass-Q는 마지막에 부분 출력 all-to-all을 더하므로 기준이 조금 내려가지만(CP 논문 부록 C) 이 경우를 뒤집을 정도는 아니다.

확인 문제Check yourself

1M토큰 prefill을 한 번에 하지 않고 8K토큰 청크로 나눈다. 총 FLOPs와, 첫 청크 대비 마지막 청크의 비용은 어떻게 되나?

chunking은 같은 causal 계산의 순서만 바꾼다. key ≤ query인 (query, key) 쌍 하나하나가 여전히 정확히 한 번씩 계산되므로 총 FLOPs는 한 번에 하는 prefill과 같다(NumPy 블록이 둘 다 출력한다). 청크 jj의 비용은 2NC+4Ldattn(C⋅jC+C2/2)2NC + 4Ld_{\text{attn}}(C \cdot jC + C^2/2)로 jj에 선형이다. 70B급 모델이면 첫 청크 약 1.2 PFLOP, 마지막 청크 약 23.6 PFLOP다. chunking으로 얻는 것은 activation 메모리의 상한과 decode와의 끼워 넣기이지 FLOPs 감소가 아니다.

정리

  • 문맥 TT에서 KV 저장과 토큰당 decode 읽기는 O(T)O(T), prefill attention은 O(T2)O(T^2)로 자란다. attention은 T∗=N/(L dattn)T^* = N/(L\,d_{\text{attn}})에서 선형층을 넘어서고(70B급 dense 모델이면 약 107K), 1M prefill의 약 90%를 차지한다.
  • decode의 KV 읽기는 배치끼리 나눠 갖지 못하므로 arithmetic intensity가 배치와 무관하게 GQA에서 nh/nkvn_h/n_{kv}(64/8이면 8)다. MLA의 흡수 모드는 이것을 약 242 FLOP/byte로 올린다.
  • chunked prefill은 activation 메모리를 묶어 두고 decode와 끼워 넣기를 가능하게 하지만 FLOPs는 옮기지 않는다. 1M의 마지막 청크는 첫 청크의 약 20배다.
  • context parallelism은 시퀀스를 나눈다. online softmax로 합치는 ring attention은 정확하다. rank마다 수백~수천 토큰만 있으면 전송이 계산 뒤에 숨는다. zigzag(2N 청크)나 striped 샤딩이 causal 불균형을 고친다. pass-KV는 full prefill에, pass-Q(LSE all-to-all 병합)는 decode와 적중률 높은 partial prefill에 맞고, 기준은 T/(T+P)=2nkv/nhT/(T+P) = 2n_{kv}/n_h다. CP는 TTFT를 줄이지만 TPOT를 늘린다.
  • DSA는 저장량을 유지하고 O(T)O(T) indexer 스캔과 sparse gather를 더한다. window와 recurrent 층은 메모리를 평평하게 하지만 prefix caching과 speculative decoding을 위해 상태 스냅샷이 필요하다.
  • eviction(sink + window, SnapKV)은 손실이 있고 query에 의존한다. offload는 손실이 없고, 링크 대역폭이 (토큰당 KV 바이트) × FLOP/s ÷ 2N2N보다 크면 다시 계산하기를 이긴다. 압축 KV 아키텍처에서는 이 값이 아주 작다.

더 읽을거리Further reading