AI Logic

Architectures

RetNet

Updated:

Architecture of RetNet. The left side shows the overall flow as a language model (L stacked layers of layer normalization, multi-scale retention, and a residual connection, followed by layer normalization, FFN, and a residual connection). The center shows the inside of multi-scale retention (retention with a different decay Ξ³ per head is computed from position-rotated Q and K and from V, followed by per-head group normalization, a swish gate, and the linear layer W_O). The upper right shows the recurrent form (the state S is multiplied by Ξ³, K_nα΅€V_n is added, and multiplying by Q_n gives the output), and the lower right shows the decay mask D of the parallel form (a lower-triangular matrix that fades with distance and is 0 for the future).

Background and overview

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.

MethodTraining parallelismInference cost (per step)Performance
TransformerYesProportional to context length (KV cache)High
Linear attentionYesConstantWorse than Transformer
RNN (LSTM, etc.)NoConstantWorse than Transformer
RetNetYesConstantOn par with Transformer

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).

  1. Start from a linear recurrence with a state: the input vnv_n is written into a state sns_n and read out linearly (Eq. (1) of the paper): sn=Asnβˆ’1+Kn⊀vns_n = A s_{n-1} + K_n^\top v_n, on=Qnsno_n = Q_n s_n.
  2. Make Q,KQ, K from the input: Q=XWQQ = XW_Q, K=XWKK = XW_K (Eq. (2) of the paper). This makes reading and writing depend on content.
  3. Diagonalize AA and make the decay a scalar: diagonalizing A=Ξ›(Ξ³eiΞΈ)Ξ›βˆ’1A = \Lambda(\gamma e^{i\theta})\Lambda^{-1}, absorbing Ξ›\Lambda into WQ,WKW_Q, W_K, and making Ξ³\gamma a scalar gives the output in the following form (Eq. (4) of the paper).
on=βˆ‘m=1nΞ³nβˆ’m(QneinΞΈ)(KmeimΞΈ)†vmo_n = \sum_{m=1}^{n} \gamma^{n-m} \bigl(Q_n e^{in\theta}\bigr)\bigl(K_m e^{im\theta}\bigr)^\dagger v_m

†\dagger denotes the conjugate transpose. The multiplication by einΞΈe^{in\theta} has the same form as xPos, a relative position encoding for Transformers, and rotates QQ and KK according to position, like RoPE. Ξ³nβˆ’m\gamma^{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).

Q=(XWQ)βŠ™Ξ˜,K=(XWK)βŠ™Ξ˜Λ‰,V=XWV,Retention(X)=(QKβŠ€βŠ™D) V,Dnm={Ξ³nβˆ’m(nβ‰₯m)0(n<m)Q = (XW_Q) \odot \Theta, \quad K = (XW_K) \odot \bar{\Theta}, \quad V = XW_V, \qquad \mathrm{Retention}(X) = (QK^\top \odot D)\,V, \quad D_{nm} = \begin{cases} \gamma^{n-m} & (n \ge m) \\ 0 & (n < m) \end{cases}

Θn=einΞΈ\Theta_n = e^{in\theta}, and Ξ˜Λ‰\bar{\Theta} is its complex conjugate. DD 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\mathrm{softmax}(QK^\top)V, it is the form that removes the softmax and instead multiplies element-wise by DD. The lower right of the figure at the top of the article shows the shape of this DD.

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.

Sn=γ Snβˆ’1+Kn⊀Vn,Retention(Xn)=QnSnS_n = \gamma\, S_{n-1} + K_n^\top V_n, \qquad \mathrm{Retention}(X_n) = Q_n S_n

The state SnS_n 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.

  1. Split into heads: h=dmodel/dh = d_{\mathrm{model}}/d heads are used, each with its own WQ,WK,WVW_Q, W_K, W_V.
  2. Use a different decay Ξ³\gamma per head: with Ξ³=1βˆ’2βˆ’5βˆ’arange(0,h)\gamma = 1 - 2^{-5-\mathrm{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. Ξ³\gamma is not learned and is fixed to the same values across layers.
  3. Normalize per head: different decays give head outputs different variances, so group normalization normalizes each head.
  4. Apply a gate and project back: MSR(X)=(swish(XWG)βŠ™Y) WO\mathrm{MSR}(X) = (\mathrm{swish}(XW_G) \odot Y)\,W_O. 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))+YlY^l = \mathrm{MSR}(\mathrm{LN}(X^l)) + X^l, \qquad X^{l+1} = \mathrm{FFN}(\mathrm{LN}(Y^l)) + Y^l

The FFN is gelu(XW1)W2\mathrm{gelu}(XW_1)W_2. In the paper's experiments, to match the parameter count of Transformer, the head dimension of VV is twice that of Q,KQ, K (256 and 512), and the intermediate dimension of the FFN is 2d2d.

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⊀QK^\top by d\sqrt{d} and dividing DD 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⊀QK^\top (NΓ—NN \times N), so it needs computation and memory quadratic in the sequence length NN. For training on long sequences, the chunkwise recurrent form is used (Eq. (7) of the paper).

  1. Split the sequence into chunks of length BB.
  2. Within a chunk, compute with the parallel form (Q[i]K[i]βŠ€βŠ™D)V[i](Q_{[i]}K_{[i]}^\top \odot D)V_{[i]}.
  3. The contribution from previous chunks is added as (Q[i]Riβˆ’1)βŠ™ΞΎ(Q_{[i]} R_{i-1}) \odot \xi, using the state Riβˆ’1R_{i-1} up to the previous chunk. ΞΎij=Ξ³i+1\xi_{ij} = \gamma^{i+1} is the decay from the start of the chunk.
  4. Update the state: Ri=K[i]⊀(V[i]βŠ™ΞΆ)+Ξ³BRiβˆ’1R_i = K_{[i]}^\top (V_{[i]} \odot \zeta) + \gamma^B R_{i-1}, with ΞΆij=Ξ³Bβˆ’iβˆ’1\zeta_{ij} = \gamma^{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 AtA_t is a constant Ξ³\gamma 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)

SettingModelHellaSwagBoolQCOPAPIQAWinogradWinograndeStoryClozeAverage
Zero-shotTransformer55.962.069.074.669.556.575.066.07
Zero-shotRetNet60.762.277.075.477.258.176.069.51
4-shotTransformer55.858.771.075.071.957.375.466.44
4-shotRetNet60.560.178.076.077.959.975.969.76

Training cost (length 8,192, 8 A100s. Table 4 of the paper)

Model sizeMemory: TransformerMemory: +FlashAttentionMemory: RetNetSpeed: TransformerSpeed: +FlashAttentionSpeed: RetNet
1.3B74.8 GB38.8 GB34.5 GB10,83263,96573,345
6.7B69.0 GB51.4 GB48.0 GB2,75416,23017,459

(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)

ModelIn-domainPG22QMSumGovReportSummScreen
RWKV30.9251.4128.1719.8025.78
H329.9749.1724.2919.1925.11
Hyena32.0852.7528.1820.5526.51
Linear attention40.2463.8628.4525.3332.02
RetNet26.0545.2721.3316.5222.48

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 Ξ³\gamma 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 Ξ³\gamma is a fixed hyperparameter: in the paper's language model experiments, it is fixed to Ξ³=1βˆ’elinspace(log⁑1/32,Β log⁑1/512,Β h)\gamma = 1 - e^{\mathrm{linspace}(\log 1/32,\ \log 1/512,\ h)} instead of the default value in Eq. (8), so that it is the same across model sizes. Heads with Ξ³\gamma 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 Ξ³\gamma 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\gamma^{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,KnQ_n, K_n 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 DD.
  • 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:

ModelHow the sequence is mixedDoes forgetting depend on the input?Training computationPer generation step
TransformerSoftmax attentionNo state (keeps the entire past)Quadratic in lengthProportional to the length so far
Linear attentionAccumulates into a state via feature-map inner productsNever forgets (only accumulates)Linear in lengthConstant
S4Linear SSM (initialized with HiPPO)NoNearly linear in length (FFT)Constant
HyenaLong convolutions and element-wise gatesNo (the kernel is fixed; the gates depend on the input)Nearly linear in length (FFT)Not constant as a plain convolution
MambaSSM whose parameters depend on the inputYesLinear in length (parallel scan)Constant
Mamba-2SSM with the state decay restricted to a scalarYesLinear in length (mostly matrix multiplications)Constant
RWKVLinear RNN with exponentially decaying weighted averagesNo (constant per channel)Linear in lengthConstant
RetNetRetention with decayNo (constant per head)Quadratic in parallel form, linear when chunkedConstant

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\mathrm{softmax}(QK^\top)V, removes the softmax, and instead multiplies element-wise by a distance-based decay mask Dnm=Ξ³nβˆ’mD_{nm} = \gamma^{n-m}, giving (QKβŠ€βŠ™D)V(QK^\top \odot D)V. Without the softmax, the same computation can be written as a recurrence on the state Sn=Ξ³Snβˆ’1+Kn⊀VnS_n = \gamma S_{n-1} + K_n^\top V_n, so each generation step takes constant computation.

Q. Why use a different decay $\gamma$ for each head?
A.

Heads with Ξ³\gamma close to 1 remember the distant past, while heads with small Ξ³\gamma focus on nearby tokens. Using a different Ξ³\gamma 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⊀VK^\top V to a state, it belongs to the family of causal linear attention. The differences are that it multiplies the state by the decay γ\gamma 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.

References

  1. Y. Sun, L. Dong, S. Huang, S. Ma, Y. Xia, J. Xue, J. Wang, and F. Wei, "Retentive Network: A Successor to Transformer for Large Language Models," arXiv:2307.08621, 2023.
  2. Y. Sun, L. Dong, B. Patra, S. Ma, S. Huang, A. Benhaim, V. Chaudhary, X. Song, and F. Wei, "A Length-Extrapolatable Transformer," arXiv:2212.10554, 2022.
  3. T. Dao and A. Gu, "Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality," ICML, 2024.