AI State of the Art
SOTA/Post-Transformer Architectures/24 min
Section 69

RetNet (Retention Networks)

Listen as a podcast →

Three modes for the price of one

Here's a dilemma every NLP researcher knows well. During training, you want to process the entire sequence at once, in parallel, that's how GPUs work fast. At inference, you generate tokens one by one, and there, you want each token to cost as little as possible. And then there's a third scenario: prefill, when you need to digest a long prompt before starting to generate. There, you need a compromise between the two.

Most architectures choose a single mode and live with it. Transformers are parallel during training but drag their KV cache at inference. RNNs are efficient token by token but impossible to parallelize for training. Always a sacrifice somewhere.

RetNet, proposed by Microsoft Research, refuses this compromise. Its ambition: natively support three computation modes that are mathematically equivalent, you choose the best one depending on the situation, without ever losing precision.

Retentive Network: A Successor to Transformer for Large Language Models
A Penrose triangle (impossible triangle) drawn in three shades of grey. The three corners are labelled Low-Cost Inference at the top, Training Parallelism at the bottom left and Strong Performance at the bottom right. Each side carries the name of an architecture family: Linear Transformer on the left side, Recurrent Network on the right side, Transformer along the bottom. RetNet is written in the centre of the triangle.
The impossible triangle from the RetNet paper. Each side stands for a family that only gets two of the three properties: the Transformer is parallel and strong but expensive at inference, the linear Transformer is parallel and cheap but weaker, the RNN is cheap and strong but cannot be parallelised. RetNet sits in the middle and claims all three at once.Source : RetNet paper by Sun et al. (figure 2), via Cai Jianfeng's blog

The Retention mechanism

The central idea: attention with exponential decay

RetNet replaces the standard attention mechanism with retention, a cousin of attention with a fundamental difference: the interaction weights between tokens are automatically weighted by an exponential decay factor based on their distance.

Retention(X)=(Q⋅K⊤⊙D)⋅V\text{Retention}(X) = (Q \cdot K^\top \odot D) \cdot V

The symbols: XX is the matrix stacking the tokens' representations; QQ, KK and VV (queries, keys, values) are computed from it via learned weight matrices, exactly as in attention; Q⋅K⊤Q \cdot K^\top gives the table of interaction scores between every pair of tokens; the symbol ⊙\odot denotes the element-wise product (each cell multiplied by the matching cell, no mixing); and D is a causal masking matrix with decay:

Dn,m={γ(n−m)if n≥m (token n is after token m)0if n<m (causal masking)D_{n,m} = \begin{cases} \gamma^{(n-m)} & \text{if } n \geq m \text{ (token } n \text{ is after token } m\text{)} \\ 0 & \text{if } n < m \text{ (causal masking)} \end{cases}

The parameter gamma (between 0 and 1) controls the speed of this decay. Let's take a concrete example: with gamma = 0.99, a token located 100 positions away sees its weight multiplied by 0.99^100 ~ 0.37, less than half the original weight. A token at 500 positions? Its weight drops to 0.99^500 ~ 0.007, almost nothing.

Intuition behind retention

Imagine you're reading a novel. The sentences you just read are perfectly clear in your mind. Those from the previous paragraph are still there, but a bit fuzzy. The first chapter? You remember the general idea, not the exact words. Retention mathematically encodes this natural memory decay with distance. It's a reasonable inductive bias: in most texts, the immediate context matters more than the distant context.

Position encoding in complex space

RetNet uses a complex rotation similar to RoPE (Rotary Position Embedding) to encode positions:

Q=(X⋅WQ)⊙ΘK=(X⋅WK)⊙Θ‾\begin{aligned} Q &= (X \cdot W_Q) \odot \Theta \\ K &= (X \cdot W_K) \odot \overline{\Theta} \end{aligned}

Here WQW_Q and WKW_K are the learned weight matrices producing queries and keys, and Θ‾\overline{\Theta} is the conjugate of Θ\Theta (the same rotation, in the opposite direction). Theta contains elements exp(i*n*theta), complex numbers (the i is the mathematicians' imaginary unit, not an index) that rotate according to position n. Each position in the sequence corresponds to a different rotation angle. When you compute the product Q * K^T, the rotations combine to produce a signal that depends on the relative distance between tokens, exactly what you want for encoding positional information, without needing a separate encoding.

The three computation paradigms

This is the real gem of RetNet, and what sets it apart from all its competitors.

Parallel mode: for training

In parallel mode, retention is computed as a standard matrix multiplication, similar to attention:

Retentionparallel(X)=(Q⋅K⊤⊙D)⋅V\text{Retention}_{\text{parallel}}(X) = (Q \cdot K^\top \odot D) \cdot V

Complexity: O(L^2 d), identical to standard attention. It's perfectly parallelizable on GPU, each element of the matrix can be computed independently. You use this mode during training, where speed takes priority.

Recurrent mode: for token-by-token inference

In recurrent mode, retention is reformulated as a recurrence with a matrix state s:

sn=γ⋅sn−1+kn⊤⋅vn(state update)on=qn⋅sn(output)\begin{aligned} s_n &= \gamma \cdot s_{n-1} + k_n^\top \cdot v_n & \text{(state update)} \\ o_n &= q_n \cdot s_n & \text{(output)} \end{aligned}

The state s_n is a d x d matrix that accumulates key-value associations, weighted by gamma decay. It's like a notebook that updates with each new token: old notes gradually fade (multiplication by gamma), and the new key-value association is added. Each new token is computed in O(d^2), independent of sequence length, no more endlessly growing KV cache.

Figure 3 from the RetNet paper, in two panels. Panel a, parallel representation: input X feeds three branches Q, K and V, which combine into the expression (Q times K transpose, element-wise product with D) times V, then pass through a GN block (GroupNorm) to give output O. Panel b, recurrent representation: input X_n produces V_n, K_n and Q_n; K_n and V_n are multiplied then added to the previous state S_n minus 1 scaled by gamma, giving the new state S_n; that state is multiplied by Q_n then passed through GN to give output O_n.
Two faces of the same computation. On the left, parallel mode: the whole sequence goes through one matrix multiplication, just like attention. On the right, recurrent mode: a state S flows from left to right, multiplied by gamma at each step (that is the decay) and enriched with the new key-value pair. Nothing is approximated between the two, it is the same formula rewritten.Source : RetNet paper by Sun et al. (figure 3), via Andrey Lukyanenko's blog
Exact equivalence between modes

Unlike some approximations (like linear attention that approximates softmax), RetNet's three modes are mathematically identical. The numerical result is exactly the same whether you use parallel, recurrent, or chunkwise mode. You can train in parallel mode and infer in recurrent mode without any precision loss, it's not an approximation, it's an exact reformulation of the same computation.

Chunkwise mode: the smart compromise

The chunkwise mode splits the sequence into chunks of size B, then combines the best of both worlds:

  • Intra-chunk: parallel computation within each chunk (fast, well suited to GPUs)
  • Inter-chunk: recurrent state propagation between chunks (fixed memory)
Retentionchunk(Xi)=(Qi⋅Ki⊤⊙D)⋅Vi+(Qi⋅Si)⊙ξ\text{Retention}_{\text{chunk}}(X_i) = (Q_i \cdot K_i^\top \odot D) \cdot V_i + (Q_i \cdot S_i) \odot \xi

Two pieces in this formula. The first term is the parallel retention computed inside chunk ii (QiQ_i, KiK_i, ViV_i are the queries, keys and values restricted to that chunk). The second term brings in the past: SiS_i is the matrix state accumulated over all previous chunks, queried by the current chunk's queries, and ξ\xi ("xi") gathers the decay factors γ...\gamma^{...} that account for the distance between each position in the chunk and that past. In plain terms: what the chunk's neighbors say, plus what the memory of earlier chunks says.

This mode is ideal for the prefill phase: when a user sends a long prompt, you can digest it in chunks, faster than pure recurrence (which processes one token at a time), less memory-hungry than parallel mode on a very long sequence.

Figure 4 from the RetNet paper: three blocks of PyTorch pseudocode. Top left, ParallelRetention takes q, k, v and decay_mask, computes retention = q times k transpose, multiplied by decay_mask, then times v, and applies group_norm. Top right, RecurrentRetention takes q, k, v, past_kv and decay, computes current_kv = decay times past_kv plus k times v, then the output from q and current_kv, and returns the output together with current_kv. At the bottom, ChunkwiseRetention combines both: inner_retention computed inside the chunk, cross_retention computed from past_kv and inner_decay, the two summed, and current_kv updated with chunk_decay.
The three modes side by side, as code. Parallel mode (top left) knows neither state nor chunk. Recurrent mode (top right) carries past_kv from one token to the next. Chunkwise mode (bottom) does both: inner_retention for what happens inside the chunk, cross_retention for what comes from earlier chunks through past_kv.Source : RetNet paper by Sun et al. (figure 4), via the AIInfra documentation

Multi-Scale Retention: multiple time scales

Just as Multi-Head Attention uses multiple heads to capture different aspects of context, RetNet uses multiple retention heads with different decay rates:

γh∈{1−2−5,  1−2−6,  …,  1−2−(5+h)}\gamma_h \in \{1 - 2^{-5},\; 1 - 2^{-6},\; \ldots,\; 1 - 2^{-(5+h)}\}

The index hh numbers the heads: head number 1 gets γ=1−2−5≈0.97\gamma = 1 - 2^{-5} \approx 0.97, the next one 1−2−6≈0.981 - 2^{-6} \approx 0.98, and so on, each successive head has a γ\gamma twice as close to 1, hence a memory twice as long.

Multi-Scale Retention

Each gamma value gives a head a different "temporal range." A head with a gamma very close to 1 (very slow decay) remembers distant tokens well, it captures long-range dependencies, like the general theme of a paragraph. A head with gamma ≈ 0.97 (fast decay: after 100 tokens, only 0.97^100 ≈ 5% of the weight remains) focuses on nearby tokens, grammatical agreements, local syntactic relationships. Together, they cover multiple scales simultaneously, somewhat like an orchestra where each instrument covers a different frequency range.

Complete architecture of a RetNet block

Each RetNet block contains:

  1. Multi-Scale Retention (MSR) with GroupNorm normalization (a normalization applied per group of channels, to stabilize values)
  2. Feed-forward layer with SwiGLU (a gated variant of the feed-forward layer, standard in recent models)
  3. Residual connections and normalization

Comparison with competing architectures

PropertyTransformerRetNetRWKVMamba
Training modeParallelParallelParallelParallel scan
Inference per tokenO(L) (KV cache)O(1) fixed stateO(1) fixed stateO(1) fixed state
State sizeKV cache = O(L*d)Matrices per headVectors (RWKV-4; matrices since RWKV-5)Matrix O(N*d)
Native chunkwise modeNoYesPossibleYes (Mamba-2)

RetNet's matrix state is larger than RWKV-4's or Mamba's state, which potentially gives it more memorization capacity, at the cost of higher inference memory. It's an explicit trade-off: more information stored per layer, but a larger fixed memory cost.

Strengths and limitations

What RetNet does well

  • Triple paradigm: unique flexibility, you choose the mode based on the usage context, training, inference, or prefill
  • No KV cache: fixed inference memory, independent of context length
  • Mathematical equivalence: no precision trade-off between modes, unlike linear attention approximations
  • Multi-scale: different gamma values naturally capture different temporal ranges
The cost of the matrix state

RetNet's recurrent state is a matrix per head, of size (head dimension) × (head dimension) roughly, not (model dimension) squared, which would be gigantic. Let's do the math for a typical model with 32 layers and 32 heads of dimension 128: each head stores 128 × 128 = 16,384 numbers; multiplied by 32 heads and 32 layers, that's ~17 million numbers, i.e. ~34 MB in float16 (2 bytes per number) per active sequence. That's dozens of times more than RWKV-4's vector state, but nowhere near a KV cache, which runs into gigabytes after a few tens of thousands of tokens. The real cost lies elsewhere: this state is paid per request served in parallel, and every new token has to update the whole matrix.

What RetNet does less well

  • Fixed decay: gamma rates are fixed after training, not data-dependent (unlike Mamba). The model can't dynamically decide to remember an important token longer, a crucial keyword is forgotten at the same rate as an unremarkable word.
  • No selectivity: it's an LTI (time-invariant) system, like S4 before Mamba. Each token is processed with the same filter, without content adaptation.
  • Limited adoption: few production models use RetNet, unlike Mamba or RWKV which have active communities.

RetNet's legacy

Even though RetNet hasn't been massively adopted in production, its ideas have had real impact. Mamba-2's SSD framework (see the Mamba-2 and Jamba lesson), which unifies parallel and recurrent views of SSMs, is conceptually very close to RetNet's triple paradigm. The concept of "chunkwise computation" (this compromise between parallel and recurrent) has become a standard evaluation criterion for new architectures.

Where does RetNet fit in the ecosystem?

RetNet occupies an intermediate space between Transformers (maximum expressiveness, high cost) and classic RNNs (maximum efficiency, limited expressiveness). Its main contribution may not be the architecture itself, but the demonstration that you can have exact equivalence between parallel and recurrent modes, an idea that influenced the entire next generation of alternative architectures.

Check your understanding0 / 4

1. RetNet offers three computation modes: parallel, recurrent and chunkwise. How do the results of these three modes relate to each other?

2. At inference, roughly how heavy is RetNet's recurrent state for a typical 32-layer model, and how does that compare to a Transformer's KV cache?

3. What is retention's main weakness compared to Mamba?

4. What is the chunkwise mode used for in practice?