MLA, GQA and sliding windows shrink the size of each KV entry; sparse attention shrinks how many entries a query reads. This lesson takes the third route: replace the growing KV cache of most layers by a state whose size does not depend on the context length at all. Five of the frontier architectures in this track do it — Qwen3-Next / Qwen3.5 (Gated DeltaNet, 3:1), Qwen3.8-Next, Kimi Linear and K3 (KDA, 3:1), Nemotron 3 (Mamba-2, 4:1) and MiniMax-M1 (lightning attention, 7:1) — and one went back: MiniMax-M2 returned to full attention everywhere.
The report lessons already derive GDN and KDA in their own notation. Here we do what those lessons could not: put all of these layers into one recurrence, prove that a state-space model is a masked attention, derive the chunkwise algorithm that makes them trainable, and measure — with a recall experiment and with real configs — what the fixed state costs and why every surviving design keeps some full-attention layers.
The problem: decoding reads the entire past
At decode step , a softmax attention layer computes . It must read all cached keys and values: per-token compute and memory traffic grow linearly with context, and the cache itself grows linearly in memory (Track III’s inference lesson). In an agent trajectory of 200K tokens, that read is the decode cost.
An RNN carries a fixed-size instead, so decode is per token — but as Track II showed, classic RNNs cannot be trained in parallel over time and squeeze the whole past through one vector. The designs in this lesson keep the RNN’s decode while (a) making the state a matrix that stores key→value associations and (b) keeping training parallel.
Linear attention is a fast-weight memory
Drop the softmax (or replace by a feature-map inner product , as Katharopoulos et al. did; modern layers simply use normalised directly). Then associativity lets us move the brackets:
is a fast weight: a matrix written by outer products and read by a matrix-vector product, a linear associative memory (Schlag et al. 2021). Training can use the parallel form with a causal mask ; decoding uses the recurrence, reading and writing numbers per head per token, independent of .
What can it remember? Write pairs and read with a stored key ():
The second term is crosstalk. If the keys are orthonormal it vanishes — but holds at most orthonormal vectors, so a state stores at most independent associations. For random unit keys , so the crosstalk-to-signal ratio is about : recall degrades smoothly as approaches . Two more failure modes follow from the additive write: a key that is written twice returns the sum of both values (no overwrite), and nothing is ever forgotten, so the state’s norm grows without bound.
One recurrence, many transition matrices
Every layer in this lesson is the same recurrence with a different transition applied to the old state before writing:
| Layer | Transition | Write | Forgetting | Used in |
|---|---|---|---|---|
| Linear attention | none | — | ||
| RetNet, Lightning Attention-2 | (fixed per head) | fixed exponential | MiniMax-01/M1 (lightning) | |
| Mamba-2 (SSD) | , data-dependent scalar | input-dependent, one rate per head | Nemotron-H, Nemotron 3 | |
| GLA-style | per key channel | — | ||
| DeltaNet | replaces the value under | — | ||
| Gated DeltaNet | scalar gate + replacement | Qwen3-Next, Qwen3.5, Qwen3.8 | ||
| KDA | per-channel gate + replacement | Kimi Linear, Kimi K3 |
Two readings of the same table are useful.
- Online learning. The state is the weight of a linear regressor trained online, one step per token. Linear attention is gradient ascent on (it only adds); the delta rule is one SGD step with learning rate on , whose gradient is — so with the key’s old value is replaced. The gate is weight decay on the fast weights. The derivation is in the Qwen3-Next lesson and, for KDA’s channel-wise gate and its decay floor, in the K3 lesson.
- Stability. The eigenvalues of are (on ) and . With -normalised keys and they lie in : the transition never amplifies, which is why every delta-rule layer normalises and . Gates multiply by numbers in , so the product of transitions is a contraction.
Selective state spaces: Mamba and Mamba-2
State-space models arrive at the same place from control theory. A continuous linear system , , discretised with step (zero-order hold on ), becomes
Classic SSMs (S4) keep fixed, which makes the layer a long convolution — but a fixed filter cannot decide what to keep based on content. Mamba (Gu & Dao 2023) makes functions of the current input (a selective SSM): a large resets the state and absorbs , a small one ignores the token. Mamba-1 runs a separate diagonal SSM with a small state (default ) for every channel, computed with a hardware-aware parallel scan.
Mamba-2 restricts to a scalar times identity, , shared by a head of channels (the SSD paper says is typical). The per-head state becomes a matrix:
Put and compare with the table: this is exactly decayed linear attention with , , and a data-dependent scalar decay. Nemotron 3 Ultra’s config makes it concrete: 256 Mamba heads per layer, , (mamba_head_dim, ssm_state_size), a state per head.
The SSD duality: a state-space model is masked attention
Unroll the scalar-decay recurrence from :
Stacking all : , with for and otherwise. That is masked attention without a softmax, where the mask is not just causal but a learned, input-dependent decay — it is also the model’s positional information. In the SSD paper’s language, the sequence map is the matrix with , and is 1-semiseparable: every submatrix strictly below the diagonal has rank 1, because with . Consequently every off-diagonal block of has rank at most .
The same matrix can be applied in two ways — that is the duality:
- linear (recurrent) mode: FLOPs, state, but dependent steps;
- quadratic (attention) mode: form explicitly, FLOPs, fully parallel matmuls.
Neither is good for training on long sequences. The chunked algorithm below uses each where it is cheap.
MLA, GQA, sliding window는 KV 항목 하나의 크기를 줄이고, sparse attention은 query가 읽는 항목의 수를 줄인다. 이 레슨은 세 번째 길을 간다. 대부분 층의 자라나는 KV cache를 문맥 길이와 전혀 상관없는 크기의 상태로 바꾼다. 이 트랙에서 다루는 프런티어 아키텍처 다섯이 그렇게 했다. Qwen3-Next / Qwen3.5(Gated DeltaNet, 3:1), Qwen3.8-Next, Kimi Linear와 K3(KDA, 3:1), Nemotron 3(Mamba-2, 4:1), MiniMax-M1(lightning attention, 7:1). 그리고 하나는 되돌아갔다. MiniMax-M2는 전 층을 full attention으로 돌려놓았다.
보고서 레슨들은 GDN과 KDA를 각자의 표기로 이미 유도했다. 여기서는 그 레슨들이 하지 못한 일을 한다. 이 층들을 모두 하나의 점화식에 넣고, 상태공간 모델이 곧 masked attention임을 증명하고, 이것들을 학습 가능하게 만드는 chunk 알고리즘을 유도하고, 고정 상태가 무엇을 잃는지와 살아남은 설계가 왜 모두 full attention 층을 일부 남기는지를 recall 실험과 실제 config로 잰다.
문제: decode는 과거 전체를 읽는다
decode 단계 에서 softmax attention 층은 를 계산한다. 캐시된 key와 value 개를 모두 읽어야 하므로 토큰당 연산과 메모리 트래픽이 문맥에 비례해 늘고, 캐시 자체도 메모리에서 선형으로 자란다(Track III 추론 레슨). 20만 토큰짜리 agent 궤적에서는 그 읽기가 곧 decode 비용이다.
RNN은 고정 크기 를 들고 다니므로 decode가 토큰당 이다. 하지만 Track II에서 본 것처럼 고전 RNN은 시간 방향으로 병렬 학습이 안 되고 과거 전체를 벡터 하나로 짜낸다. 이 레슨의 설계들은 RNN의 decode를 유지하면서 (a) 상태를 key→value 연관을 저장하는 행렬로 만들고 (b) 학습은 병렬로 유지한다.
Linear attention은 fast-weight 메모리다
softmax를 빼면(또는 Katharopoulos et al.처럼 를 feature map 내적 로 바꾸면. 최신 층들은 정규화한 를 그대로 쓴다) 결합법칙으로 괄호를 옮길 수 있다.
는 fast weight다. outer product로 쓰고 행렬-벡터 곱으로 읽는 행렬, 즉 선형 연상 메모리다(Schlag et al. 2021). 학습은 causal mask 을 쓴 병렬형 로, decode는 점화식으로 한다. head·토큰마다 개 숫자를 읽고 쓰며, 와 무관하다.
무엇을 기억할 수 있나. 쌍 개를 쓰고 저장된 key ()로 읽으면
둘째 항이 crosstalk다. key가 정규직교면 사라지지만 에는 정규직교 벡터가 많아야 개다. 그러므로 상태는 독립적인 연관을 많아야 개 저장한다. 무작위 단위 key에서는 이므로 crosstalk 대 신호 비가 약 이고, 이 에 다가갈수록 recall이 서서히 무너진다. 덧셈 쓰기에서 실패 유형이 둘 더 나온다. 두 번 쓴 key는 두 값의 합을 돌려주고(덮어쓰기 불가), 아무것도 잊지 않으므로 상태의 norm이 끝없이 커진다.
점화식 하나, 전이 행렬 여럿
이 레슨의 모든 층은 같은 점화식이고, 쓰기 전에 옛 상태에 곱하는 전이(transition) 만 다르다.
| 층 | 전이 | 쓰기 | 잊기 | 쓰는 곳 |
|---|---|---|---|---|
| Linear attention | 없음 | — | ||
| RetNet, Lightning Attention-2 | (head별 고정) | 고정 지수 감쇠 | MiniMax-01/M1 (lightning) | |
| Mamba-2 (SSD) | , 데이터 의존 스칼라 | 입력 의존, head당 한 비율 | Nemotron-H, Nemotron 3 | |
| GLA 계열 | key 채널별 | — | ||
| DeltaNet | 아래 값을 교체 | — | ||
| Gated DeltaNet | 스칼라 gate + 교체 | Qwen3-Next, Qwen3.5, Qwen3.8 | ||
| KDA | 채널별 gate + 교체 | Kimi Linear, Kimi K3 |
같은 표를 두 가지로 읽을 수 있다.
- 온라인 학습. 상태는 선형 회귀기의 가중치이고, 토큰마다 한 step씩 온라인으로 학습된다. linear attention은 에 대한 경사 상승(더하기만 한다)이고, delta rule은 에 학습률 로 한 SGD step이다. 기울기가 이므로 이면 그 key의 옛 값이 교체된다. gate 는 fast weight의 weight decay다. 유도는 Qwen3-Next 레슨에, KDA의 채널별 gate와 decay 하한은 K3 레슨에 있다.
- 안정성. 의 고유값은 ( 위)과 이다. 정규화한 key와 이면 안에 있어 전이가 절대 증폭하지 않는다. delta rule 층이 모두 를 정규화하는 이유다. gate는 의 수를 곱하므로 전이들의 곱은 축소 사상이다.
선택적 상태공간: Mamba와 Mamba-2
상태공간 모델(SSM)은 제어이론에서 출발해 같은 곳에 닿는다. 연속 선형계 , 를 step 로 이산화하면(는 zero-order hold)
고전 SSM(S4)은 가 고정이라 층이 긴 convolution이 된다. 하지만 고정 필터는 내용을 보고 무엇을 남길지 정할 수 없다. Mamba(Gu & Dao 2023)는 를 현재 입력의 함수로 만든다(선택적 SSM). 가 크면 상태를 리셋하고 를 흡수하며, 작으면 그 토큰을 무시한다. Mamba-1은 채널마다 작은 상태(기본 )의 대각 SSM을 따로 돌리고, 하드웨어를 고려한 병렬 scan으로 계산한다.
Mamba-2는 를 스칼라 곱하기 항등행렬 로 제한하고, 이를 채널 개짜리 head가 공유한다(SSD 논문은 이 보통이라고 쓴다). head별 상태는 행렬이 된다.
로 두고 표와 비교하면 정확히 감쇠가 있는 linear attention이다. , , , 그리고 데이터 의존 스칼라 감쇠. Nemotron 3 Ultra의 config로 구체화하면 층당 Mamba head 256개, , (mamba_head_dim, ssm_state_size)로 head마다 상태다.
SSD 쌍대성: 상태공간 모델은 masked attention이다
스칼라 감쇠 점화식을 부터 펼치면
모든 를 쌓으면 이고, 에서 , 나머지는 이다. softmax 없는 masked attention인데, 마스크 이 단순한 causal 마스크가 아니라 학습되는 입력 의존 감쇠다. 모델의 위치 정보이기도 하다. SSD 논문의 말로는 시퀀스 사상이 행렬 , 이고, 은 1-semiseparable이다. 로 쓰면 라서 대각선 아래의 모든 부분행렬의 rank가 1이다. 그래서 의 비대각 블록은 rank가 이하다.
같은 행렬을 두 가지로 적용할 수 있다는 것이 쌍대성이다.
- 선형(순환) 모드: FLOPs , 상태 , 하지만 서로 의존하는 단계;
- 2차(attention) 모드: 을 직접 만들어 FLOPs , 완전히 병렬인 행렬곱.
긴 시퀀스 학습에는 둘 다 좋지 않다. 아래의 chunk 알고리즘은 각각을 싼 곳에서 쓴다.
The chunkwise-parallel algorithm
Split the sequence into chunks of length . Inside a chunk index positions , let be the state entering the chunk and the decay accumulated since the chunk start. Unrolling only within the chunk,
In matrix form, for chunk with and :
Everything is a matmul on tiles except one tiny loop over chunk boundaries. Per token and head that costs FLOPs for the intra-chunk term plus for the state read and update — versus for the pure recurrence and for the quadratic form. With and : 82 KFLOPs vs 66 KFLOPs for the recurrence, but in 64× fewer sequential steps and on tensor cores. This is exactly SSD’s four-step algorithm (diagonal blocks, chunk states, state passing, output from states), and exactly Lightning Attention-2: intra-block with , inter-block , and — the fixed-decay special case .
Adding the delta rule. For GDN the write depends on the state, , so the “values” written into the chunk are not known in advance. Unroll it inside the chunk exactly as above, , and substitute:
with strictly lower-triangular. is unit lower-triangular, so costs one triangular solve (the UT transform; DeltaNet’s WY representation is the same object). Then plays the role of in the formulas above. The K3 lesson does the same with a per-channel decay and explains why its needs a floor.
import numpy as np
rng = np.random.default_rng(0)
T, dk, dv, C = 256, 32, 16, 64 # length, key/value width, chunk size
def l2n(x): return x / np.linalg.norm(x, axis=-1, keepdims=True)
q, k = l2n(rng.normal(size=(T, dk))), l2n(rng.normal(size=(T, dk)))
v = rng.normal(size=(T, dv))
alpha = 1 / (1 + np.exp(-(rng.normal(size=T) + 3))) # data-dependent scalar decay a_t in (0,1)
beta = 1 / (1 + np.exp(-rng.normal(size=T))) # write strength (delta rule only)
G = np.cumsum(np.log(alpha)) # log of the cumulative decay
# --- 1. Decayed linear attention (= Mamba-2/SSD with Q=C, K=B, V=x): three algorithms ---
def rec_decay(q, k, v, alpha): # O(T) sequential: S_t = a_t S_{t-1} + k_t v_tᵀ
S, out = np.zeros((dk, dv)), []
for t in range(len(q)):
S = alpha[t] * S + np.outer(k[t], v[t])
out.append(S.T @ q[t])
return np.array(out)
def quad_decay(q, k, v, G): # O(T²) "attention" form: (L ∘ QKᵀ) V
L = np.tril(np.exp(G[:, None] - G[None, :])) # L_ts = a_{s+1}···a_t for s ≤ t
return (L * (q @ k.T)) @ v
def chunk_decay(q, k, v, G, C): # matmuls inside a chunk, one state between chunks
S, out = np.zeros((dk, dv)), []
for s in range(0, len(q), C):
Q, K, V = q[s:s+C], k[s:s+C], v[s:s+C]
g = G[s:s+C] - (G[s-1] if s else 0.0) # log γ_r within the chunk
Lc = np.tril(np.exp(g[:, None] - g[None, :]))
out.append(np.exp(g)[:, None] * (Q @ S) + (Lc * (Q @ K.T)) @ V) # inter + intra
S = np.exp(g[-1]) * S + (K * np.exp(g[-1] - g)[:, None]).T @ V # state at the chunk end
return np.vstack(out)
o1, o2, o3 = rec_decay(q, k, v, alpha), quad_decay(q, k, v, G), chunk_decay(q, k, v, G, C)
print(f"decayed linear attn: |rec - quadratic| = {np.abs(o1-o2).max():.1e}, |rec - chunkwise| = {np.abs(o1-o3).max():.1e}")
# --- 2. Gated delta rule (GDN): recurrent vs chunkwise with the UT transform ---
def rec_gdn(q, k, v, alpha, beta):
S, out = np.zeros((dk, dv)), []
for t in range(len(q)):
S = alpha[t] * S # forget
S = S + beta[t] * np.outer(k[t], v[t] - S.T @ k[t]) # error-correcting write
out.append(S.T @ q[t])
return np.array(out), S
def chunk_gdn(q, k, v, G, beta, C):
S, out = np.zeros((dk, dv)), []
for s in range(0, len(q), C):
Q, K, V, B = q[s:s+C], k[s:s+C], v[s:s+C], beta[s:s+C]
g = G[s:s+C] - (G[s-1] if s else 0.0)
D = np.exp(g[:, None] - g[None, :]) # γ_r / γ_s
A = np.tril(D * (K @ K.T), -1) # strictly lower triangular
Tm = np.linalg.inv(np.eye(len(Q)) + B[:, None] * A) # UT transform (kernels: forward substitution)
U = Tm @ (B[:, None] * (V - np.exp(g)[:, None] * (K @ S))) # pseudo-values u_r
out.append(np.exp(g)[:, None] * (Q @ S) + np.tril(D * (Q @ K.T)) @ U)
S = np.exp(g[-1]) * S + (K * np.exp(g[-1] - g)[:, None]).T @ U
return np.vstack(out), S
(o_r, S_r), (o_c, S_c) = rec_gdn(q, k, v, alpha, beta), chunk_gdn(q, k, v, G, beta, C)
print(f"gated delta rule: |rec - chunkwise| = {np.abs(o_r-o_c).max():.1e} (outputs), {np.abs(S_r-S_c).max():.1e} (final state)")
# --- 3. Cost per token per head (multiply-add = 2 FLOPs), d_k = d_v = 128 ---
d = 128
for Tn in [4096, 131072]:
for Cn in [1, 64, 256, Tn]:
intra = 0 if Cn == 1 else Cn * 2 * d # causal half of 2·C·(d_k + d_v)
inter = 0 if Cn == Tn else 4 * d * d # q·S read + state update
print(f"T={Tn:>6} C={Cn:>6}: {(intra + inter) / 1e3:8.1f} KFLOPs/token sequential steps {Tn // Cn:>6}")All three algorithms agree to round-off, for the plain decayed form and for the delta rule. The quadratic form at 128K would be 33.5 MFLOPs per token per head — 400× the chunkwise cost — which is why no one trains a long-context linear layer that way, even though it is “just attention”.
In PyTorch the chunked form batches over heads and chunks; only the state-passing loop over chunks is sequential. Production kernels (FLA’s Triton kernels, mamba_ssm’s chunked scan, Qwen’s TileLang-based FlashQLA) fuse these four steps.
import torch
import torch.nn.functional as F
def ssd_chunked(q, k, v, log_a, chunk=64):
"""Decayed linear attention = Mamba-2 SSD (q=C, k=B, v=x), chunkwise.
q, k: (B, H, T, dk) v: (B, H, T, dv) log_a: (B, H, T), a_t = exp(log_a) in (0, 1].
Returns o: (B, H, T, dv) and the final state (B, H, dk, dv). T must be a multiple of `chunk`."""
B, H, T, dk = q.shape
dv, n = v.shape[-1], T // chunk
q, k, v = (x.reshape(B, H, n, chunk, -1) for x in (q, k, v))
g = log_a.reshape(B, H, n, chunk).cumsum(-1) # log γ_r inside each chunk
# 1) intra-chunk: (L ∘ Q Kᵀ) V with L_rs = exp(g_r − g_s) for s ≤ r — a small masked "attention"
causal = torch.ones(chunk, chunk, dtype=torch.bool, device=q.device).tril()
L = torch.exp((g.unsqueeze(-1) - g.unsqueeze(-2)).masked_fill(~causal, float("-inf")))
o_intra = (L * (q @ k.transpose(-1, -2))) @ v
# 2) what each chunk alone adds to the state at its end: Σ_s exp(g_C − g_s) k_s v_sᵀ
w = torch.exp(g[..., -1:] - g).unsqueeze(-1) # (B, H, n, C, 1)
chunk_states = (k * w).transpose(-1, -2) @ v # (B, H, n, dk, dv)
# 3) pass states across chunk boundaries — the only sequential loop, n = T/C steps
S, entering = q.new_zeros(B, H, dk, dv), []
for c in range(n):
entering.append(S)
S = torch.exp(g[:, :, c, -1])[..., None, None] * S + chunk_states[:, :, c]
# 4) inter-chunk output: decayed read of the state that entered the chunk
o_inter = torch.exp(g).unsqueeze(-1) * (q @ torch.stack(entering, dim=2))
return (o_intra + o_inter).reshape(B, H, T, dv), S
B, H, T, dk, dv = 2, 4, 256, 32, 32
q, k, v = torch.randn(B, H, T, dk), torch.randn(B, H, T, dk) / dk**0.5, torch.randn(B, H, T, dv)
log_a = F.logsigmoid(torch.randn(B, H, T) + 3) # a_t ≈ 0.95 on average
o, S = ssd_chunked(q, k, v, log_a)
S_ref, outs = torch.zeros(B, H, dk, dv), [] # reference: the plain recurrence
for t in range(T):
S_ref = log_a[..., t].exp()[..., None, None] * S_ref + k[..., t, :, None] * v[..., t, None, :]
outs.append((q[..., t, :, None] * S_ref).sum(-2))
print(torch.allclose(o, torch.stack(outs, 2), atol=1e-4), torch.allclose(S, S_ref, atol=1e-4)) # True TrueHow much can a state remember?
The capacity argument says a fixed state holds about independent associations, no matter the update rule. Zoology (Arora et al. 2023) turned this into a benchmark, multi-query associative recall (MQAR), and found that most of the perplexity gap between efficient models and attention on real text — 82% in their analysis — is explained by recall of previously seen tokens; a 70M attention model beat a 1.4B gated-convolution model on it. Based (2024) made the trade-off explicit: recall improves with state size, and you pay for it in throughput. The Mamba-2 paper reports the same: on MQAR, raising from 16 to 64 to 256 consistently helps. The figure below is a toy MQAR you can run with different rules.
chunk 병렬 알고리즘
시퀀스를 길이 의 chunk로 나눈다. chunk 안의 위치를 , chunk에 들어오는 상태를 , chunk 시작 이후 누적된 감쇠를 라 하자. chunk 안에서만 펼치면
chunk 의 와 로 행렬 꼴로 쓰면
개 chunk 경계를 도는 작은 루프 하나만 빼면 모두 tile 위의 행렬곱이다. head·토큰당 비용은 chunk 안 항이 약 FLOPs, 상태 읽기와 갱신이 다. 순수 순환형은 , 2차 형태는 다. , 이면 순환형 66 KFLOPs 대비 82 KFLOPs지만 순차 단계가 64배 적고 tensor core 위에서 돈다. 이것이 정확히 SSD의 4단계 알고리즘(대각 블록, chunk 상태, 상태 전달, 상태로부터의 출력)이고, 정확히 Lightning Attention-2다. block 안은 인 , block 사이는 , 그리고 . 고정 감쇠 인 특수한 경우다.
delta rule 더하기. GDN에서는 쓰는 값이 상태에 의존한다. 이므로 chunk에 쓰일 “값”을 미리 알 수 없다. 위와 똑같이 chunk 안에서 로 펼쳐 대입하면
이고 는 순하삼각이다. 는 대각이 1인 하삼각이므로 는 삼각 풀이 한 번이면 된다(UT transform. DeltaNet의 WY 표현과 같은 대상이다). 그다음 가 위 식의 역할을 한다. K3 레슨은 채널별 감쇠로 같은 일을 하고, 거기서 에 하한이 필요한 이유를 설명한다.
import numpy as np
rng = np.random.default_rng(0)
T, dk, dv, C = 256, 32, 16, 64 # 길이, key/value 폭, chunk 크기
def l2n(x): return x / np.linalg.norm(x, axis=-1, keepdims=True)
q, k = l2n(rng.normal(size=(T, dk))), l2n(rng.normal(size=(T, dk)))
v = rng.normal(size=(T, dv))
alpha = 1 / (1 + np.exp(-(rng.normal(size=T) + 3))) # 데이터 의존 스칼라 감쇠 a_t ∈ (0,1)
beta = 1 / (1 + np.exp(-rng.normal(size=T))) # 쓰기 세기 (delta rule에서만)
G = np.cumsum(np.log(alpha)) # 누적 감쇠의 log
# --- 1. 감쇠 linear attention (= Q=C, K=B, V=x인 Mamba-2/SSD): 세 알고리즘 ---
def rec_decay(q, k, v, alpha): # O(T) 순차: S_t = a_t S_{t-1} + k_t v_tᵀ
S, out = np.zeros((dk, dv)), []
for t in range(len(q)):
S = alpha[t] * S + np.outer(k[t], v[t])
out.append(S.T @ q[t])
return np.array(out)
def quad_decay(q, k, v, G): # O(T²) "attention" 형태: (L ∘ QKᵀ) V
L = np.tril(np.exp(G[:, None] - G[None, :])) # s ≤ t에서 L_ts = a_{s+1}···a_t
return (L * (q @ k.T)) @ v
def chunk_decay(q, k, v, G, C): # chunk 안은 행렬곱, chunk 사이는 상태 하나
S, out = np.zeros((dk, dv)), []
for s in range(0, len(q), C):
Q, K, V = q[s:s+C], k[s:s+C], v[s:s+C]
g = G[s:s+C] - (G[s-1] if s else 0.0) # chunk 안의 log γ_r
Lc = np.tril(np.exp(g[:, None] - g[None, :]))
out.append(np.exp(g)[:, None] * (Q @ S) + (Lc * (Q @ K.T)) @ V) # chunk 사이 + chunk 안
S = np.exp(g[-1]) * S + (K * np.exp(g[-1] - g)[:, None]).T @ V # chunk 끝의 상태
return np.vstack(out)
o1, o2, o3 = rec_decay(q, k, v, alpha), quad_decay(q, k, v, G), chunk_decay(q, k, v, G, C)
print(f"decayed linear attn: |rec - quadratic| = {np.abs(o1-o2).max():.1e}, |rec - chunkwise| = {np.abs(o1-o3).max():.1e}")
# --- 2. Gated delta rule (GDN): 순환형 vs UT transform을 쓴 chunk형 ---
def rec_gdn(q, k, v, alpha, beta):
S, out = np.zeros((dk, dv)), []
for t in range(len(q)):
S = alpha[t] * S # 잊기
S = S + beta[t] * np.outer(k[t], v[t] - S.T @ k[t]) # 오차를 고치는 쓰기
out.append(S.T @ q[t])
return np.array(out), S
def chunk_gdn(q, k, v, G, beta, C):
S, out = np.zeros((dk, dv)), []
for s in range(0, len(q), C):
Q, K, V, B = q[s:s+C], k[s:s+C], v[s:s+C], beta[s:s+C]
g = G[s:s+C] - (G[s-1] if s else 0.0)
D = np.exp(g[:, None] - g[None, :]) # γ_r / γ_s
A = np.tril(D * (K @ K.T), -1) # 순하삼각
Tm = np.linalg.inv(np.eye(len(Q)) + B[:, None] * A) # UT transform (커널은 전진 대입)
U = Tm @ (B[:, None] * (V - np.exp(g)[:, None] * (K @ S))) # pseudo-value u_r
out.append(np.exp(g)[:, None] * (Q @ S) + np.tril(D * (Q @ K.T)) @ U)
S = np.exp(g[-1]) * S + (K * np.exp(g[-1] - g)[:, None]).T @ U
return np.vstack(out), S
(o_r, S_r), (o_c, S_c) = rec_gdn(q, k, v, alpha, beta), chunk_gdn(q, k, v, G, beta, C)
print(f"gated delta rule: |rec - chunkwise| = {np.abs(o_r-o_c).max():.1e} (outputs), {np.abs(S_r-S_c).max():.1e} (final state)")
# --- 3. head·토큰당 비용 (곱셈-덧셈 = 2 FLOPs), d_k = d_v = 128 ---
d = 128
for Tn in [4096, 131072]:
for Cn in [1, 64, 256, Tn]:
intra = 0 if Cn == 1 else Cn * 2 * d # 2·C·(d_k + d_v)의 causal 절반
inter = 0 if Cn == Tn else 4 * d * d # q·S 읽기 + 상태 갱신
print(f"T={Tn:>6} C={Cn:>6}: {(intra + inter) / 1e3:8.1f} KFLOPs/token sequential steps {Tn // Cn:>6}")세 알고리즘이 순수 감쇠형에서도, delta rule에서도 반올림 오차 수준으로 일치한다. 128K에서 2차 형태는 head·토큰당 33.5 MFLOPs로 chunk형의 400배다. “그냥 attention”인데도 아무도 긴 문맥 linear 층을 그렇게 학습하지 않는 이유다.
PyTorch에서는 chunk형을 head와 chunk에 대해 batch로 처리하고, 개 chunk를 도는 상태 전달 루프만 순차적이다. 실제 커널(FLA의 Triton 커널, mamba_ssm의 chunk scan, Qwen의 TileLang 기반 FlashQLA)은 이 네 단계를 융합한다.
import torch
import torch.nn.functional as F
def ssd_chunked(q, k, v, log_a, chunk=64):
"""감쇠 linear attention = Mamba-2 SSD (q=C, k=B, v=x), chunk형.
q, k: (B, H, T, dk) v: (B, H, T, dv) log_a: (B, H, T), a_t = exp(log_a) ∈ (0, 1].
출력 o: (B, H, T, dv)와 마지막 상태 (B, H, dk, dv). T는 chunk의 배수여야 한다."""
B, H, T, dk = q.shape
dv, n = v.shape[-1], T // chunk
q, k, v = (x.reshape(B, H, n, chunk, -1) for x in (q, k, v))
g = log_a.reshape(B, H, n, chunk).cumsum(-1) # chunk 안의 log γ_r
# 1) chunk 안: s ≤ r에서 L_rs = exp(g_r − g_s)인 (L ∘ Q Kᵀ) V — 작은 masked "attention"
causal = torch.ones(chunk, chunk, dtype=torch.bool, device=q.device).tril()
L = torch.exp((g.unsqueeze(-1) - g.unsqueeze(-2)).masked_fill(~causal, float("-inf")))
o_intra = (L * (q @ k.transpose(-1, -2))) @ v
# 2) chunk 하나가 끝 상태에 더하는 몫: Σ_s exp(g_C − g_s) k_s v_sᵀ
w = torch.exp(g[..., -1:] - g).unsqueeze(-1) # (B, H, n, C, 1)
chunk_states = (k * w).transpose(-1, -2) @ v # (B, H, n, dk, dv)
# 3) chunk 경계를 넘어 상태 전달 — 유일한 순차 루프, n = T/C 단계
S, entering = q.new_zeros(B, H, dk, dv), []
for c in range(n):
entering.append(S)
S = torch.exp(g[:, :, c, -1])[..., None, None] * S + chunk_states[:, :, c]
# 4) chunk 사이 출력: chunk에 들어온 상태를 감쇠해 읽기
o_inter = torch.exp(g).unsqueeze(-1) * (q @ torch.stack(entering, dim=2))
return (o_intra + o_inter).reshape(B, H, T, dv), S
B, H, T, dk, dv = 2, 4, 256, 32, 32
q, k, v = torch.randn(B, H, T, dk), torch.randn(B, H, T, dk) / dk**0.5, torch.randn(B, H, T, dv)
log_a = F.logsigmoid(torch.randn(B, H, T) + 3) # 평균 a_t ≈ 0.95
o, S = ssd_chunked(q, k, v, log_a)
S_ref, outs = torch.zeros(B, H, dk, dv), [] # 기준: 그냥 점화식
for t in range(T):
S_ref = log_a[..., t].exp()[..., None, None] * S_ref + k[..., t, :, None] * v[..., t, None, :]
outs.append((q[..., t, :, None] * S_ref).sum(-2))
print(torch.allclose(o, torch.stack(outs, 2), atol=1e-4), torch.allclose(S, S_ref, atol=1e-4)) # True True상태는 얼마나 기억하나
용량 논증은 갱신 규칙과 상관없이 고정 상태가 독립적인 연관을 약 개 담는다고 말한다. Zoology(Arora et al. 2023)는 이것을 multi-query associative recall(MQAR)이라는 벤치마크로 만들었고, 실제 텍스트에서 효율적 모델과 attention 사이의 perplexity 격차 대부분(그들의 분석에서 82%)이 앞서 본 토큰을 다시 불러오는 능력으로 설명된다는 것을 보였다. 이 과제에서 70M attention 모델이 1.4B gated-convolution 모델을 이겼다. Based(2024)는 그 trade-off를 명시했다. 상태가 클수록 recall이 좋아지고, 대가는 처리량으로 치른다. Mamba-2 논문도 같은 것을 보고한다. MQAR에서 을 16 → 64 → 256으로 키우면 일관되게 좋아진다. 아래 그림은 규칙을 바꿔 가며 돌려 볼 수 있는 장난감 MQAR이다.
What to take away from the figure:
- The wall is at for every fixed-state rule. Better update rules move where and how recall fails; none of them moves the wall. Only attention, whose memory grows with what it stores, stays at 100%.
- The delta rule is not “more capacity”, it is “editable memory”. With distinct keys and it is worse than linear attention: every write projects out the old content along the new key, erasing a little of everything stored. Its advantage appears when keys are re-written (state tracking: “x = 3 … x = 5”) or correlated — exactly the situations in code, tool outputs and multi-turn dialogues. trades plasticity for retention; making data-dependent lets the model choose per token.
- Decay buys freshness at the price of long-range recall. That is the right bias for most tokens, and the wrong one for a needle 100K tokens back — which is the job of the full-attention layers.
import numpy as np
def recall(rule, n, dk=32, dv=32, ncode=64, upd=0.0, alpha=0.98, beta=1.0, trials=3):
"""n distinct keys written with values, then upd·n re-writes with new values; read every key back."""
acc = []
for tr in range(trials):
r = np.random.default_rng(100 * tr + n)
code = r.normal(size=(ncode, dv)); code /= np.linalg.norm(code, axis=1, keepdims=True)
K = r.normal(size=(n, dk)); K /= np.linalg.norm(K, axis=1, keepdims=True)
final = r.integers(0, ncode, size=n)
stream = [(i, final[i]) for i in range(n)]
for i in r.integers(0, n, size=int(upd * n)): # re-assign: "x = 3 ... x = 5"
c = r.integers(0, ncode); stream.append((i, c)); final[i] = c
idx = np.array([i for i, _ in stream]); Vs = code[[c for _, c in stream]]
if rule == "attention": # keeps every write: KV grows with the stream
score = K @ K[idx].T + 1e-6 * np.arange(len(stream)) # sharp softmax + recency tie-break (RoPE's job)
read = Vs[np.argmax(score, axis=1)] # zero-temperature limit of softmax
else:
S = np.zeros((dk, dv)) # the whole memory: d_k × d_v floats
for i, vv in zip(idx, Vs):
k = K[i]
if rule == "linear":
S += np.outer(k, vv) # additive write
else:
if rule == "gated delta":
S *= alpha # forget a little everywhere
S += beta * np.outer(k, vv - S.T @ k) # replace what is stored under k
read = K @ S
acc.append(np.mean(np.argmax(read @ code.T, axis=1) == final))
return np.mean(acc)
ns = [8, 16, 32, 64, 128]
for upd in [0.0, 1.0]:
print(f"d_k = 32, state = 32x32 floats | re-writes = {upd:.0%} of n")
print(" n " + "".join(f"{n:>6}" for n in ns))
for rule in ["linear", "delta", "gated delta", "attention"]:
print(f" {rule:12s}" + "".join(f"{recall(rule, n, upd=upd):6.2f}" for n in ns))
print("delta, β=0.5, no re-writes" + "".join(f"{recall('delta', n, beta=0.5):6.2f}" for n in ns))
# crosstalk for linear attention: Sᵀk_i = v_i + Σ_{j≠i} (k_j·k_i) v_j with k_j·k_i ~ N(0, 1/d_k)
for n in [8, 32, 128]:
print(f"linear attention, n={n:>3}: |noise|/|signal| ≈ sqrt((n-1)/d_k) = {np.sqrt((n - 1) / 32):.2f}")With 100% re-writes, linear attention is already at 71% for — far below its capacity — because it returns blends; the delta rule is perfect there. At every fixed-state rule is at 20–25% while attention is still exact. The toy’s “attention” is idealised (zero temperature, a recency tie-break that a real model learns from RoPE), but the asymmetry it shows — fixed state vs growing cache — is the real one.
A pure Gated DeltaNet layer with head dimension d_k = 128 has to answer questions about 2,000 distinct variable bindings scattered through a 100K-token context. Which statement is right?
The state is a matrix; its read-out is linear in , and at most key directions can be read back without interference. Better rules (delta, gates) decide which associations survive and make the memory editable; they cannot raise the rank. More heads multiply capacity linearly, but that is exactly the “bigger state” cost. The chunk size changes only how the same function is computed. This is why the full-attention layers in hybrids exist.
Hybrids: how many full-attention layers?
Every production design keeps a minority of global softmax-attention layers as exact-recall “anchors” (the Nemotron Super report’s word) and makes the rest linear. The configurations, all from the released config.json files:
| Model | Linear mixer | Linear : full layers | Full-attention layers | State per linear layer (values) |
|---|---|---|---|---|
| Qwen3-Next-80B-A3B | Gated DeltaNet | 36 : 12 | gated GQA, 2 KV heads × 256, partial RoPE | 32 heads × 128 × 128 = 524K |
| Qwen3.8-Flash-Next | Gated DeltaNet | 36 : 12 | Qwen Sparse Attention (2 KV heads × 256) | 48 × 128 × 128 = 786K |
| Kimi Linear 48B-A3B | KDA | 20 : 7 | MLA, NoPE | 32 × 128 × 128 = 524K |
| Kimi K3 | KDA | 69 : 24 | gated MLA, NoPE | 96 × 128 × 128 = 1.57M |
| Nemotron 3 Ultra | Mamba-2 | 48 : 12 | GQA, 2 KV heads × 128, no position embedding | 256 heads × 64 × 128 = 2.10M |
| MiniMax-M1 | lightning attention | 70 : 10 | GQA, 8 KV heads × 128 | 64 heads × 128 × 128 = 1.05M (our reading of the config) |
| MiniMax-M2 | — | 0 : 62 | GQA, 8 KV heads × 128 | — |
The decode memory of one sequence is
and a decode step reads all of it once, so the same expression is the per-token memory traffic. The two terms cross at : about 3K tokens for Qwen3-Next, 33K for Nemotron 3 Ultra (403 MB of FP32 SSM state vs 12 KB of KV per token). Below the hybrid holds more state than an all-attention model of the same shape.
그림에서 가져갈 것:
- 고정 상태 규칙은 모두 에서 벽을 만난다. 더 나은 갱신 규칙은 recall이 어디서 어떻게 무너지는지를 바꿀 뿐, 벽을 옮기지 못한다. 저장한 만큼 메모리가 자라는 attention만 100%에 머문다.
- delta rule은 “더 큰 용량”이 아니라 “고칠 수 있는 메모리”다. 서로 다른 key만 쓰고 이면 linear attention보다 나쁘다. 쓸 때마다 새 key 방향으로 옛 내용을 projection으로 빼내므로, 저장된 모든 것이 조금씩 지워진다. 장점은 key가 다시 쓰이거나(상태 추적: “x = 3 … x = 5”) 상관될 때 나타난다. 코드, 도구 출력, 멀티턴 대화가 정확히 그런 상황이다. 은 가소성과 보존을 맞바꾸고, 를 데이터 의존으로 만들면 모델이 토큰마다 고른다.
- 감쇠는 신선함을 사는 대신 먼 recall을 판다. 대부분의 토큰에는 맞는 편향이고, 100K 토큰 전의 바늘에는 틀린 편향이다. 그 바늘이 full attention 층의 몫이다.
import numpy as np
def recall(rule, n, dk=32, dv=32, ncode=64, upd=0.0, alpha=0.98, beta=1.0, trials=3):
"""서로 다른 key n개를 값과 함께 쓰고, upd·n번 새 값으로 다시 쓴 뒤, 모든 key로 읽는다."""
acc = []
for tr in range(trials):
r = np.random.default_rng(100 * tr + n)
code = r.normal(size=(ncode, dv)); code /= np.linalg.norm(code, axis=1, keepdims=True)
K = r.normal(size=(n, dk)); K /= np.linalg.norm(K, axis=1, keepdims=True)
final = r.integers(0, ncode, size=n)
stream = [(i, final[i]) for i in range(n)]
for i in r.integers(0, n, size=int(upd * n)): # 재할당: "x = 3 ... x = 5"
c = r.integers(0, ncode); stream.append((i, c)); final[i] = c
idx = np.array([i for i, _ in stream]); Vs = code[[c for _, c in stream]]
if rule == "attention": # 모든 쓰기를 보관: KV가 스트림만큼 자란다
score = K @ K[idx].T + 1e-6 * np.arange(len(stream)) # 날카로운 softmax + 최신 우선 (RoPE의 몫)
read = Vs[np.argmax(score, axis=1)] # softmax의 온도 0 극한
else:
S = np.zeros((dk, dv)) # 메모리 전체: d_k × d_v개
for i, vv in zip(idx, Vs):
k = K[i]
if rule == "linear":
S += np.outer(k, vv) # 덧셈 쓰기
else:
if rule == "gated delta":
S *= alpha # 전체를 조금씩 잊기
S += beta * np.outer(k, vv - S.T @ k) # k 아래 저장된 것을 교체
read = K @ S
acc.append(np.mean(np.argmax(read @ code.T, axis=1) == final))
return np.mean(acc)
ns = [8, 16, 32, 64, 128]
for upd in [0.0, 1.0]:
print(f"d_k = 32, state = 32x32 floats | re-writes = {upd:.0%} of n")
print(" n " + "".join(f"{n:>6}" for n in ns))
for rule in ["linear", "delta", "gated delta", "attention"]:
print(f" {rule:12s}" + "".join(f"{recall(rule, n, upd=upd):6.2f}" for n in ns))
print("delta, β=0.5, no re-writes" + "".join(f"{recall('delta', n, beta=0.5):6.2f}" for n in ns))
# linear attention의 crosstalk: Sᵀk_i = v_i + Σ_{j≠i} (k_j·k_i) v_j, k_j·k_i ~ N(0, 1/d_k)
for n in [8, 32, 128]:
print(f"linear attention, n={n:>3}: |noise|/|signal| ≈ sqrt((n-1)/d_k) = {np.sqrt((n - 1) / 32):.2f}")덮어쓰기 100%에서 linear attention은 에서 이미 71%다. 용량보다 한참 아래인데, 혼합된 값을 돌려주기 때문이다. delta rule은 거기서 완벽하다. 에서는 고정 상태 규칙 모두 20–25%인데 attention은 여전히 정확하다. 장난감의 “attention”은 이상화한 것이지만(온도 0, 실제 모델이 RoPE로 배우는 최신 우선 규칙) 그것이 보여 주는 비대칭, 즉 고정 상태 대 자라는 캐시는 실제다.
head 차원 d_k = 128인 순수 Gated DeltaNet 층이 100K 토큰 문맥에 흩어진 서로 다른 변수 바인딩 2,000개에 대해 답해야 한다. 옳은 것은?
상태는 행렬이고 읽기 는 에 선형이라, 간섭 없이 읽어 낼 수 있는 key 방향은 많아야 개다. 더 나은 규칙(delta, gate)은 어떤 연관이 살아남을지 정하고 메모리를 고칠 수 있게 할 뿐 rank를 올리지 못한다. head를 늘리면 용량이 선형으로 늘지만 그것이 곧 “더 큰 상태”의 비용이다. chunk 크기는 같은 함수를 어떻게 계산하느냐만 바꾼다. 하이브리드에 full attention 층이 있는 이유다.
하이브리드: full attention 층은 몇 개?
실제 배포된 설계는 모두 소수의 전역 softmax attention 층을 정확한 recall을 맡는 “닻(anchor)“으로 남기고(Nemotron Super 보고서의 표현) 나머지를 linear로 만든다. 공개된 config.json에서 가져온 구성은 이렇다.
| 모델 | Linear mixer | linear : full 층 | full attention 층 | linear 층당 상태 (값 개수) |
|---|---|---|---|---|
| Qwen3-Next-80B-A3B | Gated DeltaNet | 36 : 12 | gated GQA, KV head 2 × 256, partial RoPE | head 32 × 128 × 128 = 524K |
| Qwen3.8-Flash-Next | Gated DeltaNet | 36 : 12 | Qwen Sparse Attention (KV head 2 × 256) | 48 × 128 × 128 = 786K |
| Kimi Linear 48B-A3B | KDA | 20 : 7 | MLA, NoPE | 32 × 128 × 128 = 524K |
| Kimi K3 | KDA | 69 : 24 | gated MLA, NoPE | 96 × 128 × 128 = 1.57M |
| Nemotron 3 Ultra | Mamba-2 | 48 : 12 | GQA, KV head 2 × 128, 위치 임베딩 없음 | head 256 × 64 × 128 = 2.10M |
| MiniMax-M1 | lightning attention | 70 : 10 | GQA, KV head 8 × 128 | head 64 × 128 × 128 = 1.05M (config를 우리가 읽은 값) |
| MiniMax-M2 | — | 0 : 62 | GQA, KV head 8 × 128 | — |
시퀀스 하나의 decode 메모리는
이고 decode 한 step이 이것을 모두 한 번 읽으므로 같은 식이 토큰당 메모리 트래픽이다. 두 항은 에서 만난다. Qwen3-Next는 약 3K 토큰, Nemotron 3 Ultra는 33K 토큰이다(FP32 SSM 상태 403 MB 대 토큰당 KV 12 KB). 보다 짧으면 하이브리드가 같은 모양의 전부-attention 모델보다 상태를 더 많이 들고 있다.
Memory is the visible cost. The less visible ones decide whether a lab ships a hybrid:
- Quality is configuration- and evaluation-sensitive. The Qwen3.8-Next report’s controlled comparison (25B-A3B, Qwen3.5 structure, 1 full layer in 4) found the GDN hybrid ahead of all-full-attention on 8 of 9 benchmarks (average 53.81 vs 49.87; SWA hybrid 51.15). Kimi Linear claims to beat full attention “under fair comparisons”. MiniMax, at M2 scale, found hybrid sliding-window variants equal on MMLU and MATH but clearly worse on 128K retrieval (RULER CWE 72 vs 90) and long in-context learning, and went back to full attention (M2 lesson). Short benchmarks barely see the difference; long-context recall does.
- Infrastructure. A recurrent state is overwritten at every token, so there is no past to roll back to: speculative decoding with rejected drafts and prefix caching need explicit state snapshots (Nemotron 3 Ultra snapshots the SSM state per draft step and at fixed token intervals). MiniMax lists immature kernels, precision sensitivity and missing native prefix caching among its reasons for leaving linear attention.
- Precision. States are kept in FP32 (
mamba_ssm_dtype/mamba_ssm_cache_dtype: float32in the Qwen3.5, Qwen3.8 and Nemotron configs); KDA’s decay needs a floor so that stays inside BF16 range in the chunk kernel.
Qwen3-Next-80B has 36 GDN layers (32 heads × 128 × 128 state, FP32) and 12 attention layers (2 KV heads × 256, BF16). Roughly where does the fixed GDN state equal the KV cache of one sequence?
State: MB. KV per token: B. The ratio is tokens. (One GDN layer’s state equals about 1K tokens of one attention layer’s KV; with three GDN layers per attention layer the crossover is 3K.) Beyond that, the hybrid’s advantage grows linearly with context — at 256K its total is about 25% of a same-shape all-attention model.
Summary
- Linear attention is a fast-weight memory , read by . Linear attention, lightning attention, Mamba-2, GLA, DeltaNet, GDN and KDA differ only in the transition (identity, fixed decay, data-dependent scalar decay, per-channel decay, Householder-like replacement, or both).
- Mamba-2’s SSD duality: a scalar-decay SSM equals masked attention with a 1-semiseparable decay mask; .
- The chunkwise algorithm computes diagonal blocks as small masked matmuls and passes one state across chunk boundaries — a few percent more FLOPs than the recurrence, sequential steps, tensor cores. The delta rule adds one triangular solve per chunk (UT transform).
- A state holds about independent associations. Update rules change how recall fails (crosstalk, no overwrite, forgetting), not where; the delta rule’s real gift is editable memory.
- Hybrids keep 1 in 4 to 1 in 8 layers as full attention for exact recall; their memory is a growing KV term plus a fixed state, crossing at a few thousand to a few tens of thousands of tokens. Quality, rollback, prefix caching and precision are the costs that decide adoption.
메모리는 눈에 보이는 비용이다. 연구소가 하이브리드를 내놓을지를 정하는 것은 덜 보이는 비용들이다.
- 품질은 구성과 평가에 민감하다. Qwen3.8-Next 보고서의 통제 비교(25B-A3B, Qwen3.5 구조, 4층마다 full 1층)에서 GDN 하이브리드는 9개 중 8개 벤치마크에서 전부-full attention을 앞섰다(평균 53.81 대 49.87, SWA 하이브리드 51.15). Kimi Linear는 “공정한 비교에서” full attention을 이긴다고 주장한다. MiniMax는 M2 규모에서 하이브리드 sliding window 변형들이 MMLU·MATH에서는 같지만 128K 검색(RULER CWE 72 대 90)과 긴 in-context learning에서 분명히 나쁘다는 것을 보고 full attention으로 돌아갔다(M2 레슨). 짧은 벤치마크는 차이를 거의 못 보고, 긴 문맥 recall은 본다.
- 인프라. 순환 상태는 토큰마다 덮어쓰이므로 되돌아갈 과거가 없다. draft가 거절되는 speculative decoding과 prefix caching에는 명시적인 상태 snapshot이 필요하다(Nemotron 3 Ultra는 draft step마다, 그리고 일정 토큰 간격으로 SSM 상태를 snapshot한다). MiniMax는 미성숙한 커널, 정밀도 민감성, 네이티브 prefix caching 부재를 linear attention을 떠난 이유로 든다.
- 정밀도. 상태는 FP32로 둔다(Qwen3.5, Qwen3.8, Nemotron config의
mamba_ssm_dtype/mamba_ssm_cache_dtype: float32). KDA의 감쇠에는 chunk 커널에서 가 BF16 범위 안에 머물도록 하한이 필요하다.
Qwen3-Next-80B는 GDN 36층(상태 head 32 × 128 × 128, FP32)과 attention 12층(KV head 2 × 256, BF16)을 가진다. 시퀀스 하나에서 고정 GDN 상태와 KV cache가 같아지는 길이는 대략?
상태: MB. 토큰당 KV: B. 비는 약 토큰이다. (GDN 한 층의 상태는 attention 한 층의 KV 약 1K 토큰 분과 같고, attention 층 하나당 GDN 층이 셋이므로 교차점은 3K다.) 그 뒤로는 하이브리드의 이점이 문맥에 비례해 커진다. 256K에서 합계는 같은 모양의 전부-attention 모델의 약 25%다.
정리
- Linear attention은 로 쓰고 로 읽는 fast-weight 메모리다. linear attention, lightning attention, Mamba-2, GLA, DeltaNet, GDN, KDA는 전이 만 다르다(항등, 고정 감쇠, 데이터 의존 스칼라 감쇠, 채널별 감쇠, Householder 꼴 교체, 또는 둘 다).
- Mamba-2의 SSD 쌍대성: 스칼라 감쇠 SSM은 1-semiseparable 감쇠 마스크를 쓴 masked attention 와 같다. .
- chunk 알고리즘은 대각 블록을 작은 masked 행렬곱으로 계산하고 chunk 경계마다 상태 하나를 넘긴다. FLOPs는 순환형보다 몇 % 많지만 순차 단계는 번이고 tensor core에서 돈다. delta rule은 chunk마다 삼각 풀이 하나(UT transform)를 더한다.
- 상태는 독립적인 연관을 약 개 담는다. 갱신 규칙은 recall이 어떻게 무너지는지(crosstalk, 덮어쓰기 불가, 잊기)를 바꾸지 어디서를 바꾸지 않는다. delta rule의 진짜 선물은 고칠 수 있는 메모리다.
- 하이브리드는 4층에 1층에서 8층에 1층을 full attention으로 남겨 정확한 recall을 맡긴다. 메모리는 자라는 KV 항과 고정 상태의 합이고, 수천–수만 토큰에서 교차한다. 채택을 정하는 것은 품질, 되돌리기, prefix caching, 정밀도라는 비용이다.
더 읽을거리Further reading
- Katharopoulos et al., Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention (ICML 2020) — softmax를 커널 내적으로 바꾸면 attention이 순환 상태 하나로 접힌다는 출발점.The starting point — replace softmax by a kernel inner product and attention folds into one recurrent state.
- Schlag, Irie, Schmidhuber, Linear Transformers Are Secretly Fast Weight Programmers (ICML 2021) — 상태를 fast weight로 읽고, 용량 한계와 delta rule을 제안한 논문.Reads the state as fast weights, points out the capacity limit and proposes the delta rule.
- Yang et al., Parallelizing Linear Transformers with the Delta Rule over Sequence Length (NeurIPS 2024) — DeltaNet의 chunk 병렬 학습(WY/UT 표현). 이 레슨의 두 번째 유도의 원형.Chunkwise-parallel training of DeltaNet (WY/UT representation); the template for this lesson's second derivation.
- Yang, Kautz, Hatamizadeh, Gated Delta Networks: Improving Mamba2 with Delta Rule (ICLR 2025) — Mamba-2의 gate와 delta rule을 합친 GDN. Qwen3-Next·Qwen3.5·Qwen3.8의 linear 층.GDN — Mamba-2's gate plus the delta rule; the linear layer of Qwen3-Next, Qwen3.5 and Qwen3.8.
- Gu & Dao, Mamba: Linear-Time Sequence Modeling with Selective State Spaces (2023) — 입력에 따라 Δ, B, C가 바뀌는 선택적 SSM.The selective SSM — Δ, B and C depend on the input.
- Dao & Gu, Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (ICML 2024) — Mamba-2와 SSD. SSM = 1-semiseparable mask를 쓴 masked attention이라는 쌍대성과 chunk 알고리즘.Mamba-2 and SSD — an SSM is masked attention with a 1-semiseparable mask; the chunked algorithm.
- Kimi Team, Kimi Linear: An Expressive, Efficient Attention Architecture (2025) — KDA(채널별 decay)와 3:1 KDA:MLA 하이브리드. KV cache 최대 75% 감소, 1M 문맥 decode 최대 6배.KDA (channel-wise decay) and the 3:1 KDA:MLA hybrid; up to 75% less KV cache and up to 6× decode throughput at 1M context.
- Arora et al., Zoology: Measuring and Improving Recall in Efficient Language Models (2023); Simple linear attention language models balance the recall-throughput tradeoff (2024) — MQAR과, 상태 크기와 recall 사이의 trade-off. 이 레슨의 recall 실험의 원형.MQAR and the state-size/recall trade-off; the template for this lesson's recall experiment.
- Qin et al., Lightning Attention-2 (2024); MiniMax, MiniMax-01 / MiniMax-M1 (2025) — block 안은 마스크 행렬곱, block 사이는 누적 상태로 계산하는 lightning attention과 그 7:1 하이브리드.Lightning attention (masked matmul inside a block, accumulated state between blocks) and its 7:1 hybrid.