Track VII · Architecture Deep Dives · 05/12

Linear attention과 SSM — 고정 크기 상태로 문맥 압축하기Linear attention and SSMs — compressing context into a fixed-size state

linear attention을 outer-product fast-weight 메모리로 보고, delta rule → Gated DeltaNet → KDA, Mamba → Mamba-2의 SSD 쌍대성(state space ↔ masked attention), lightning attention을 하나의 점화식 가족으로 묶는다. chunk 병렬 알고리즘을 유도해 NumPy로 순환형과 일치를 확인하고, associative recall 실험으로 고정 상태의 용량 한계를 재며, 실제 config로 하이브리드 비율별 메모리를 계산해 왜 full attention 층을 일부 남기는지 본다.Read linear attention as an outer-product fast-weight memory and put the delta rule → Gated DeltaNet → KDA, Mamba → Mamba-2's SSD duality (state space ↔ masked attention) and lightning attention into one family of recurrences. Derive the chunkwise-parallel algorithm and check it against the recurrence in NumPy, measure the capacity limit of a fixed state with an associative-recall experiment, and compute memory per hybrid ratio from real configs to see why hybrids keep some full-attention layers.

60 분min linear attention · state space model · Mamba · Mamba-2 · SSD · DeltaNet · Gated DeltaNet · KDA · lightning attention · chunkwise · hybrid · associative recall 먼저 볼 것:Before this: Attention: query·key·valueAttention: query, key, value, 순환 신경망과 LSTMRecurrent networks and LSTM, Attention과 KV: MHA → GQA → MLA, sliding window·sink, local/globalAttention and KV: MHA → GQA → MLA, sliding windows and sinks, local/global

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 tt, a softmax attention layer computes ot=∑s≤tsoftmax⁡s(qt⊤ks/d) vso_t=\sum_{s\le t}\operatorname{softmax}_s(q_t^\top k_s/\sqrt d)\,v_s. It must read all tt 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 hth_t instead, so decode is O(1)O(1) 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 O(1)O(1) 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 exp⁡(q⊤k)\exp(q^\top k) by a feature-map inner product ϕ(q)⊤ϕ(k)\phi(q)^\top\phi(k), as Katharopoulos et al. did; modern layers simply use normalised q,kq,k directly). Then associativity lets us move the brackets:

ot=∑s≤t(qt⊤ks) vs=(∑s≤tvsks⊤)qt=St⊤qt,St=St−1+ktvt⊤∈Rdk×dv.o_t=\sum_{s\le t}(q_t^\top k_s)\,v_s=\Big(\sum_{s\le t}v_s k_s^\top\Big)q_t = S_t^\top q_t,\qquad S_t=S_{t-1}+k_t v_t^\top\in\mathbb R^{d_k\times d_v}.

StS_t 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 (QK⊤⊙M)V(QK^\top\odot M)V with a causal mask MM; decoding uses the recurrence, reading and writing dkdvd_kd_v numbers per head per token, independent of tt.

What can it remember? Write nn pairs and read with a stored key kik_i (∥k∥=1\|k\|=1):

S⊤ki=vi+∑j≠i(kj⊤ki) vj.S^\top k_i=v_i+\sum_{j\ne i}(k_j^\top k_i)\,v_j .

The second term is crosstalk. If the keys are orthonormal it vanishes — but Rdk\mathbb R^{d_k} holds at most dkd_k orthonormal vectors, so a dk×dvd_k\times d_v state stores at most dkd_k independent associations. For random unit keys kj⊤ki∼N(0,1/dk)k_j^\top k_i\sim\mathcal N(0,1/d_k), so the crosstalk-to-signal ratio is about (n−1)/dk\sqrt{(n-1)/d_k}: recall degrades smoothly as nn approaches dkd_k. 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 MtM_t applied to the old state before writing:

St=Mt St−1+βt ktvt⊤(or the delta form below),ot=St⊤qt.S_t = M_t\,S_{t-1} + \beta_t\,k_t v_t^\top \quad(\text{or the delta form below}),\qquad o_t=S_t^\top q_t .
LayerTransition MtM_tWriteForgettingUsed in
Linear attentionIIktvt⊤k_tv_t^\topnone—
RetNet, Lightning Attention-2λI\lambda I (fixed per head)ktvt⊤k_tv_t^\topfixed exponentialMiniMax-01/M1 (lightning)
Mamba-2 (SSD)atIa_t I, at=e−ΔtAa_t=e^{-\Delta_t A} data-dependent scalarBtxt⊤B_tx_t^\topinput-dependent, one rate per headNemotron-H, Nemotron 3
GLA-styleDiag⁡(αt)\operatorname{Diag}(\boldsymbol\alpha_t)ktvt⊤k_tv_t^\topper key channel—
DeltaNetI−βtktkt⊤I-\beta_tk_tk_t^\topβtktvt⊤\beta_tk_tv_t^\topreplaces the value under ktk_t—
Gated DeltaNetαt(I−βtktkt⊤)\alpha_t(I-\beta_tk_tk_t^\top)βtktvt⊤\beta_tk_tv_t^\topscalar gate + replacementQwen3-Next, Qwen3.5, Qwen3.8
KDA(I−βtktkt⊤)Diag⁡(αt)(I-\beta_tk_tk_t^\top)\operatorname{Diag}(\boldsymbol\alpha_t)βtktvt⊤\beta_tk_tv_t^\topper-channel gate + replacementKimi Linear, Kimi K3

Two readings of the same table are useful.

  • Online learning. The state is the weight of a linear regressor k↦vk\mapsto v trained online, one step per token. Linear attention is gradient ascent on ⟨S⊤kt,vt⟩\langle S^\top k_t,v_t\rangle (it only adds); the delta rule is one SGD step with learning rate βt\beta_t on 12∥S⊤kt−vt∥2\tfrac12\|S^\top k_t-v_t\|^2, whose gradient is kt(S⊤kt−vt)⊤k_t(S^\top k_t-v_t)^\top — so with ∥kt∥=1,βt=1\|k_t\|=1,\beta_t=1 the key’s old value is replaced. The gate αt\alpha_t 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 I−βkk⊤I-\beta k k^\top are 11 (on k⊥k^\perp) and 1−β∥k∥21-\beta\|k\|^2. With L2L_2-normalised keys and β∈(0,1)\beta\in(0,1) they lie in [0,1][0,1]: the transition never amplifies, which is why every delta-rule layer normalises qq and kk. Gates multiply by numbers in (0,1)(0,1), 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 h′(τ)=Ah(τ)+Bx(τ)h'(\tau)=Ah(\tau)+Bx(\tau), y=Chy=Ch, discretised with step Δ\Delta (zero-order hold on AA), becomes

ht=Aˉtht−1+Bˉtxt,yt=Ctht,Aˉt=exp⁡(ΔtA),  Bˉt≈ΔtBt.h_t=\bar A_t h_{t-1}+\bar B_t x_t,\qquad y_t=C_t h_t,\qquad \bar A_t=\exp(\Delta_t A),\ \ \bar B_t\approx\Delta_t B_t .

Classic SSMs (S4) keep A,B,C,ΔA,B,C,\Delta 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 Δt,Bt,Ct\Delta_t,B_t,C_t functions of the current input (a selective SSM): a large Δt\Delta_t resets the state and absorbs xtx_t, a small one ignores the token. Mamba-1 runs a separate diagonal SSM with a small state (default N=16N=16) for every channel, computed with a hardware-aware parallel scan.

Mamba-2 restricts Aˉt\bar A_t to a scalar times identity, atIa_tI, shared by a head of PP channels (the SSD paper says P∈{64,128}P\in\{64,128\} is typical). The per-head state becomes a P×NP\times N matrix:

ht=at ht−1+xtBt⊤,yt=ht Ct,xt∈RP, Bt,Ct∈RN.h_t=a_t\,h_{t-1}+x_tB_t^\top,\qquad y_t=h_t\,C_t,\qquad x_t\in\mathbb R^{P},\ B_t,C_t\in\mathbb R^{N}.

Put St=ht⊤S_t=h_t^\top and compare with the table: this is exactly decayed linear attention with q↔Cq\leftrightarrow C, k↔Bk\leftrightarrow B, v↔xv\leftrightarrow x and a data-dependent scalar decay. Nemotron 3 Ultra’s config makes it concrete: 256 Mamba heads per layer, P=64P=64, N=128N=128 (mamba_head_dim, ssm_state_size), a 64×12864\times128 state per head.

The SSD duality: a state-space model is masked attention

Unroll the scalar-decay recurrence from S0=0S_0=0:

St=∑s≤t(∏r=s+1tar)ksvs⊤⟹ot=∑s≤t(∏r=s+1tar)⏟Lts(qt⊤ks) vs.S_t=\sum_{s\le t}\Big(\prod_{r=s+1}^{t}a_r\Big)k_s v_s^\top \quad\Longrightarrow\quad o_t=\sum_{s\le t}\underbrace{\Big(\prod_{r=s+1}^{t}a_r\Big)}_{L_{ts}}(q_t^\top k_s)\,v_s .

Stacking all tt: O=(L∘QK⊤) VO=(L\circ QK^\top)\,V, with Lts=as+1⋯atL_{ts}=a_{s+1}\cdots a_t for s≤ts\le t and 00 otherwise. That is masked attention without a softmax, where the mask LL 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 M=L∘(CB⊤)M=L\circ(CB^\top) with Mts=Ct⊤(at⋯as+1)BsM_{ts}=C_t^\top(a_t\cdots a_{s+1})B_s, and LL is 1-semiseparable: every submatrix strictly below the diagonal has rank 1, because Lts=γt/γsL_{ts}=\gamma_t/\gamma_s with γt=∏r≤tar\gamma_t=\prod_{r\le t}a_r. Consequently every off-diagonal block of MM has rank at most NN.

The same matrix can be applied in two ways — that is the duality:

  • linear (recurrent) mode: O(TNP)O(TNP) FLOPs, O(NP)O(NP) state, but TT dependent steps;
  • quadratic (attention) mode: form MM explicitly, O(T2N)O(T^2N) 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 단계 tt에서 softmax attention 층은 ot=∑s≤tsoftmax⁡s(qt⊤ks/d) vso_t=\sum_{s\le t}\operatorname{softmax}_s(q_t^\top k_s/\sqrt d)\,v_s를 계산한다. 캐시된 key와 value tt개를 모두 읽어야 하므로 토큰당 연산과 메모리 트래픽이 문맥에 비례해 늘고, 캐시 자체도 메모리에서 선형으로 자란다(Track III 추론 레슨). 20만 토큰짜리 agent 궤적에서는 그 읽기가 곧 decode 비용이다.

RNN은 고정 크기 hth_t를 들고 다니므로 decode가 토큰당 O(1)O(1)이다. 하지만 Track II에서 본 것처럼 고전 RNN은 시간 방향으로 병렬 학습이 안 되고 과거 전체를 벡터 하나로 짜낸다. 이 레슨의 설계들은 RNN의 O(1)O(1) decode를 유지하면서 (a) 상태를 key→value 연관을 저장하는 행렬로 만들고 (b) 학습은 병렬로 유지한다.

Linear attention은 fast-weight 메모리다

softmax를 빼면(또는 Katharopoulos et al.처럼 exp⁡(q⊤k)\exp(q^\top k)를 feature map 내적 ϕ(q)⊤ϕ(k)\phi(q)^\top\phi(k)로 바꾸면. 최신 층들은 정규화한 q,kq,k를 그대로 쓴다) 결합법칙으로 괄호를 옮길 수 있다.

ot=∑s≤t(qt⊤ks) vs=(∑s≤tvsks⊤)qt=St⊤qt,St=St−1+ktvt⊤∈Rdk×dv.o_t=\sum_{s\le t}(q_t^\top k_s)\,v_s=\Big(\sum_{s\le t}v_s k_s^\top\Big)q_t = S_t^\top q_t,\qquad S_t=S_{t-1}+k_t v_t^\top\in\mathbb R^{d_k\times d_v}.

StS_t는 fast weight다. outer product로 쓰고 행렬-벡터 곱으로 읽는 행렬, 즉 선형 연상 메모리다(Schlag et al. 2021). 학습은 causal mask MM을 쓴 병렬형 (QK⊤⊙M)V(QK^\top\odot M)V로, decode는 점화식으로 한다. head·토큰마다 dkdvd_kd_v개 숫자를 읽고 쓰며, tt와 무관하다.

무엇을 기억할 수 있나. 쌍 nn개를 쓰고 저장된 key kik_i(∥k∥=1\|k\|=1)로 읽으면

S⊤ki=vi+∑j≠i(kj⊤ki) vj.S^\top k_i=v_i+\sum_{j\ne i}(k_j^\top k_i)\,v_j .

둘째 항이 crosstalk다. key가 정규직교면 사라지지만 Rdk\mathbb R^{d_k}에는 정규직교 벡터가 많아야 dkd_k개다. 그러므로 dk×dvd_k\times d_v 상태는 독립적인 연관을 많아야 dkd_k개 저장한다. 무작위 단위 key에서는 kj⊤ki∼N(0,1/dk)k_j^\top k_i\sim\mathcal N(0,1/d_k)이므로 crosstalk 대 신호 비가 약 (n−1)/dk\sqrt{(n-1)/d_k}이고, nn이 dkd_k에 다가갈수록 recall이 서서히 무너진다. 덧셈 쓰기에서 실패 유형이 둘 더 나온다. 두 번 쓴 key는 두 값의 합을 돌려주고(덮어쓰기 불가), 아무것도 잊지 않으므로 상태의 norm이 끝없이 커진다.

점화식 하나, 전이 행렬 여럿

이 레슨의 모든 층은 같은 점화식이고, 쓰기 전에 옛 상태에 곱하는 전이(transition) MtM_t만 다르다.

St=Mt St−1+βt ktvt⊤(또는 아래의 delta 꼴),ot=St⊤qt.S_t = M_t\,S_{t-1} + \beta_t\,k_t v_t^\top \quad(\text{또는 아래의 delta 꼴}),\qquad o_t=S_t^\top q_t .
층전이 MtM_t쓰기잊기쓰는 곳
Linear attentionIIktvt⊤k_tv_t^\top없음—
RetNet, Lightning Attention-2λI\lambda I (head별 고정)ktvt⊤k_tv_t^\top고정 지수 감쇠MiniMax-01/M1 (lightning)
Mamba-2 (SSD)atIa_t I, at=e−ΔtAa_t=e^{-\Delta_t A} 데이터 의존 스칼라Btxt⊤B_tx_t^\top입력 의존, head당 한 비율Nemotron-H, Nemotron 3
GLA 계열Diag⁡(αt)\operatorname{Diag}(\boldsymbol\alpha_t)ktvt⊤k_tv_t^\topkey 채널별—
DeltaNetI−βtktkt⊤I-\beta_tk_tk_t^\topβtktvt⊤\beta_tk_tv_t^\topktk_t 아래 값을 교체—
Gated DeltaNetαt(I−βtktkt⊤)\alpha_t(I-\beta_tk_tk_t^\top)βtktvt⊤\beta_tk_tv_t^\top스칼라 gate + 교체Qwen3-Next, Qwen3.5, Qwen3.8
KDA(I−βtktkt⊤)Diag⁡(αt)(I-\beta_tk_tk_t^\top)\operatorname{Diag}(\boldsymbol\alpha_t)βtktvt⊤\beta_tk_tv_t^\top채널별 gate + 교체Kimi Linear, Kimi K3

같은 표를 두 가지로 읽을 수 있다.

  • 온라인 학습. 상태는 k↦vk\mapsto v 선형 회귀기의 가중치이고, 토큰마다 한 step씩 온라인으로 학습된다. linear attention은 ⟨S⊤kt,vt⟩\langle S^\top k_t,v_t\rangle에 대한 경사 상승(더하기만 한다)이고, delta rule은 12∥S⊤kt−vt∥2\tfrac12\|S^\top k_t-v_t\|^2에 학습률 βt\beta_t로 한 SGD step이다. 기울기가 kt(S⊤kt−vt)⊤k_t(S^\top k_t-v_t)^\top이므로 ∥kt∥=1,βt=1\|k_t\|=1,\beta_t=1이면 그 key의 옛 값이 교체된다. gate αt\alpha_t는 fast weight의 weight decay다. 유도는 Qwen3-Next 레슨에, KDA의 채널별 gate와 decay 하한은 K3 레슨에 있다.
  • 안정성. I−βkk⊤I-\beta k k^\top의 고유값은 11(k⊥k^\perp 위)과 1−β∥k∥21-\beta\|k\|^2이다. L2L_2 정규화한 key와 β∈(0,1)\beta\in(0,1)이면 [0,1][0,1] 안에 있어 전이가 절대 증폭하지 않는다. delta rule 층이 모두 q,kq,k를 정규화하는 이유다. gate는 (0,1)(0,1)의 수를 곱하므로 전이들의 곱은 축소 사상이다.

선택적 상태공간: Mamba와 Mamba-2

상태공간 모델(SSM)은 제어이론에서 출발해 같은 곳에 닿는다. 연속 선형계 h′(τ)=Ah(τ)+Bx(τ)h'(\tau)=Ah(\tau)+Bx(\tau), y=Chy=Ch를 step Δ\Delta로 이산화하면(AA는 zero-order hold)

ht=Aˉtht−1+Bˉtxt,yt=Ctht,Aˉt=exp⁡(ΔtA),  Bˉt≈ΔtBt.h_t=\bar A_t h_{t-1}+\bar B_t x_t,\qquad y_t=C_t h_t,\qquad \bar A_t=\exp(\Delta_t A),\ \ \bar B_t\approx\Delta_t B_t .

고전 SSM(S4)은 A,B,C,ΔA,B,C,\Delta가 고정이라 층이 긴 convolution이 된다. 하지만 고정 필터는 내용을 보고 무엇을 남길지 정할 수 없다. Mamba(Gu & Dao 2023)는 Δt,Bt,Ct\Delta_t,B_t,C_t를 현재 입력의 함수로 만든다(선택적 SSM). Δt\Delta_t가 크면 상태를 리셋하고 xtx_t를 흡수하며, 작으면 그 토큰을 무시한다. Mamba-1은 채널마다 작은 상태(기본 N=16N=16)의 대각 SSM을 따로 돌리고, 하드웨어를 고려한 병렬 scan으로 계산한다.

Mamba-2는 Aˉt\bar A_t를 스칼라 곱하기 항등행렬 atIa_tI로 제한하고, 이를 채널 PP개짜리 head가 공유한다(SSD 논문은 P∈{64,128}P\in\{64,128\}이 보통이라고 쓴다). head별 상태는 P×NP\times N 행렬이 된다.

ht=at ht−1+xtBt⊤,yt=ht Ct,xt∈RP, Bt,Ct∈RN.h_t=a_t\,h_{t-1}+x_tB_t^\top,\qquad y_t=h_t\,C_t,\qquad x_t\in\mathbb R^{P},\ B_t,C_t\in\mathbb R^{N}.

St=ht⊤S_t=h_t^\top로 두고 표와 비교하면 정확히 감쇠가 있는 linear attention이다. q↔Cq\leftrightarrow C, k↔Bk\leftrightarrow B, v↔xv\leftrightarrow x, 그리고 데이터 의존 스칼라 감쇠. Nemotron 3 Ultra의 config로 구체화하면 층당 Mamba head 256개, P=64P=64, N=128N=128(mamba_head_dim, ssm_state_size)로 head마다 64×12864\times128 상태다.

SSD 쌍대성: 상태공간 모델은 masked attention이다

스칼라 감쇠 점화식을 S0=0S_0=0부터 펼치면

St=∑s≤t(∏r=s+1tar)ksvs⊤⟹ot=∑s≤t(∏r=s+1tar)⏟Lts(qt⊤ks) vs.S_t=\sum_{s\le t}\Big(\prod_{r=s+1}^{t}a_r\Big)k_s v_s^\top \quad\Longrightarrow\quad o_t=\sum_{s\le t}\underbrace{\Big(\prod_{r=s+1}^{t}a_r\Big)}_{L_{ts}}(q_t^\top k_s)\,v_s .

모든 tt를 쌓으면 O=(L∘QK⊤) VO=(L\circ QK^\top)\,V이고, s≤ts\le t에서 Lts=as+1⋯atL_{ts}=a_{s+1}\cdots a_t, 나머지는 00이다. softmax 없는 masked attention인데, 마스크 LL이 단순한 causal 마스크가 아니라 학습되는 입력 의존 감쇠다. 모델의 위치 정보이기도 하다. SSD 논문의 말로는 시퀀스 사상이 행렬 M=L∘(CB⊤)M=L\circ(CB^\top), Mts=Ct⊤(at⋯as+1)BsM_{ts}=C_t^\top(a_t\cdots a_{s+1})B_s이고, LL은 1-semiseparable이다. γt=∏r≤tar\gamma_t=\prod_{r\le t}a_r로 쓰면 Lts=γt/γsL_{ts}=\gamma_t/\gamma_s라서 대각선 아래의 모든 부분행렬의 rank가 1이다. 그래서 MM의 비대각 블록은 rank가 NN 이하다.

같은 행렬을 두 가지로 적용할 수 있다는 것이 쌍대성이다.

  • 선형(순환) 모드: FLOPs O(TNP)O(TNP), 상태 O(NP)O(NP), 하지만 서로 의존하는 TT단계;
  • 2차(attention) 모드: MM을 직접 만들어 FLOPs O(T2N)O(T^2N), 완전히 병렬인 행렬곱.

긴 시퀀스 학습에는 둘 다 좋지 않다. 아래의 chunk 알고리즘은 각각을 싼 곳에서 쓴다.

순차 단계sequential steps – FLOPs/토큰 (chunk)FLOPs/token (chunked) – vs 순환형vs recurrent – vs 2차 형태vs quadratic form –
Left: the 32×32 matrix that maps inputs to outputs in decayed linear attention / Mamba-2, Mts = (as+1⋯at)·qt·ks (shade = |M|). Drag the chunk size: blue diagonal blocks are computed exactly like small causal attention; the hatched off-diagonal blocks have rank ≤ dk and are never materialised — their effect travels through one dk×dv state per chunk boundary. Lower the retention a and the matrix fades away from the diagonal (the decay is the positional mask). Right: FLOPs per token per head (dk = dv = 128) for the chosen length. C = 1 is the pure recurrence (fewest FLOPs, but T sequential, memory-bound steps); C = T is the quadratic “attention” form. (Beyond C = 32 the toy matrix is a single block.) Real kernels pick C = 64–256: a few percent more FLOPs, all of it tensor-core matmuls, and only T/C sequential steps. 왼쪽은 감쇠가 있는 linear attention / Mamba-2에서 입력을 출력으로 보내는 32×32 행렬 Mts = (as+1⋯at)·qt·ks이다(색 = |M|). chunk 크기를 끌어 보면 파란 대각 블록은 작은 causal attention처럼 정확히 계산하고, 빗금 친 비대각 블록은 rank ≤ dk라서 만들지 않는다. 그 효과는 chunk 경계마다 dk×dv 상태 하나로 전달된다. 보존율 a를 낮추면 대각선에서 멀어질수록 행렬이 옅어진다(감쇠가 곧 위치 마스크다). 오른쪽은 고른 길이에서 head 하나의 토큰당 FLOPs(dk = dv = 128)다. C = 1은 순수 순환(FLOPs 최소, 그러나 T번의 순차적·메모리 병목 단계), C = T는 2차 "attention" 형태다. (C가 32를 넘으면 왼쪽 장난감 행렬은 블록 하나다.) 실제 커널은 C = 64–256을 고른다. FLOPs는 몇 % 늘지만 전부 tensor core 행렬곱이고 순차 단계는 T/C번뿐이다.

The chunkwise-parallel algorithm

Split the sequence into chunks of length CC. Inside a chunk index positions r=1..Cr=1..C, let S0S_0 be the state entering the chunk and γr=∏u≤rau\gamma_r=\prod_{u\le r}a_u the decay accumulated since the chunk start. Unrolling only within the chunk,

Sr=γrS0+∑s≤rγrγs ksvs⊤,or=γr S0⊤qr⏟inter-chunk+∑s≤rγrγs(qr⊤ks) vs⏟intra-chunk.S_r=\gamma_r S_0+\sum_{s\le r}\frac{\gamma_r}{\gamma_s}\,k_sv_s^\top ,\qquad o_r=\underbrace{\gamma_r\,S_0^\top q_r}_{\text{inter-chunk}}+\underbrace{\sum_{s\le r}\frac{\gamma_r}{\gamma_s}(q_r^\top k_s)\,v_s}_{\text{intra-chunk}} .

In matrix form, for chunk [c][c] with Q,K,V∈RC×dQ,K,V\in\mathbb R^{C\times d} and Γ=diag⁡(γ)\Gamma=\operatorname{diag}(\gamma):

O[c]=Γ Q S[c]+(L(c)∘QK⊤)V,S[c+1]=γC S[c]+(K⊙γCγ) ⁣⊤V.O_{[c]}=\Gamma\,Q\,S_{[c]}+\big(L^{(c)}\circ QK^\top\big)V,\qquad S_{[c+1]}=\gamma_C\,S_{[c]}+\big(K\odot\tfrac{\gamma_C}{\gamma}\big)^{\!\top}V .

Everything is a matmul on C×dC\times d tiles except one tiny loop over T/CT/C chunk boundaries. Per token and head that costs ≈C(dk+dv)\approx C(d_k+d_v) FLOPs for the intra-chunk term plus 4dkdv4d_kd_v for the state read and update — versus 4dkdv4d_kd_v for the pure recurrence and T(dk+dv)T(d_k+d_v) for the quadratic form. With C=64C=64 and d=128d=128: 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 [(QiKi⊤)⊙M]Vi[(Q_iK_i^\top)\odot M]V_i with Mts=λt−sM_{ts}=\lambda^{t-s}, inter-block ΛQi(KV)\Lambda Q_i(KV), and KV←λBKV+(λBΛ−1Ki)⊤ViKV\leftarrow\lambda^BKV+(\lambda^B\Lambda^{-1}K_i)^\top V_i — the fixed-decay special case at=λa_t=\lambda.

Adding the delta rule. For GDN the write depends on the state, ur=βr(vr−αrSr−1⊤kr)u_r=\beta_r\big(v_r-\alpha_rS_{r-1}^\top k_r\big), so the “values” written into the chunk are not known in advance. Unroll it inside the chunk exactly as above, Sr=γrS0+∑s≤rγrγsksus⊤S_r=\gamma_rS_0+\sum_{s\le r}\tfrac{\gamma_r}{\gamma_s}k_su_s^\top, and substitute:

ur+βr∑s<rγrγs(kr⊤ks) us=βr(vr−γrS0⊤kr)⟺(I+diag⁡(β)A) U=diag⁡(β) (V−ΓKS0),u_r+\beta_r\sum_{s<r}\frac{\gamma_r}{\gamma_s}(k_r^\top k_s)\,u_s=\beta_r\big(v_r-\gamma_r S_0^\top k_r\big) \quad\Longleftrightarrow\quad (I+\operatorname{diag}(\beta)A)\,U=\operatorname{diag}(\beta)\,(V-\Gamma KS_0),

with Ars=γrγskr⊤ksA_{rs}=\tfrac{\gamma_r}{\gamma_s}k_r^\top k_s strictly lower-triangular. I+diag⁡(β)AI+\operatorname{diag}(\beta)A is unit lower-triangular, so UU costs one C×CC\times C triangular solve (the UT transform; DeltaNet’s WY representation is the same object). Then UU plays the role of VV in the formulas above. The K3 lesson does the same with a per-channel decay and explains why its 1/Γ1/\Gamma needs a floor.

NumPy One family, three algorithms: recurrent = quadratic (SSD) = chunkwise; and the delta rule via the UT transform
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 T/CT/C chunks is sequential. Production kernels (FLA’s Triton kernels, mamba_ssm’s chunked scan, Qwen’s TileLang-based FlashQLA) fuse these four steps.

PyTorch PyTorch: chunked SSD / decayed linear attention, checked against the recurrence 로컬에서 실행run locally (pip install torch)
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 True
 

How much can a dk×dvd_k\times d_v state remember?

The capacity argument says a fixed state holds about dkd_k 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 NN from 16 to 64 to 256 consistently helps. The figure below is a toy MQAR you can run with different rules.

chunk 병렬 알고리즘

시퀀스를 길이 CC의 chunk로 나눈다. chunk 안의 위치를 r=1..Cr=1..C, chunk에 들어오는 상태를 S0S_0, chunk 시작 이후 누적된 감쇠를 γr=∏u≤rau\gamma_r=\prod_{u\le r}a_u라 하자. chunk 안에서만 펼치면

Sr=γrS0+∑s≤rγrγs ksvs⊤,or=γr S0⊤qr⏟chunk 사이+∑s≤rγrγs(qr⊤ks) vs⏟chunk 안.S_r=\gamma_r S_0+\sum_{s\le r}\frac{\gamma_r}{\gamma_s}\,k_sv_s^\top ,\qquad o_r=\underbrace{\gamma_r\,S_0^\top q_r}_{\text{chunk 사이}}+\underbrace{\sum_{s\le r}\frac{\gamma_r}{\gamma_s}(q_r^\top k_s)\,v_s}_{\text{chunk 안}} .

chunk [c][c]의 Q,K,V∈RC×dQ,K,V\in\mathbb R^{C\times d}와 Γ=diag⁡(γ)\Gamma=\operatorname{diag}(\gamma)로 행렬 꼴로 쓰면

O[c]=Γ Q S[c]+(L(c)∘QK⊤)V,S[c+1]=γC S[c]+(K⊙γCγ) ⁣⊤V.O_{[c]}=\Gamma\,Q\,S_{[c]}+\big(L^{(c)}\circ QK^\top\big)V,\qquad S_{[c+1]}=\gamma_C\,S_{[c]}+\big(K\odot\tfrac{\gamma_C}{\gamma}\big)^{\!\top}V .

T/CT/C개 chunk 경계를 도는 작은 루프 하나만 빼면 모두 C×dC\times d tile 위의 행렬곱이다. head·토큰당 비용은 chunk 안 항이 약 C(dk+dv)C(d_k+d_v) FLOPs, 상태 읽기와 갱신이 4dkdv4d_kd_v다. 순수 순환형은 4dkdv4d_kd_v, 2차 형태는 T(dk+dv)T(d_k+d_v)다. C=64C=64, d=128d=128이면 순환형 66 KFLOPs 대비 82 KFLOPs지만 순차 단계가 64배 적고 tensor core 위에서 돈다. 이것이 정확히 SSD의 4단계 알고리즘(대각 블록, chunk 상태, 상태 전달, 상태로부터의 출력)이고, 정확히 Lightning Attention-2다. block 안은 Mts=λt−sM_{ts}=\lambda^{t-s}인 [(QiKi⊤)⊙M]Vi[(Q_iK_i^\top)\odot M]V_i, block 사이는 ΛQi(KV)\Lambda Q_i(KV), 그리고 KV←λBKV+(λBΛ−1Ki)⊤ViKV\leftarrow\lambda^BKV+(\lambda^B\Lambda^{-1}K_i)^\top V_i. 고정 감쇠 at=λa_t=\lambda인 특수한 경우다.

delta rule 더하기. GDN에서는 쓰는 값이 상태에 의존한다. ur=βr(vr−αrSr−1⊤kr)u_r=\beta_r\big(v_r-\alpha_rS_{r-1}^\top k_r\big)이므로 chunk에 쓰일 “값”을 미리 알 수 없다. 위와 똑같이 chunk 안에서 Sr=γrS0+∑s≤rγrγsksus⊤S_r=\gamma_rS_0+\sum_{s\le r}\tfrac{\gamma_r}{\gamma_s}k_su_s^\top로 펼쳐 대입하면

ur+βr∑s<rγrγs(kr⊤ks) us=βr(vr−γrS0⊤kr)⟺(I+diag⁡(β)A) U=diag⁡(β) (V−ΓKS0)u_r+\beta_r\sum_{s<r}\frac{\gamma_r}{\gamma_s}(k_r^\top k_s)\,u_s=\beta_r\big(v_r-\gamma_r S_0^\top k_r\big) \quad\Longleftrightarrow\quad (I+\operatorname{diag}(\beta)A)\,U=\operatorname{diag}(\beta)\,(V-\Gamma KS_0)

이고 Ars=γrγskr⊤ksA_{rs}=\tfrac{\gamma_r}{\gamma_s}k_r^\top k_s는 순하삼각이다. I+diag⁡(β)AI+\operatorname{diag}(\beta)A는 대각이 1인 하삼각이므로 UU는 C×CC\times C 삼각 풀이 한 번이면 된다(UT transform. DeltaNet의 WY 표현과 같은 대상이다). 그다음 UU가 위 식의 VV 역할을 한다. K3 레슨은 채널별 감쇠로 같은 일을 하고, 거기서 1/Γ1/\Gamma에 하한이 필요한 이유를 설명한다.

NumPy 한 가족, 세 알고리즘: 순환형 = 2차형(SSD) = chunk형, 그리고 UT transform으로 푼 delta rule
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로 처리하고, T/CT/C개 chunk를 도는 상태 전달 루프만 순차적이다. 실제 커널(FLA의 Triton 커널, mamba_ssm의 chunk scan, Qwen의 TileLang 기반 FlashQLA)은 이 네 단계를 융합한다.

PyTorch PyTorch: chunk형 SSD / 감쇠 linear attention과 순환형 대조 로컬에서 실행run locally (pip install torch)
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
 

dk×dvd_k\times d_v 상태는 얼마나 기억하나

용량 논증은 갱신 규칙과 상관없이 고정 상태가 독립적인 연관을 약 dkd_k개 담는다고 말한다. 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에서 NN을 16 → 64 → 256으로 키우면 일관되게 좋아진다. 아래 그림은 규칙을 바꿔 가며 돌려 볼 수 있는 장난감 MQAR이다.

n = dk → linear – delta – gated delta – attention – 상태state –
A toy multi-query associative recall. n distinct random keys are written with values into one dk×32 matrix (then a fraction of them is re-written with new values); every key is read back and decoded to the nearest of 64 codebook values. Change dk: all three fixed-size rules break down around n ≈ dk — a dk×dv matrix cannot hold more than dk independent key directions. Turn up the re-writes: linear attention can only add, so it returns a blend of old and new values; the delta rule replaces the value under a key and wins. With β = 1 the delta rule also erases old content along every new key, so on distinct keys it trails linear attention — lower β to trade plasticity for retention. Correlated keys hurt linear attention most. Softmax attention keeps every write (its KV cache grows with n) and stays near 100% throughout — the reason hybrids keep some full-attention layers. 장난감 multi-query associative recall이다. 서로 다른 무작위 key n개를 값과 함께 dk×32 행렬 하나에 쓰고(그다음 일부 key를 새 값으로 다시 쓴다), 모든 key로 다시 읽어 64개 codebook 값 중 가장 가까운 것으로 해독한다. dk를 바꿔 보면 고정 크기 규칙 셋 모두 n ≈ dk 근처에서 무너진다. dk×dv 행렬은 독립적인 key 방향을 dk개보다 많이 담을 수 없다. 덮어쓰기 비율을 올리면 더하기만 하는 linear attention은 옛 값과 새 값의 혼합을 돌려주고, key 아래의 값을 교체하는 delta rule이 이긴다. β = 1의 delta rule은 새 key 방향마다 옛 내용도 지우므로 서로 다른 key만 쓸 때는 linear attention보다 뒤처진다. β를 낮추면 가소성과 보존을 맞바꾼다. 상관된 key는 linear attention을 가장 크게 해친다. softmax attention은 모든 쓰기를 보관하므로(KV cache가 n에 비례) 끝까지 100% 근처다. 하이브리드가 full attention 층을 일부 남기는 이유다.

What to take away from the figure:

  1. The wall is at n≈dkn\approx d_k 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%.
  2. The delta rule is not “more capacity”, it is “editable memory”. With distinct keys and β=1\beta=1 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. β<1\beta<1 trades plasticity for retention; making βt\beta_t data-dependent lets the model choose per token.
  3. 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.
NumPy Toy MQAR: recall vs number of keys, with and without re-writes
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 n=8n=8 — far below its capacity — because it returns blends; the delta rule is perfect there. At n=4dkn=4d_k 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.

확인 문제Check yourself

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 dk×dvd_k\times d_v matrix; its read-out S⊤kS^\top k is linear in kk, and at most dkd_k 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:

ModelLinear mixerLinear : full layersFull-attention layersState per linear layer (values)
Qwen3-Next-80B-A3BGated DeltaNet36 : 12gated GQA, 2 KV heads × 256, partial RoPE32 heads × 128 × 128 = 524K
Qwen3.8-Flash-NextGated DeltaNet36 : 12Qwen Sparse Attention (2 KV heads × 256)48 × 128 × 128 = 786K
Kimi Linear 48B-A3BKDA20 : 7MLA, NoPE32 × 128 × 128 = 524K
Kimi K3KDA69 : 24gated MLA, NoPE96 × 128 × 128 = 1.57M
Nemotron 3 UltraMamba-248 : 12GQA, 2 KV heads × 128, no position embedding256 heads × 64 × 128 = 2.10M
MiniMax-M1lightning attention70 : 10GQA, 8 KV heads × 12864 heads × 128 × 128 = 1.05M (our reading of the config)
MiniMax-M2—0 : 62GQA, 8 KV heads × 128—

The decode memory of one sequence is

mem(T)=nfull⋅(KV values per token)⋅bKV⋅T⏟grows  +  nlin⋅(state values)⋅bstate⏟fixed,\text{mem}(T)=\underbrace{n_{\text{full}}\cdot(\text{KV values per token})\cdot b_{\text{KV}}\cdot T}_{\text{grows}}\;+\;\underbrace{n_{\text{lin}}\cdot(\text{state values})\cdot b_{\text{state}}}_{\text{fixed}},

and a decode step reads all of it once, so the same expression is the per-token memory traffic. The two terms cross at T\*=nlin state bstate/(nfull KV bKV)T^\*=n_{\text{lin}}\,\text{state}\,b_{\text{state}}/(n_{\text{full}}\,\text{KV}\,b_{\text{KV}}): 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 T\*T^\* the hybrid holds more state than an all-attention model of the same shape.

그림에서 가져갈 것:

  1. 고정 상태 규칙은 모두 n≈dkn\approx d_k에서 벽을 만난다. 더 나은 갱신 규칙은 recall이 어디서 어떻게 무너지는지를 바꿀 뿐, 벽을 옮기지 못한다. 저장한 만큼 메모리가 자라는 attention만 100%에 머문다.
  2. delta rule은 “더 큰 용량”이 아니라 “고칠 수 있는 메모리”다. 서로 다른 key만 쓰고 β=1\beta=1이면 linear attention보다 나쁘다. 쓸 때마다 새 key 방향으로 옛 내용을 projection으로 빼내므로, 저장된 모든 것이 조금씩 지워진다. 장점은 key가 다시 쓰이거나(상태 추적: “x = 3 … x = 5”) 상관될 때 나타난다. 코드, 도구 출력, 멀티턴 대화가 정확히 그런 상황이다. β<1\beta<1은 가소성과 보존을 맞바꾸고, βt\beta_t를 데이터 의존으로 만들면 모델이 토큰마다 고른다.
  3. 감쇠는 신선함을 사는 대신 먼 recall을 판다. 대부분의 토큰에는 맞는 편향이고, 100K 토큰 전의 바늘에는 틀린 편향이다. 그 바늘이 full attention 층의 몫이다.
NumPy 장난감 MQAR: key 수에 따른 recall, 덮어쓰기 있을 때와 없을 때
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은 n=8n=8에서 이미 71%다. 용량보다 한참 아래인데, 혼합된 값을 돌려주기 때문이다. delta rule은 거기서 완벽하다. n=4dkn=4d_k에서는 고정 상태 규칙 모두 20–25%인데 attention은 여전히 정확하다. 장난감의 “attention”은 이상화한 것이지만(온도 0, 실제 모델이 RoPE로 배우는 최신 우선 규칙) 그것이 보여 주는 비대칭, 즉 고정 상태 대 자라는 캐시는 실제다.

확인 문제Check yourself

head 차원 d_k = 128인 순수 Gated DeltaNet 층이 100K 토큰 문맥에 흩어진 서로 다른 변수 바인딩 2,000개에 대해 답해야 한다. 옳은 것은?

상태는 dk×dvd_k\times d_v 행렬이고 읽기 S⊤kS^\top k는 kk에 선형이라, 간섭 없이 읽어 낼 수 있는 key 방향은 많아야 dkd_k개다. 더 나은 규칙(delta, gate)은 어떤 연관이 살아남을지 정하고 메모리를 고칠 수 있게 할 뿐 rank를 올리지 못한다. head를 늘리면 용량이 선형으로 늘지만 그것이 곧 “더 큰 상태”의 비용이다. chunk 크기는 같은 함수를 어떻게 계산하느냐만 바꾼다. 하이브리드에 full attention 층이 있는 이유다.

하이브리드: full attention 층은 몇 개?

실제 배포된 설계는 모두 소수의 전역 softmax attention 층을 정확한 recall을 맡는 “닻(anchor)“으로 남기고(Nemotron Super 보고서의 표현) 나머지를 linear로 만든다. 공개된 config.json에서 가져온 구성은 이렇다.

모델Linear mixerlinear : full 층full attention 층linear 층당 상태 (값 개수)
Qwen3-Next-80B-A3BGated DeltaNet36 : 12gated GQA, KV head 2 × 256, partial RoPEhead 32 × 128 × 128 = 524K
Qwen3.8-Flash-NextGated DeltaNet36 : 12Qwen Sparse Attention (KV head 2 × 256)48 × 128 × 128 = 786K
Kimi Linear 48B-A3BKDA20 : 7MLA, NoPE32 × 128 × 128 = 524K
Kimi K3KDA69 : 24gated MLA, NoPE96 × 128 × 128 = 1.57M
Nemotron 3 UltraMamba-248 : 12GQA, KV head 2 × 128, 위치 임베딩 없음head 256 × 64 × 128 = 2.10M
MiniMax-M1lightning attention70 : 10GQA, KV head 8 × 128head 64 × 128 × 128 = 1.05M (config를 우리가 읽은 값)
MiniMax-M2—0 : 62GQA, KV head 8 × 128—

시퀀스 하나의 decode 메모리는

mem(T)=nfull⋅(토큰당 KV 값 수)⋅bKV⋅T⏟자란다  +  nlin⋅(상태 값 수)⋅bstate⏟고정\text{mem}(T)=\underbrace{n_{\text{full}}\cdot(\text{토큰당 KV 값 수})\cdot b_{\text{KV}}\cdot T}_{\text{자란다}}\;+\;\underbrace{n_{\text{lin}}\cdot(\text{상태 값 수})\cdot b_{\text{state}}}_{\text{고정}}

이고 decode 한 step이 이것을 모두 한 번 읽으므로 같은 식이 토큰당 메모리 트래픽이다. 두 항은 T\*=nlin state bstate/(nfull KV bKV)T^\*=n_{\text{lin}}\,\text{state}\,b_{\text{state}}/(n_{\text{full}}\,\text{KV}\,b_{\text{KV}})에서 만난다. Qwen3-Next는 약 3K 토큰, Nemotron 3 Ultra는 33K 토큰이다(FP32 SSM 상태 403 MB 대 토큰당 KV 12 KB). T\*T^\*보다 짧으면 하이브리드가 같은 모양의 전부-attention 모델보다 상태를 더 많이 들고 있다.

KV – 고정 상태fixed state – KV = 상태 지점KV = state at – 전부 attention 대비vs all-attention – 80 GB에 들어가는 시퀀스sequences per 80 GB –
Per-sequence decode state, from each model's config.json: KV cache of the attention layers (BF16) plus the fixed recurrent state of the linear layers (FP32; NVIDIA and Qwen configs say float32, for K3 and M1 FP32 is our assumption). Decode reads all of it once per generated token, so the same curve is the memory-traffic cost. Drag the full-attention fraction away from the real ratio: at 0 the memory is flat (pure linear model — and recall collapses, previous figure); at 1 it is a plain Transformer. Below the crossover length the hybrid actually holds more state than an all-attention model of the same shape. Short-conv state, activations and weights are left out; the K3 MLA entry is taken as 512 + 64 values from the config. 각 모델 config.json으로 계산한 시퀀스 하나의 decode 상태다. attention 층의 KV cache(BF16)와 linear 층의 고정 순환 상태(FP32; NVIDIA·Qwen config는 float32라고 적혀 있고, K3·M1은 FP32로 가정)의 합이다. decode는 토큰마다 이것을 한 번씩 다 읽으므로 같은 곡선이 메모리 트래픽 비용이기도 하다. full attention 비율을 실제 값에서 옮겨 보면 0에서는 메모리가 평평하고(순수 linear 모델 — 대신 앞 그림처럼 recall이 무너진다), 1에서는 보통의 Transformer다. 교차 길이보다 짧은 문맥에서는 하이브리드가 같은 모양의 전부-attention 모델보다 오히려 더 많은 상태를 들고 있다. short conv 상태, activation, 가중치는 뺐고, K3의 MLA 항목은 config의 512 + 64개 값으로 잡았다.

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: float32 in the Qwen3.5, Qwen3.8 and Nemotron configs); KDA’s decay needs a floor so that 1/Γ1/\Gamma stays inside BF16 range in the chunk kernel.
확인 문제Check yourself

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: 36×32×128×128×4 B≈75.536\times 32\times128\times128\times4\ \text{B}\approx 75.5 MB. KV per token: 12×2×2×256×2 B=24,57612\times2\times2\times256\times2\ \text{B}=24{,}576 B. The ratio is ≈3,072\approx3{,}072 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 St=MtSt−1+writetS_t=M_tS_{t-1}+\text{write}_t, read by St⊤qtS_t^\top q_t. Linear attention, lightning attention, Mamba-2, GLA, DeltaNet, GDN and KDA differ only in the transition MtM_t (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 (L∘QK⊤)V(L\circ QK^\top)V with a 1-semiseparable decay mask; q,k,v↔C,B,xq,k,v\leftrightarrow C,B,x.
  • The chunkwise algorithm computes diagonal blocks as small masked matmuls and passes one dk×dvd_k\times d_v state across chunk boundaries — a few percent more FLOPs than the recurrence, T/CT/C sequential steps, tensor cores. The delta rule adds one triangular solve per chunk (UT transform).
  • A dk×dvd_k\times d_v state holds about dkd_k 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 커널에서 1/Γ1/\Gamma가 BF16 범위 안에 머물도록 하한이 필요하다.
확인 문제Check yourself

Qwen3-Next-80B는 GDN 36층(상태 head 32 × 128 × 128, FP32)과 attention 12층(KV head 2 × 256, BF16)을 가진다. 시퀀스 하나에서 고정 GDN 상태와 KV cache가 같아지는 길이는 대략?

상태: 36×32×128×128×4 B≈75.536\times 32\times128\times128\times4\ \text{B}\approx 75.5 MB. 토큰당 KV: 12×2×2×256×2 B=24,57612\times2\times2\times256\times2\ \text{B}=24{,}576 B. 비는 약 3,0723{,}072 토큰이다. (GDN 한 층의 상태는 attention 한 층의 KV 약 1K 토큰 분과 같고, attention 층 하나당 GDN 층이 셋이므로 교차점은 3K다.) 그 뒤로는 하이브리드의 이점이 문맥에 비례해 커진다. 256K에서 합계는 같은 모양의 전부-attention 모델의 약 25%다.

정리

  • Linear attention은 St=MtSt−1+쓰기tS_t=M_tS_{t-1}+\text{쓰기}_t로 쓰고 St⊤qtS_t^\top q_t로 읽는 fast-weight 메모리다. linear attention, lightning attention, Mamba-2, GLA, DeltaNet, GDN, KDA는 전이 MtM_t만 다르다(항등, 고정 감쇠, 데이터 의존 스칼라 감쇠, 채널별 감쇠, Householder 꼴 교체, 또는 둘 다).
  • Mamba-2의 SSD 쌍대성: 스칼라 감쇠 SSM은 1-semiseparable 감쇠 마스크를 쓴 masked attention (L∘QK⊤)V(L\circ QK^\top)V와 같다. q,k,v↔C,B,xq,k,v\leftrightarrow C,B,x.
  • chunk 알고리즘은 대각 블록을 작은 masked 행렬곱으로 계산하고 chunk 경계마다 dk×dvd_k\times d_v 상태 하나를 넘긴다. FLOPs는 순환형보다 몇 % 많지만 순차 단계는 T/CT/C번이고 tensor core에서 돈다. delta rule은 chunk마다 삼각 풀이 하나(UT transform)를 더한다.
  • dk×dvd_k\times d_v 상태는 독립적인 연관을 약 dkd_k개 담는다. 갱신 규칙은 recall이 어떻게 무너지는지(crosstalk, 덮어쓰기 불가, 잊기)를 바꾸지 어디서를 바꾸지 않는다. delta rule의 진짜 선물은 고칠 수 있는 메모리다.
  • 하이브리드는 4층에 1층에서 8층에 1층을 full attention으로 남겨 정확한 recall을 맡긴다. 메모리는 자라는 KV 항과 고정 상태의 합이고, 수천–수만 토큰에서 교차한다. 채택을 정하는 것은 품질, 되돌리기, prefix caching, 정밀도라는 비용이다.

더 읽을거리Further reading