Search

Search papers and lessons

Retentive Network: A Successor to Transformer for Large Language Models

Yutao Sun, Li Dong, Shaohan Huang et al. · 2023

RetNet replaces attention with a retention layer that trains in parallel like a Transformer, runs one step at a time like an RNN at inference, and keeps Transformer-level language modelling scores.

On this page

  • Colour = topic mix
  • Linear algebra
  • Neural network basics
  • Architectures
  • Probability
  • Calculus
  • Discrete math
  • ReadReady to readNot yet

TL;DR

RetNet is a language-model architecture that tries to keep the best of two families. A Transformer trains in parallel across a whole sequence but is slow and memory-hungry when it generates text, because it keeps a growing cache of past keys and values. A recurrent network generates cheaply, one step at a time, but cannot train in parallel. RetNet replaces attention with a retention layer that has three equivalent forms: a parallel form for training, a recurrent form for generation, and a chunkwise form for long sequences. The authors report Transformer-level language-modelling scores with much lower inference cost.

Builds on: Transformer, Recurrent Neural Network, Linear Attention · Leads to: State Space Model, Mamba: Linear-Time Sequence Modeling with Selective State Spaces

Why it mattered

For several years the Transformer was the default architecture for large language models, and its main cost is at generation time. Serving a Transformer means storing a key-value cache that grows with every token, so memory use and latency rise with the length of the output. Many groups had tried to find a design that avoids this cost, but the earlier attempts gave up quality or training speed. RetNet was presented as a candidate successor that gives up neither, which is the claim the title makes.

The paper's concrete contribution is a single layer, the retention mechanism, shown to be mathematically the same computation written three ways. That lets one trained model be run in whichever form suits the job. The authors trained language models from 1.3B to 6.7B parameters and reported costs in memory, throughput and latency against Transformers of matching size.

The problem

The authors frame the difficulty as an "impossible triangle" with three goals: training parallelism, good performance, and low-cost inference. Previous approaches met two of the three.

Transformers train in parallel and perform well, but their inference cost per step is O(N)O(N) in the sequence length and their key-value cache is memory-bound. Linearised attention, which replaces the softmax with a kernel so that generation can run as a recurrence, is efficient but performs worse than standard attention. Recurrent models generate in constant time per step but cannot be trained in parallel across the sequence, and the element-wise simplifications used to speed them up reduce their capacity. State-space models such as S4 are another route; the authors argue that none of these had yet broken the triangle.

RetNet's stated target is a layer that sits in the corner the others miss: parallel training, O(1)O(1) inference per token, and quality close to the Transformer.

How it works

RetNet is a stack of LL identical blocks. Each block has a multi-scale retention (MSR) module and a feed-forward module, with residual connections and pre-normalisation, as in a Transformer. The retention layer is where the idea lives. Here is the three-form trick on one tiny instance: a single channel, with the query and key set to 11 and values v=(1,2,3)v = (1, 2, 3) at positions 11, 22, 33, and decay γ=0.5\gamma = 0.5.

  1. Input. Each token is projected to a value vnv_n. The query and key projections QnQ_n and KnK_n are content-aware, so they depend on the token. In the example both are 11.
  2. Recurrent form, step by step. Keep a state SnS_n that carries the past forward, with Sn=γSn−1+Kn⊺vnS_n = \gamma S_{n-1} + K_n^\intercal v_n, and read out on=QnSno_n = Q_n S_n. Start with S0=0S_0 = 0. At n=1n = 1: S1=0+1=1S_1 = 0 + 1 = 1, so o1=1o_1 = 1. Check: only one token has been seen.
  3. Continue the recurrence. At n=2n = 2: S2=0.5×1+2=2.5S_2 = 0.5 \times 1 + 2 = 2.5, so o2=2.5o_2 = 2.5. At n=3n = 3: S3=0.5×2.5+3=4.25S_3 = 0.5 \times 2.5 + 3 = 4.25, so o3=4.25o_3 = 4.25. Check: the state is a decayed running sum, so the older value 11 counts half as much at step 22 as at step 11.
  4. Parallel form. The same output can be written as one matrix product, (QK⊺⊙D)V(QK^\intercal \odot D)V, where DD is a lower-triangular matrix with Dnm=γn−mD_{nm} = \gamma^{n-m} for n≥mn \geq m and zero above the diagonal. Here DD has rows (1,0,0)(1, 0, 0), (0.5,1,0)(0.5, 1, 0) and (0.25,0.5,1)(0.25, 0.5, 1). Multiplying gives o3=0.25×1+0.5×2+1×3=4.25o_3 = 0.25 \times 1 + 0.5 \times 2 + 1 \times 3 = 4.25. Check: the same number as step 3, computed without a loop.
  5. Chunkwise form. For a long sequence, split it into chunks of length BB. Inside a chunk, use the parallel form. Between chunks, pass a summary state, as in step 2. The result is the same, but memory stays bounded by the chunk size.
  6. Generation. At inference, use only the recurrent form. Each new token updates SnS_n with a fixed-size matrix and reads it out. The cost per token does not depend on how many tokens came before.
  7. Multi-scale decay. The model has several heads, and each head uses its own γ\gamma, so some heads forget quickly and some slowly. The outputs of the heads are normalised with GroupNorm and gated by a swish branch before the output projection.
flowchart LR
  X["Token inputs"] --> P["Parallel form, training: (QK^T ⊙ D) V"]
  X --> C["Chunkwise form, long training sequences"]
  X --> R["Recurrent form, generation: S_n = γ S_(n-1) + K_n^T V_n"]
  P --> O["Same outputs"]
  C --> O
  R --> O

The math

Step 1 in symbols: the recurrence

Let vnv_n be the scalar value at step nn, sn\mathbf{s}_n a state vector, and AA a fixed matrix. The paper begins with the linear recurrence sn=Asn−1+Kn⊺vn\mathbf{s}_n = A\mathbf{s}_{n-1} + K_n^\intercal v_n, with output on=Qnsno_n = Q_n \mathbf{s}_n. Unrolling it gives

on=∑m=1nQnA n−mKm⊺vm.o_n = \sum_{m=1}^{n} Q_n A^{\,n-m} K_m^\intercal v_m.

Making AA a scalar multiple of a rotation, A=γeiθA = \gamma e^{i\theta} and then γ\gamma real, turns the power An−mA^{n-m} into a decay γn−m\gamma^{n-m}. This gives the decay used in the walkthrough.

Step 4 in symbols: the parallel form

With Q=XWQQ = XW_Q, K=XWKK = XW_K, V=XWVV = XW_V, and a decay matrix DD whose entries are Dnm=γn−mD_{nm} = \gamma^{n-m} for n≥mn \geq m and zero otherwise, the retention layer is

Retention(X)=(QK⊺⊙D) V.\mathrm{Retention}(X) = (QK^\intercal \odot D)\,V.

The product QK⊺QK^\intercal is the same kind of object as attention scores, but it is multiplied elementwise by DD instead of passed through a softmax. Removing the softmax is what makes the recurrent form possible. In the paper, QQ and KK are also multiplied by a rotation einθe^{in\theta} that encodes position, the way rotary embeddings do.

Step 2 in symbols: the recurrent form

The same layer, written as a recurrence over a state matrix SnS_n, is

Sn=γSn−1+Kn⊺Vn,Retention(Xn)=QnSn.S_n = \gamma S_{n-1} + K_n^\intercal V_n, \qquad \mathrm{Retention}(X_n) = Q_n S_n.

The state SnS_n has fixed size, so generating one token costs the same at step ten and at step ten thousand. This is the O(1)O(1) inference claim.

Step 5 in symbols: the chunkwise form

Let BB be the chunk length and let [i][i] index the ii-th chunk. The paper writes the output of chunk ii as the sum of an inner-chunk term and a cross-chunk term,

Retention(X[i])=(Q[i]K[i]⊺⊙D) V[i]⏟inside the chunk+(Q[i]Ri−1)⊙ξ⏟from earlier chunks,\mathrm{Retention}(X_{[i]}) = \underbrace{(Q_{[i]} K_{[i]}^\intercal \odot D)\,V_{[i]}}_{\text{inside the chunk}} + \underbrace{(Q_{[i]} R_{i-1}) \odot \xi}_{\text{from earlier chunks}},

where the summary state is updated as Ri=K[i]⊺(V[i]⊙ζ)+γBRi−1R_i = K_{[i]}^\intercal (V_{[i]} \odot \zeta) + \gamma^{B} R_{i-1}. The paper sets ζ\zeta and ξ\xi to powers of γ\gamma that depend on the position inside the chunk. The inner term is parallel, the cross term is recurrent.

Step 7 in symbols: multi-scale decay and the block

The decay for head ii is

γi=1−2−5−i,i=0,1,…,h−1,\gamma_i = 1 - 2^{-5 - i}, \qquad i = 0, 1, \dots, h-1,

so the first head has γ0=1−2−5=0.96875\gamma_0 = 1 - 2^{-5} = 0.96875, and each later head has a value closer to 11 and therefore remembers further back. The head outputs are concatenated, normalised by GroupNorm, gated and projected:

MSR(X)=(swish(XWG)⊙GroupNormh(Concat(head1,…,headh)))WO.\mathrm{MSR}(X) = \big(\mathrm{swish}(XW_G) \odot \mathrm{GroupNorm}_h(\mathrm{Concat}(\mathrm{head}_1, \dots, \mathrm{head}_h))\big) W_O.

The block then adds a feed-forward network with a Gaussian Error Linear Unit (GELU) activation:

Yl=MSR(LN(Xl))+Xl,Xl+1=FFN(LN(Yl))+Yl.Y^l = \mathrm{MSR}(\mathrm{LN}(X^l)) + X^l, \qquad X^{l+1} = \mathrm{FFN}(\mathrm{LN}(Y^l)) + Y^l.

The paper also rescales the scores for numerical stability, which does not change the output because GroupNorm is invariant to a scalar factor.

Example
Recurrent and parallel forms agree on three tokens

Use a single channel with Qn=Kn=1Q_n = K_n = 1, decay γ=0.5\gamma = 0.5, and values v=(1,2,3)v = (1, 2, 3).

Recurrent form:

  1. Start with S0=0S_0 = 0.
  2. S1=0.5×0+1=1S_1 = 0.5 \times 0 + 1 = 1, so o1=1o_1 = 1.
  3. S2=0.5×1+2=2.5S_2 = 0.5 \times 1 + 2 = 2.5, so o2=2.5o_2 = 2.5.
  4. S3=0.5×2.5+3=4.25S_3 = 0.5 \times 2.5 + 3 = 4.25, so o3=4.25o_3 = 4.25.

Parallel form:

  1. DD has entries D31=0.52=0.25D_{31} = 0.5^2 = 0.25, D32=0.5D_{32} = 0.5, D33=1D_{33} = 1 in its last row.
  2. Since QK⊺QK^\intercal is all ones here, the output is DvD v.
  3. Last row: 0.25×1+0.5×2+1×3=4.250.25 \times 1 + 0.5 \times 2 + 1 \times 3 = 4.25.
  4. Second row: 0.5×1+1×2=2.50.5 \times 1 + 1 \times 2 = 2.5.

Interpretation: both forms give o2=2.5o_2 = 2.5 and o3=4.25o_3 = 4.25. The recurrent form computes them one at a time with a state of fixed size. The parallel form computes all of them at once. Training uses the second; generation uses the first.

Example
Training memory and throughput from the paper's table

Table 4 of the paper reports, for the 1.3B model trained with an 81928192-token sequence on eight A100-80GB GPUs, a memory use of 74.874.8 GB for a standard Transformer and 34.534.5 GB for RetNet. Throughput is 10832.410832.4 words per second for the Transformer and 73344.873344.8 for RetNet.

  1. Memory saving: 74.8−34.5=40.374.8 - 34.5 = 40.3 GB.
  2. Fraction saved: 40.3/74.8≈0.5440.3 / 74.8 \approx 0.54, so about 5454 percent.
  3. Throughput ratio: 73344.8/10832.4≈6.873344.8 / 10832.4 \approx 6.8.
  4. The introduction summarises training as about a 7×7\times speed-up, which is close to this ratio.

Interpretation: at this size RetNet uses much less memory and trains several times faster than a plain Transformer. The introduction's summary of 25 to 50 percent memory saving is a looser range than this one row, so read the table, not the summary, for the exact figure. The paper's comparison with FlashAttention is narrower, covered in the results below.

Try it: for the 2.7B model the paper reports 69.669.6 GB for the Transformer and 42.042.0 GB for RetNet. What fraction of memory does RetNet save? Answer: (69.6−42.0)/69.6=27.6/69.6≈0.40(69.6 - 42.0) / 69.6 = 27.6 / 69.6 \approx 0.40, about 4040 percent.

Results

The main comparisons are on language modelling with models of 1.31.3B, 2.72.7B and 6.76.7B parameters, trained on 100100B tokens from The Pile, C4 and The Stack.

Scaling. The authors report that RetNet and Transformer give comparable perplexity at the smaller sizes, and that RetNet starts to outperform the Transformer once the model is larger than about 22B parameters. The claim rests on three model sizes, so it is an empirical trend, not a law.

Zero-shot and few-shot. For the 6.76.7B models, the average accuracy over seven tasks is 66.0766.07 for the Transformer and 69.5169.51 for RetNet in the zero-shot setting, and 66.4466.44 versus 69.7669.76 with four shots. RetNet is higher on every listed task in both settings; the gains are largest on Winograd (77.277.2 versus 69.569.5) and COPA (77.077.0 versus 69.069.0).

Training cost. Table 4 compares a Transformer, a Transformer with FlashAttention, and RetNet, measured on eight A100-80GB GPUs with an 81928192-token sequence. At 1.31.3B, RetNet uses 34.534.5 GB against 38.838.8 GB for FlashAttention, and processes 73344.873344.8 words per second against 63965.263965.2. At 6.76.7B the gap narrows: 48.048.0 GB and 17458.617458.6 words per second for RetNet against 51.451.4 GB and 16230.116230.1 for FlashAttention. The authors note that their RetNet implementation uses vanilla PyTorch, so kernel-level optimisation was left for later work.

Inference. The 6.76.7B model's memory is almost entirely the weights: the authors state that the extra state is about 33 percent, while the weights are 9797 percent. For an 88k-token input on a 77B model, the introduction reports that RetNet decodes 8.4×8.4\times faster and saves 7070 percent of memory compared with a Transformer using a KV cache. Decoding throughput stays constant as the output grows, and latency barely changes with batch size.

Against other efficient models. On a 200200M-parameter comparison, RetNet has the lowest perplexity on the in-domain set (26.0526.05) and on the out-of-domain sets. For example, the Transformer-style Linear Transformer scores 40.2440.24 in-domain, RWKV 30.9230.92, H3 29.9729.97 and Hyena 32.0832.08.

Ablations. Removing the swish gate raises in-domain perplexity from 26.0526.05 to 27.8427.84. Removing GroupNorm raises it to 27.5427.54, and reducing the head dimension from 256256 to 6464 raises it to 27.6827.68. Removing the decay altogether, or using one decay across all heads, also hurts.

Limits. The quality comparison with the Transformer goes up only to 6.76.7B parameters, and the paper's claim that RetNet pulls ahead above about 22B rests on three sizes. The table comparing properties (Table 1) is qualitative. The training speed numbers come from eight A100-80GB GPUs with a non-optimised PyTorch implementation, so the gap to FlashAttention is closer than the gap to a plain Transformer. The inference numbers are for the 6.76.7B model on one GPU type. The 13B row in Table 4 reports training cost only, with no quality results.

Reading guide

The paper follows a standard research-paper layout. Each section needs the following lessons.

Check yourself

QuestionRetNet has a parallel form for training and a recurrent form for generation. What single property of the recurrent form gives it constant cost per generated token?Show answer

The recurrent form keeps a state matrix SnS_n whose size does not depend on sequence length. Each new token updates Sn=γSn−1+Kn⊺VnS_n = \gamma S_{n-1} + K_n^\intercal V_n and reads it with QnSnQ_n S_n, so the work per token is the same at any position. A Transformer's key-value cache grows with each token, which is why its cost rises.

QuestionWith one channel, γ=0.5\gamma = 0.5 and values (2,4)(2, 4) at positions 1 and 2, what is the output at position 2 using the recurrence with Q=K=1Q = K = 1?Show answer

S1=0×0.5+2=2S_1 = 0 \times 0.5 + 2 = 2. Then S2=0.5×2+4=5S_2 = 0.5 \times 2 + 4 = 5, so the output is 55. Check with the parallel form: D21=0.5D_{21} = 0.5 and D22=1D_{22} = 1, so the output is 0.5×2+1×4=50.5 \times 2 + 1 \times 4 = 5.

QuestionWhy does the paper remove the softmax from retention, and what does it give up?Show answer

A softmax normalises each row of scores over all earlier tokens, which cannot be updated one token at a time as a fixed-size state. Removing it, and using a decay matrix DD instead, lets the same computation run as a recurrence. The price is that the model no longer makes the normalised, competitive weighting over tokens that attention does; the paper compensates with GroupNorm and normalisation of the retention scores, and reports that quality stays comparable.

QuestionA team wants to serve a 6.76.7B model that must generate very long outputs cheaply. Based on the paper's reported numbers, which architecture should they expect to scale better at generation time, and what should they check before deciding?Show answer

RetNet should scale better at generation time: its memory is dominated by weights, with about 33 percent extra state, while a Transformer's cache grows with output length. Before deciding, they should check the paper's limits: its inference numbers come from a single 6.76.7B model on one GPU type, its training speed comparison used a non-optimised implementation, and they should measure quality on their own tasks, since the paper's language-modelling results are on its own data mix.

Sources

Read the full paper

Yutao Sun, Li Dong, Shaohan Huang et al., 2023. arXiv:2307.08621