RetNet (Retentive Network) is a language model that aims to achieve training parallelism, low inference cost, and performance on par with Transformer at the same time, using "retention", which removes the softmax from attention and multiplies by a decay mask that weakens exponentially with distance. It was proposed in 2023 by Sun and colleagues in the paper "Retentive Network: A Successor to Transformer for Large Language Models".
The paper calls the following three requirements for a language model backbone the "impossible triangle" and frames earlier methods as each sacrificing one of them.
RetNet's retention can be computed in three ways that give the same result.
Parallel form: computes all time steps at once with matrix multiplications, like attention. Used for training.
Recurrent form: updates the state one time step at a time. Used for generation; the computation and memory per step do not depend on the context length.
Chunkwise recurrent form: computes in parallel within chunks and recurrently across chunks. Used for training on long sequences.
The paper reports that, for a 6.7-billion-parameter model generating sequences of length 8,000, it was 8.4Γ faster than a Transformer with a KV cache and used 70% less memory.
Theory: deriving retention
The paper derives retention starting from the form of an RNN (Section 2.1 of the paper).
Start from a linear recurrence with a state: the input vnβ is written into a state snβ and read out linearly (Eq. (1) of the paper): snβ=Asnβ1β+Knβ€βvnβ, onβ=Qnβsnβ.
Make Q,K from the input: Q=XWQβ, K=XWKβ (Eq. (2) of the paper). This makes reading and writing depend on content.
Diagonalize A and make the decay a scalar: diagonalizing A=Ξ(Ξ³eiΞΈ)Ξβ1, absorbing Ξ into WQβ,WKβ, and making Ξ³ a scalar gives the output in the following form (Eq. (4) of the paper).
β denotes the conjugate transpose. The multiplication by einΞΈ has the same form as xPos, a relative position encoding for Transformers, and rotates Q and K according to position, like RoPE. Ξ³nβm is a decay that shrinks exponentially with distance.
Collecting this equation in matrix form gives the parallel form (Eq. (5) of the paper).
Ξnβ=einΞΈ, and ΞΛ is its complex conjugate. D combines the causal mask (no looking at the future) and the distance-based decay into a single matrix. Compared with softmax attention softmax(QKβ€)V, it is the form that removes the softmax and instead multiplies element-wise by D. The lower right of the figure at the top of the article shows the shape of this D.
The same computation can also be written in the recurrent form (Eq. (6) of the paper). The upper right of the figure at the top of the article shows this computation for one time step.
The state Snβ is a (key dimension) Γ (value dimension) matrix per head and does not depend on the sequence length.
Multi-scale retention and the RetNet layer
Multi-scale retention (MSR) (Section 2.2 and Eq. (8) of the paper) is a layer that replaces multi-head attention.
Split into heads: h=dmodelβ/d heads are used, each with its own WQβ,WKβ,WVβ.
Use a different decay Ξ³ per head: with Ξ³=1β2β5βarange(0,h), each head is responsible for memory of a different length (multi-scale). This is the default value in Eq. (8), and the official implementation (torchscale) uses it as well. Ξ³ is not learned and is fixed to the same values across layers.
Normalize per head: different decays give head outputs different variances, so group normalization normalizes each head.
Apply a gate and project back: MSR(X)=(swish(XWGβ)βY)WOβ. The Swish gate adds nonlinearity.
Like Transformer, a RetNet layer places layer normalization first (Pre-LN) and stacks MSR and FFN with residual connections (Eq. (9) of the paper).
Yl=MSR(LN(Xl))+Xl,Xl+1=FFN(LN(Yl))+Yl
The FFN is gelu(XW1β)W2β. In the paper's experiments, to match the parameter count of Transformer, the head dimension of V is twice that of Q,K (256 and 512), and the intermediate dimension of the FFN is 2d.
Group normalization gives the same output when its input is multiplied by a constant. The paper uses this property to add normalizations, such as dividing QKβ€ by dβ and dividing D by the square root of its row sums, which stabilize the numbers without changing the result (Section 2.2 of the paper).
Training on long sequences: chunkwise recurrence
The parallel form builds QKβ€ (NΓN), so it needs computation and memory quadratic in the sequence length N. For training on long sequences, the chunkwise recurrent form is used (Eq. (7) of the paper).
Split the sequence into chunks of length B.
Within a chunk, compute with the parallel form (Q[i]βK[i]β€ββD)V[i]β.
The contribution from previous chunks is added as (Q[i]βRiβ1β)βΞΎ, using the state Riβ1β up to the previous chunk. ΞΎijβ=Ξ³i+1 is the decay from the start of the chunk.
Update the state: Riβ=K[i]β€β(V[i]ββΞΆ)+Ξ³BRiβ1β, with ΞΆijβ=Ξ³Bβiβ1.
The computation is matrix multiplication within chunks and only passing a small state between chunks, so memory is linear in the sequence length. The SSD algorithm of Mamba-2 follows the same idea, and the Mamba-2 paper positions RetNet as "SSD whose decay Atβ is a constant Ξ³ independent of time".
Experimental results
Language model scaling (Figure 5 of the paper): models with 1.3, 2.7, and 6.7 billion parameters were trained on 100 billion tokens from a combination of The Pile, C4, and The Stack. Validation perplexity was comparable to Transformer, with a tendency for RetNet to be better above 2 billion parameters.
Zero-shot and few-shot evaluation (6.7 billion parameters, accuracy %. Table 3 of the paper)
Setting
Model
HellaSwag
BoolQ
COPA
PIQA
Winograd
Winogrande
StoryCloze
Average
Zero-shot
Transformer
55.9
62.0
69.0
74.6
69.5
56.5
75.0
66.07
Zero-shot
RetNet
60.7
62.2
77.0
75.4
77.2
58.1
76.0
69.51
4-shot
Transformer
55.8
58.7
71.0
75.0
71.9
57.3
75.4
66.44
4-shot
RetNet
60.5
60.1
78.0
76.0
77.9
59.9
75.9
69.76
Training cost (length 8,192, 8 A100s. Table 4 of the paper)
(Speed is words per second.) RetNet, using a plain PyTorch implementation without custom kernels (chunk length 512), matched or exceeded a Transformer with FlashAttention.
Inference cost (6.7 billion parameters, A100. Figure 6 of the paper): Transformer's memory grew with sequence length because of the KV cache, and its throughput dropped. RetNet's memory and throughput stayed constant regardless of length, and memory used beyond the model weights was about 3% of the total.
Comparison with other efficient models (200 million parameters, 16 layers, perplexity. Table 5 of the paper)
Effect of removing components (in-domain perplexity. Table 6 of the paper): compared with RetNet's 26.05, removing the swish gate gave 27.84, removing group normalization gave 27.54, removing the decay Ξ³ gave 27.86, and dropping per-head decays gave 27.02, so every component contributed to performance.
Practical considerations
Keep the following points in mind when using RetNet.
Choose the form of computation for the situation: use the parallel or chunkwise recurrent form for training and the recurrent form for generation. All three return the same values, so trained weights can be used as is.
The decay Ξ³ is a fixed hyperparameter: in the paper's language model experiments, it is fixed to Ξ³=1βelinspace(log1/32,Β log1/512,Β h) instead of the default value in Eq. (8), so that it is the same across model sizes. Heads with Ξ³ closer to 1 remember longer contexts.
Prepend a <bos> token to sequences: the paper states that prepending <bos> stabilized training and improved performance.
RetNet's decay Ξ³ is a per-head constant and does not change with the input. As a result, the decay itself cannot switch based on the input, such as "keep this information for a long time and forget that information quickly". Models whose decay changes with the input include Mamba and Mamba-2.
Because the state during generation has a fixed size, older information fades by Ξ³nβm, unlike a Transformer that keeps all past tokens. The paper's evaluation focuses on models up to 6.7 billion parameters and context lengths up to 2,048, so for tasks that require precisely retrieving fine-grained information from longer contexts, verify against a Transformer on your own task.
Comparison with other models
The paper organizes the relationship between RetNet and earlier methods as follows (Section 2.4 of the paper).
Transformer: the parallel form is close to attention; the difference is removing the softmax so that a recurrent form becomes possible. Positions are handled in the same form as xPos.
S4: if Qnβ,Knβ are made independent of the input, retention degenerates into the same convolutional form as S4.
Linear attention: it tries to approximate the softmax with feature maps, but the paper points out that it cannot represent positional information well. RetNet does not aim to approximate the softmax and instead represents position with the decay D.
AFT and RWKV: RWKV is similar in replacing position weights with exponential decay, but its computation is per channel. The paper states that RetNet is more expressive because it has a high-dimensional state (a matrix).
Lining up sequence models that replace Transformer from the same perspectives:
Linear RNN with exponentially decaying weighted averages
No (constant per channel)
Linear in length
Constant
RetNet
Retention with decay
No (constant per head)
Quadratic in parallel form, linear when chunked
Constant
Guidelines for choosing:
To generate with a large language model using little memory at constant speed: RetNet is a good fit. It trains in parallel like Transformer and runs without custom kernels.
To make forgetting depend on the input: consider Mamba or Mamba-2.
To use pretrained models and tools as they are: Transformer is a good fit.
PyTorch example
βΆShow code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of RetNet's retention and multi-scale retention (MSR)
- Parallel form (Eq. 5): (Q Kα΅ β D) V, D_nm = Ξ³^(n-m) (n β₯ m)
- Recurrent form (Eq. 6): S_n = Ξ³ S_{n-1} + K_nα΅ V_n, output = Q_n S_n
- Chunkwise recurrence (Eq. 7): parallel form within chunks, recurrent form across chunks
- The e^{inΞΈ} applied to Q and K is written as real-valued rotations of paired dimensions (same form as RoPE and xPos)
- MSR (Eq. 8): a different Ξ³ per head, group normalization per head, and a swish gate
"""
def rotate(x, theta):
"""x: [B, h, T, d]. Rotate the row at position n by angle nΒ·ΞΈ (same as multiplying by the complex number e^{inΞΈ})"""
T, d = x.shape[-2], x.shape[-1]
ang = torch.arange(T, device=x.device)[:, None] * theta[None, :] # [T, d/2]
cos, sin = ang.cos(), ang.sin()
x1, x2 = x[..., 0::2], x[..., 1::2]
return torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1).flatten(-2)
def decay_mask(gamma, T):
"""D_nm = Ξ³^(n-m) (n β₯ m), 0 (n < m). gamma: [h] β [h, T, T]"""
n = torch.arange(T, device=gamma.device)
diff = (n[:, None] - n[None, :]).float()
D = gamma[:, None, None] ** diff.clamp(min=0)
return D * (diff >= 0)
def parallel_retention(q, k, v, gamma):
"""Eq. (5). q, k: [B, h, T, dk], v: [B, h, T, dv]"""
return ((q @ k.transpose(-1, -2)) * decay_mask(gamma, q.shape[2])) @ v
def recurrent_retention(q, k, v, gamma):
"""Eq. (6). Update the state S ([B, h, dk, dv]) one time step at a time"""
B, h, T, dk = q.shape
S = q.new_zeros(B, h, dk, v.shape[-1])
out = []
for n in range(T):
S = gamma[None, :, None, None] * S + k[:, :, n, :, None] * v[:, :, n, None, :]
out.append((q[:, :, n, :, None] * S).sum(-2))
return torch.stack(out, dim=2)
def chunkwise_retention(q, k, v, gamma, chunk=4):
"""Eq. (7). Parallel within chunks; pass the state R across chunks"""
B, h, T, dk = q.shape
g = gamma[None, :, None, None]
D = decay_mask(gamma, chunk)
pos = torch.arange(chunk, device=q.device).float()
inner_decay = gamma[:, None] ** (pos + 1) # ΞΎ: decay from the start of the chunk
key_decay = gamma[:, None] ** (chunk - pos - 1) # ΞΆ: decay to the end of the chunk
R = q.new_zeros(B, h, dk, v.shape[-1])
out = []
for i in range(0, T, chunk):
qi, ki, vi = q[:, :, i:i + chunk], k[:, :, i:i + chunk], v[:, :, i:i + chunk]
inner = ((qi @ ki.transpose(-1, -2)) * D) @ vi # within the chunk
cross = (qi @ R) * inner_decay[None, :, :, None] # from previous chunks
out.append(inner + cross)
R = (ki * key_decay[None, :, :, None]).transpose(-1, -2) @ vi + (g ** chunk) * R
return torch.cat(out, dim=2)
class MultiScaleRetention(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
self.h, self.dk = n_heads, d_model // n_heads
self.dv = 2 * self.dk # V head dimension is twice that of Q and K (Section 3.1)
self.W_q = nn.Linear(d_model, d_model, bias=False)
self.W_k = nn.Linear(d_model, d_model, bias=False)
self.W_v = nn.Linear(d_model, 2 * d_model, bias=False)
self.W_g = nn.Linear(d_model, 2 * d_model, bias=False)
self.W_o = nn.Linear(2 * d_model, d_model, bias=False)
self.norm = nn.GroupNorm(n_heads, 2 * d_model) # normalize per head
self.register_buffer('gamma', 1 - 2.0 ** (-5 - torch.arange(n_heads).float())) # Eq. (8)
self.register_buffer('theta', 1.0 / (10000 ** (torch.arange(0, self.dk, 2).float() / self.dk))) # rotation angles (example)
def forward(self, x): # x: [B, T, d_model]
B, T, _ = x.shape
split = lambda t, d: t.view(B, T, self.h, d).transpose(1, 2)
q = rotate(split(self.W_q(x), self.dk), self.theta) / self.dk ** 0.5 # QKα΅/βd (group normalization leaves the result unchanged)
k = rotate(split(self.W_k(x), self.dk), self.theta)
v = split(self.W_v(x), self.dv)
y = parallel_retention(q, k, v, self.gamma) # training uses the parallel form
y = y.transpose(1, 2).reshape(B * T, -1)
y = self.norm(y).view(B, T, -1)
return self.W_o(F.silu(self.W_g(x)) * y) # swish gate
class RetNetBlock(nn.Module):
"""Eq. (9): Y = MSR(LN(X)) + X, X' = FFN(LN(Y)) + Y. The FFN intermediate dimension is 2d (Section 3.1)"""
def __init__(self, d_model, n_heads):
super().__init__()
self.ln1, self.ln2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
self.msr = MultiScaleRetention(d_model, n_heads)
self.ffn = nn.Sequential(nn.Linear(d_model, 2 * d_model), nn.GELU(), nn.Linear(2 * d_model, d_model))
def forward(self, x):
y = self.msr(self.ln1(x)) + x
return self.ffn(self.ln2(y)) + y
if __name__ == "__main__":
torch.manual_seed(0)
B, h, T, dk, dv = 2, 4, 16, 8, 16
q, k, v = torch.randn(B, h, T, dk), torch.randn(B, h, T, dk), torch.randn(B, h, T, dv)
gamma = 1 - 2.0 ** (-5 - torch.arange(h).float())
p = parallel_retention(q, k, v, gamma)
print('parallel vs recurrent diff:', (p - recurrent_retention(q, k, v, gamma)).abs().max().item())
print('parallel vs chunkwise diff:', (p - chunkwise_retention(q, k, v, gamma, chunk=4)).abs().max().item())
block = RetNetBlock(d_model=64, n_heads=4)
print(block(torch.randn(2, 32, 64)).shape) # torch.Size([2, 32, 64])
FAQ
Q. What is the difference between retention and attention?
A.
Retention takes attention's softmax(QKβ€)V, removes the softmax, and instead multiplies element-wise by a distance-based decay mask Dnmβ=Ξ³nβm, giving (QKβ€βD)V. Without the softmax, the same computation can be written as a recurrence on the state Snβ=Ξ³Snβ1β+Knβ€βVnβ, so each generation step takes constant computation.
Q. Why use a different decay $\gamma$ for each head?
A.
Heads with Ξ³ close to 1 remember the distant past, while heads with small Ξ³ focus on nearby tokens. Using a different Ξ³ per head lets the model handle dependencies of many lengths at once (multi-scale). In the paper's experiments, giving all heads the same decay worsened perplexity from 26.05 to 27.02.
Q. Is RetNet a kind of linear attention?
A.
In that it uses no softmax and has a recurrent form that keeps adding Kβ€V to a state, it belongs to the family of causal linear attention. The differences are that it multiplies the state by the decay Ξ³ and uses group normalization instead of normalizing by a denominator. In the framework of the Mamba-2 paper, it is positioned as a kind of SSD with a constant decay.