Hybrid Architectures: RetNet and the Three Computation Paradigms
Building RetNet from scratch — how a single retention formula admits three computation modes (parallel for training, recurrent for inference, chunkwise for long sequences) producing identical outputs, why exponential decay and complex-exponential position encoding together fix the two failure modes of linear attention, and what the impossible triangle of training parallelism, low-cost inference, and strong performance actually requires.
A hybrid architecture is one whose forward pass can be computed by more than one algorithm — a parallel one and a recurrent one — that produce identical outputs from the same parameters. Not approximations of each other. Not different models that happen to behave similarly. The same number, computed two ways. Such an architecture is neither a transformer nor an RNN; it is both, depending on which algorithm the implementation chooses to run.
This matters because of an old tension. Training a sequence model on a GPU rewards parallelism: every position should be computable at the same time. Generating tokens at inference rewards a constant-size state: every new token should cost the same regardless of how much context came before. Transformers nail the first but pay a growing KV cache for the second. RNNs nail the second but cannot parallelize across time. A model that admits both algorithms — train it as a parallel transformer, deploy it as an RNN — sidesteps the tradeoff entirely. Sun et al. (2023) call this the impossible triangle: training parallelism, low-cost inference, and strong performance, and argue that previous architectures achieved at most two of the three.
This post derives retention, the mechanism at the core of the Retentive Network (RetNet) and the cleanest worked example of the hybrid pattern. Retention has three computation modes — parallel (for training), recurrent (for inference), and chunkwise (for long sequences) — all dropping out of a single recurrence . We will derive each mode, verify numerically that all three produce identical outputs, and then layer on the two pieces that make retention competitive with softmax attention: complex-exponential position encoding (which slots in via the eigendecomposition of a generalized state-transition matrix) and multi-scale retention (which assigns each head a different decay rate to capture different timescales).
The core paper is Sun et al. (2023), “Retentive Network: A Successor to Transformer for Large Language Models.”
The Running Example
We continue with the same tiny example from the Why Replace Attention blog:
- tokens, , single head
with the same query, key, and value matrices:
For the decay derivations, we fix:
This means each past token’s contribution to the state decays by a factor of per step. A token 10 steps in the past has its influence scaled by — roughly one-third of a token that just arrived.
For cost analysis, we use the same model parameters from the series:
- , heads, , layers, fp16
1. The Two Problems with Linear Attention’s Recurrence
1.1 Problem 1: Unbounded state accumulation
The Why Replace Attention blog derived the linear attention recurrence:
Every token adds to the state. Nothing is ever forgotten. Let us trace what happens to the state matrix as tokens accumulate, using the linear attention values from the Why Replace Attention blog (with ):
The entries of grow monotonically. To quantify this, we compute the Frobenius norm , which measures the total magnitude of the state:
The norm grew from 2.24 to 12.25 in just 4 tokens — a increase. For a sequence of tokens, each contributing an outer product of expected magnitude , the state norm grows as . At , the state entries become enormous. The numerical range of expands without bound, which creates two practical problems:
-
Precision loss. In fp16 (the standard training precision), values above 65,504 overflow to infinity. Even before overflow, large values lose precision in the mantissa — small but important contributions from new tokens get rounded away when added to a large accumulated state.
-
Old information dominates. Token 1’s contribution to is the same magnitude as token ‘s, regardless of how far apart they are. In language modeling, a token 100,000 positions ago is almost certainly less relevant than a token 10 positions ago. But the accumulate-only recurrence treats them identically.
1.2 Problem 2: No position information
In standard softmax attention, the similarity is typically augmented with position encodings — either absolute (Vaswani et al., 2017) or relative (Su et al., 2021). These encodings allow the model to distinguish “token is 3 positions before token ” from “token is 300 positions before token .”
In linear attention, the kernel similarity has no position dependence. The feature maps and depend only on the content of the query and key vectors, not on their positions and . The recurrent state is a sum of outer products where each outer product carries no information about when it was added.
This means the model cannot learn position-dependent patterns like “the verb usually follows the subject within 5 tokens” or “the closing bracket matches the most recent opening bracket.” The decay factor in the normalization is uniform across all positions — a crude tool that cannot distinguish distances.
1.3 What we need
We need two modifications to the linear attention recurrence:
- A forgetting mechanism that decays the contribution of old tokens, keeping the state bounded and prioritizing recent information.
- Position encoding that makes the query-key interaction depend on relative position , not just content.
RetNet achieves both. The forgetting mechanism is an exponential decay factor applied to the state at every step. The position encoding comes from complex exponentials that rotate the query and key vectors based on their absolute positions, producing a similarity that depends on relative position. We will derive each modification from scratch.
2. The Retention Recurrence
2.1 Adding decay
The simplest fix for unbounded accumulation is to multiply the old state by a scalar at every step. This gives the retention recurrence:
where is the state matrix, is the key vector for token , is the value vector, is the query vector, and is the output. The initial state is (the zero matrix).
Compare this to the linear attention recurrence from the Why Replace Attention blog:
Two differences:
-
The factor . The old state is scaled by before the new token’s contribution is added. When , this reduces to linear attention’s accumulation (without the kernel). When , older information exponentially decays.
-
No kernel feature map. Retention uses the raw key vector , not a transformed version . There is no elu+1 or any other kernel. This means the query-key product can be negative — retention does not produce non-negative attention weights. The normalization comes from GroupNorm applied to the output (Section 8), not from a denominator like linear attention’s .
2.2 Unrolling the recurrence
Let us expand by repeatedly substituting the recurrence. This is the technique of unrolling a recurrence relation — replacing each with its definition in terms of until we reach the base case .
Substitute :
Substitute :
The pattern is clear. After substitutions, we reach and the term vanishes:
Each token contributes the outer product , scaled by . The exponent is the distance from token to the current position .
The output for token is:
Since is a scalar and is a row vector, we can write the output as a row vector:
This says: the output for token is a weighted sum of all past value vectors . The weight on value is the product of two factors: the content similarity (how relevant is token to query ?) and the decay (how far away is token ?).
2.3 What exponential decay means
The decay factor is an exponentially decaying function of the distance . Let us compute its values for :
| Distance | Interpretation | |
|---|---|---|
| 0 | Current token — full weight | |
| 1 | Previous token — 90% | |
| 2 | 2 tokens ago — 81% | |
| 5 | 5 tokens ago — 59% | |
| 10 | 10 tokens ago — 35% | |
| 50 | 50 tokens ago — 0.5% | |
| 100 | 100 tokens ago — negligible |
With , tokens more than 50 positions ago contribute less than 1% of their original weight. The model has a soft attention window: it can see all past tokens, but overwhelmingly focuses on recent ones.
The effective window size — the distance at which the decay drops to some threshold — is:
This follows by taking the natural logarithm of both sides and dividing. For and :
So the effective window is about 44 tokens. The choice of controls the tradeoff between long-range and short-range attention. Higher (closer to 1) gives longer effective windows; lower gives shorter ones. RetNet uses different values for different heads — we will derive this in Section 7.
2.4 The bounded state property
Unlike linear attention, the retention state is bounded. Each entry of is a sum of decaying contributions:
Assuming each is bounded by some constant , the sum is bounded by a geometric series:
The last equality uses the geometric series partial sum formula .
As , (since ), so:
For : . The state entries are bounded by 10 times the maximum single-token contribution. No matter how long the sequence, the state cannot grow beyond this bound. This is the bounded geometric series limit, and it eliminates the precision loss problem of linear attention.
3. Tracing the Retention Recurrence
3.1 Step-by-step computation
Let us trace the retention recurrence for all 4 tokens with , using the raw , , matrices (no kernel feature map).
Step :
Token 1 can only attend to itself. The query-key similarity is — query 1 and key 1 are orthogonal. In softmax attention, this would still produce a nonzero output (because ). In retention, zero similarity means zero output. The GroupNorm applied later (Section 8) will handle the scaling.
Step :
The old state was decayed by . The entry (from token 1’s contribution) became in . Token 2’s contribution was added at full strength.
Numerical check. We can verify this directly from the unrolled formula:
Token 2 attends to token 1 with similarity 1, decayed by . It attends to itself with similarity 0. So the output is dominated by token 1’s value vector.
Step :
Notice that the entry from token 1 has now decayed to , exactly as predicted by the formula .
Step :
3.2 Summary of outputs
| Token | |
|---|---|
| 1 | |
| 2 | |
| 3 | |
| 4 |
3.3 State norm comparison
Compare to the linear attention state norms (from Section 1.1): . The retention state norms are: . The retention state is growing more slowly because the decay factor shrinks old contributions at every step. For long sequences, the retention state converges to a bounded value while the linear attention state grows without bound.
4. The Parallel Form
4.1 From recurrence to matrix form
The recurrent form is ideal for inference (one token at a time), but it is sequential — depends on , which depends on , and so on. During training, we process the entire sequence at once and need a parallel computation.
We already derived the unrolled output:
This is a weighted combination of value vectors. The weight on is:
The first factor is the entry of the matrix . The second factor is a function of the distance only, and is zero for (causal masking). We can write this as a single matrix.
4.2 The matrix
Define the decay matrix as:
This matrix combines two things into one: causal masking (the zero entries above the diagonal ensure token cannot attend to future tokens ) and exponential decay (the entry weights past tokens by their distance).
For our running example with and :
The diagonal is all 1’s (each token attends to itself with no decay). The first column decays as — token 1’s influence fades as we move forward. The upper triangle is all zeros — no future peeking.
Compare this to the standard causal mask in softmax attention, which is:
The standard mask uses 1 for all allowed positions — no decay. is a generalization: it is a causal mask where the allowed entries are weighted by exponential decay instead of being uniformly 1. When , reduces to .
4.3 The parallel retention formula
The full parallel computation is:
where is the Hadamard product (element-wise multiplication, defined in the Gated Attention blog). This says: compute the query-key similarity matrix , multiply it element-wise by the decay matrix (which simultaneously applies causal masking and exponential decay), then multiply by the value matrix .
4.4 Numerical verification
Let us compute the parallel form and verify it matches the recurrent outputs from Section 3.
Step 1: Compute .
Row 1:
Row 2:
Row 3:
Row 4:
Step 2: Apply via Hadamard product.
Row 1:
Row 2:
Row 3:
Row 4:
This is the retention matrix — the analog of the attention weight matrix in softmax attention. But unlike softmax attention weights, these entries are not normalized to sum to 1, and they can be negative (though in this example they happen to be non-negative because all are non-negative for our particular and ).
Step 3: Multiply by .
Row 1:
Row 2:
Row 3:
Row 4:
Verification: Compare each row with the recurrent outputs from Section 3.2:
| Token | Recurrent | Parallel row | Match? |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 |
Both forms produce identical outputs. The parallel form computed everything at once using matrix operations. The recurrent form computed outputs one at a time using state updates. The mathematics guarantees they are equivalent.
5. The Hybrid Architecture: One Formula, Multiple Computation Modes
This is the defining section of this blog. Everything we have derived so far leads here: the retention formula is a single mathematical object that can be computed in fundamentally different ways depending on the context. This is what makes RetNet a hybrid architecture — not a transformer, not an RNN, but a single model that computes as a transformer during training and as an RNN during inference, with exact equivalence.
5.1 Training uses the parallel form
During training, the full sequence is available. The parallel form is a sequence of matrix multiplications and a Hadamard product — operations that GPUs execute efficiently in parallel. The cost is:
- :
- Hadamard product with :
- Multiply by :
Total: per head. This is the same asymptotic cost as softmax attention. The advantage is not in the asymptotic complexity — it is in the simplicity. There is no softmax (which requires a sequential max-subtraction for numerical stability), no exponential, no normalization denominator. Just matrix multiply, Hadamard product, matrix multiply.
5.2 Inference uses the recurrent form
During autoregressive generation, we process one token at a time. The recurrent form , has:
-
State size: per head. With : elements per head. Across heads and layers, in fp16: bytes MB.
-
Compute per token: One scalar-matrix multiply (: ), one outer product (: ), one matrix-vector product (: ). Total: per head.
Both are constant — independent of how many tokens have been generated. Compare to softmax attention, where the KV cache grows as per head and the compute per token grows as :
| Property | Softmax attention | Retention (recurrent) |
|---|---|---|
| State per head at step | elements (KV cache) | elements (constant) |
| Compute per token at step | (grows) | (constant) |
| State at , our model | 3.15 GB | 0.75 MB |
The recurrent retention state is smaller than the KV cache at 128K tokens.
5.3 The impossible triangle and why hybrid architectures matter
The parallel and recurrent forms compute the same function. This is the core property of a hybrid architecture: you choose the computation mode based on the hardware context, not the mathematical definition. Training uses the parallel form because GPUs are parallel processors. Inference uses the recurrent form because autoregressive generation is inherently sequential. The same weights, the same function, different execution strategies.
Before hybrid architectures, the field was stuck in a tradeoff. Sun et al. (2023) call it the impossible triangle: training parallelism, low-cost inference, and strong performance. Every architecture achieved at most two of the three:
| Architecture | Training parallelism | inference | Strong performance |
|---|---|---|---|
| Transformer | |||
| Linear Transformer | |||
| Recurrent NN | |||
| RWKV | |||
| H3/S4 | |||
| Hyena | |||
| RetNet |
RetNet claims all three vertices of the triangle. The rest of this blog derives the additional components — position encoding, chunkwise computation, multi-scale heads, and gating — that make this possible.
6. Position Encoding via Complex Exponentials
6.1 The problem
The retention formula has a position-dependent factor (, which depends on the distance), but the query-key interaction depends only on the content of and , not on their positions and .
Consider two scenarios:
- Query at position 10, key at position 8: with decay
- Query at position 1000, key at position 998: with decay
If and (same content), both scenarios produce the same output. The model cannot learn that position-dependent patterns like “subject-verb agreement” work differently at the start vs the middle of a document. The decay factor provides only a distance-based weighting, not a full relative position encoding.
6.2 The general state transition matrix
The fix has to come from the recurrence itself. The scalar decay shrinks the state by the same fraction at every step regardless of position, which is why nothing in the formula knows where token sits on the timeline. Replace that single number with a matrix and the per-step transformation becomes rich enough to encode rotation in addition to decay — the rotation will carry the position information.
Concretely, generalize the recurrence by replacing the scalar with a state-transition matrix :
Unrolling this gives:
The output is:
Now is a matrix raised to the power . Computing directly is expensive — matrix exponentiation costs . But if we diagonalize , the computation simplifies dramatically.
6.3 Diagonalizing
By the eigendecomposition theorem, if has linearly independent eigenvectors, we can write:
where is the matrix of eigenvectors (columns are eigenvectors) and are the eigenvalues. The notation denotes the diagonal matrix with on the -th diagonal entry.
The key property of the eigendecomposition is that matrix powers become trivial:
This follows because , where the cancellation in the middle is the crucial step. By induction, , and because powers of a diagonal matrix are diagonal with powered entries.
6.4 Absorbing into the projections
Substituting the eigendecomposition into the output:
Define new query and key vectors that absorb the eigenvector matrices:
Since and for learned projection matrices , absorbing into the projections means defining:
These are just different learned matrices. Since and are learned from data, absorbing changes nothing about the model’s expressivity — the optimizer will find appropriate values for and . After this absorption:
The matrix is diagonal, so the product can be written element-wise:
This is a sum of terms, each involving one eigenvalue .
6.5 Choosing eigenvalues:
RetNet chooses the eigenvalues to be complex numbers of the form:
where is a scalar (the same decay rate for all dimensions within a head) and is a different angle for each dimension . The notation is Euler’s formula: , where is the imaginary unit.
Why this specific form? Because it separates two functions:
-
The magnitude controls decay. Since , the magnitude of each eigenvalue is . This means — exponential decay with distance, exactly as before.
-
The phase controls rotation. The factor depends on the distance and the dimension-specific angle . Different dimensions rotate at different frequencies, creating a rich encoding of relative position.
The power factors as:
This is the product of a decay term (real, positive, decreasing) and a rotation term (complex, unit magnitude, oscillating).
6.6 The factored form
We can further factor the position-dependent term. Since is a scalar (same for all dimensions):
The last step uses the exponential product rule , applied to .
Substituting into the output:
Define position-encoded queries and keys:
In vector notation, using for element-wise multiplication:
where and is its complex conjugate (the complex conjugate of is ).
Then the inner sum becomes:
where the transpose here is the regular transpose (not conjugate transpose), because the conjugation is already built into through .
The full output is:
This has exactly the same form as Section 2.2, but now and carry position information through the complex exponential factors. The parallel form becomes:
with the position-encoded , , , and for , zero otherwise.
6.7 The relative position property
This is the crucial observation. The product expands as:
The complex exponential depends only on the relative position , not on the absolute positions and separately. This is precisely the property of relative position encodings like RoPE (Su et al., 2021) and xPos (Sun et al., 2022). The RetNet paper notes that this formulation is equivalent to xPos — the same mechanism proposed for length-extrapolatable transformers, here derived naturally from the eigendecomposition of the state transition matrix.
6.8 Practical implementation
In practice, the complex arithmetic is implemented using real numbers. For each pair of consecutive dimensions , the rotation is applied as a rotation matrix:
This is the standard technique used by RoPE and xPos: pair up dimensions, rotate each pair by an angle proportional to the position, and different pairs use different base frequencies .
6.9 Numerical example: position encoding effect
To see the effect concretely, consider a single dimension pair with . For query at position and keys at positions :
| Distance | |||
|---|---|---|---|
| 3 | |||
| 2 | |||
| 1 | |||
| 0 |
The rotation factor oscillates with distance. A key 3 positions away gets its first dimension component flipped in sign (), while a key 1 position away gets a positive contribution (). Combined with the decay , this creates a rich position-dependent similarity landscape: the model can learn to prefer keys at specific relative positions, not just nearby keys.
7. The Chunkwise Recurrent Form
7.1 The motivation
The parallel form has cost — good for moderate sequences, but quadratic in . The recurrent form has cost — linear in , but sequential (each step depends on the previous state). For long sequences during training, we want the best of both: parallel computation where possible, sequential state passing where necessary.
The chunkwise recurrent form divides the sequence into chunks of size . Within each chunk, retention is computed in parallel using the parallel form. Across chunks, the state is passed recurrently. This gives:
- Parallelism within each chunk (GPU-efficient)
- Linear memory across chunks (no matrix)
- Total cost: — when and are much smaller than , this is linear in
7.2 Derivation
Consider chunk containing tokens through . For notational simplicity, we write for the query, key, and value matrices restricted to this chunk (each is ).
The output for a token at position within chunk has two parts:
-
Inner-chunk: Attention to other tokens within the same chunk. This uses the parallel form restricted to the chunk: , where is the decay matrix for positions within the chunk.
-
Cross-chunk: Attention to all tokens in previous chunks, summarized by the recurrent state .
The cross-chunk contribution for token at position (1-indexed) within chunk is:
where accounts for the decay from the end of the previous chunk to position within the current chunk. In matrix form:
where is a column vector broadcast across the value dimensions.
The state update after processing chunk is:
where is a matrix with row equal to — the decay from position within the chunk to the end of the chunk, broadcast across value dimensions. This ensures that the state correctly accumulates contributions from all tokens up to and including chunk , with appropriate decay.
The complete chunkwise formula is:
7.3 Numerical verification with
Let us split our 4-token sequence into two chunks of :
- Chunk 1: tokens 1, 2
- Chunk 2: tokens 3, 4
Chunk 1:
The chunk-level decay matrix ():
Inner-chunk computation:
Cross-chunk: , so the cross-chunk contribution is zero.
State update for chunk 1:
Verification: should equal from the recurrent computation (the state at the end of chunk 1). From Section 3.1: .
Chunk 2:
Inner-chunk:
Cross-chunk:
The decay vector , broadcast across columns:
Total output chunk 2:
Both tokens match the recurrent and parallel outputs.
State update for chunk 2:
Verification: should equal from the recurrent computation. From Section 3.1: .
All three computation paradigms — recurrent, parallel, and chunkwise — produce identical outputs and identical final states. They are three views of the same mathematical object.
7.4 Chunkwise complexity
The cost of the chunkwise form per chunk:
- Inner-chunk: is . Multiply by : . Total: .
- Cross-chunk: is .
- State update: is .
There are chunks. Total cost:
With and (RetNet’s experimental settings):
Compare to the parallel form: . The chunkwise form becomes cheaper when , which is — true for virtually all practical sequences.
8. Multi-Scale Retention
8.1 Different decay rates per head
A single decay rate pins the model to a single effective window. With we built a model that pays attention to the last ~44 tokens; with we would build one that reaches ~458 tokens but gives almost equal weight to everything in that window; with we would build one that effectively only sees the last ~7 tokens. Language has structure at all of these scales — a closing bracket binds to the most recent opening one (short window), a pronoun binds to its antecedent some sentences ago (medium), a topic word echoes across paragraphs (long). One cannot serve all three.
The fix is to make a per-head knob: assign each of the heads its own decay rate, spaced geometrically from “very forgetful” to “very persistent”. RetNet picks the spacing with the formula:
where and the formula is applied element-wise, producing one per head. The offset starts the smallest gap at (so , already a fairly long window), and each subsequent head halves the gap, pushing closer and closer to 1.
8.2 Numerical values for heads
| Head | Effective window () | |||
|---|---|---|---|---|
| 0 | 145 | |||
| 1 | 292 | |||
| 2 | 587 | |||
| 3 | 1{,}177 | |||
| 4 | 2{,}357 | |||
| 5 | 4{,}717 | |||
| 6 | 9{,}439 | |||
| 7 | 18{,}882 |
The effective window is computed as , the formula from Section 2.3.
Head 0 has with an effective window of ~145 tokens — it focuses on local patterns. Head 7 has with an effective window of ~18,882 tokens — it captures long-range dependencies. This is multi-scale retention (MSR): the heads automatically specialize at different scales, similar to how multi-resolution wavelets capture patterns at different frequencies.
8.3 Why multiple scales help
The ablation in Table 6 of Sun et al. (2023) quantifies the contribution:
| Variant | In-Domain PPL |
|---|---|
| RetNet (full) | 26.05 |
| decay (set ) | 27.86 |
| multi-scale decay (same for all heads) | 27.02 |
Removing decay entirely () degrades perplexity by 1.81 — this reverts retention to linear attention, confirming that decay is essential. Using a single decay rate across all heads degrades perplexity by 0.97 — confirming that multi-scale specialization provides meaningful improvement beyond the decay mechanism itself.
8.4 GroupNorm instead of LayerNorm
Since different heads use different values, their output magnitudes differ. A head with accumulates less state (more decay) and produces smaller outputs than a head with (less decay). Applying LayerNorm across all heads would couple their normalization statistics, distorting the relative scales.
RetNet uses GroupNorm (Wu and He, 2018) instead, which normalizes each head independently. Formally, if is the output of the -th retention head:
where the GroupNorm has groups, one per head. Each head is normalized by its own mean and variance, preserving the different scales induced by different values.
The ablation confirms this: removing GroupNorm degrades perplexity from 26.05 to 27.54 (a 1.49 increase).
An important property of GroupNorm is scale invariance: for any scalar . This means the retention outputs do not need to be normalized by a denominator (unlike linear attention’s normalization). The GroupNorm absorbs any global scaling. This is why retention can use raw query-key products — even if the products are large or negative, the GroupNorm handles the scale.
8.5 Retention Score Normalization
The scale invariance of GroupNorm also enables additional normalization tricks that improve numerical precision without changing the final output. Sun et al. (2023) apply three normalization factors:
- Scale by (same as the scaling in standard attention).
- Normalize the decay matrix: replace with .
- Normalize the retention scores: .
These tricks stabilize the numerical flow in both forward and backward passes. Because of GroupNorm’s scale invariance, they do not affect the final output or gradients — they only improve intermediate precision.
9. The Complete RetNet Block
9.1 The MSR layer
The multi-scale retention (MSR) module combines the retention heads with a swish gate:
where and are learned parameter matrices. The swish activation (Ramachandran et al., 2017) is where is the sigmoid function.
The swish gate is a multiplicative interaction between the raw input (passed through a linear layer and swish) and the retention output. This is the same gating principle we derived in the Gated Attention blog — learned, per-dimension multiplicative control of information flow. The gate increases the non-linearity of the retention layer, which is important because the retention mechanism itself (without softmax) is a linear function of the values.
The ablation from Sun et al. (2023) confirms: removing the swish gate degrades perplexity from 26.05 to 27.84 (a 1.79 increase). This is the largest single-component degradation in the ablation, even larger than removing decay () — indicating that the gate is essential for model quality.
9.2 The full RetNet block
Each RetNet layer consists of an MSR module and a feed-forward network (FFN), with pre-norm residual connections (the same layout we derived in the Gated Attention blog, Section 2.2):
where is LayerNorm (Ba et al., 2016). The FFN uses GELU activation:
with and .
9.3 Parameter allocation
RetNet re-allocates parameters between the MSR and FFN modules to match the total parameter count of a standard transformer.
In a transformer: self-attention has parameters (, each ), and FFN has parameters (, ). Total: .
In RetNet: MSR has , (the value head dimension is twice the query/key dimension), , and (projecting from the widened value dimension back to ). That is .
To keep the total at , the FFN intermediate dimension is reduced to (from ), giving for FFN. Total: .
9.4 Numerical check
With :
- Transformer: parameters per layer
- RetNet: parameters per layer
The parameter counts match exactly. Any difference in performance comes from the architecture, not from having more or fewer parameters.
10. Experimental Results
Sun et al. (2023) evaluate RetNet against Transformers and other efficient architectures across multiple dimensions.
10.1 Language modeling
RetNet and Transformer are trained from scratch at three scales (1.3B, 2.7B, 6.7B parameters) on 100B tokens from The Pile, C4, and The Stack. The validation perplexities:
| Model Size | Transformer PPL | RetNet PPL |
|---|---|---|
| 1.3B | ~15.0 | ~14.8 |
| 2.7B | ~13.5 | ~13.3 |
| 6.7B | ~12.8 | ~12.5 |
RetNet achieves comparable or better perplexity at every scale. The gap widens in RetNet’s favor as models get larger — a favorable scaling trend.
10.2 Zero-shot and few-shot evaluation
On seven downstream tasks (HellaSwag, BoolQ, COPA, PIQA, Winograd, Winogrande, StoryCloze) with the 6.7B model:
| Setting | Transformer Avg | RetNet Avg |
|---|---|---|
| Zero-shot | 66.07 | 69.51 |
| 4-shot | 66.44 | 69.76 |
RetNet outperforms the Transformer on average in both zero-shot and few-shot settings. The improvements are consistent across individual tasks.
10.3 Training cost
Training throughput and memory on 8 NVIDIA A100-80GB GPUs with sequence length 8192:
| Model Size | Trm Memory (GB) | RetNet Memory (GB) | Trm Throughput (wps) | RetNet Throughput (wps) |
|---|---|---|---|---|
| 1.3B | 74.8 | 34.5 | 10{,}832 | 73{,}345 |
| 2.7B | 69.6 | 42.0 | 5{,}186 | 38{,}921 |
| 6.7B | 69.0 | 48.0 | 2{,}754 | 17{,}459 |
| 13B | 61.4 | 45.9 | 1{,}209 | 8{,}642 |
RetNet uses 25–54% less memory and achieves 6–7 higher throughput than vanilla Transformer. Even compared to FlashAttention-optimized Transformers, RetNet is competitive — and RetNet’s implementation uses vanilla PyTorch without custom kernels.
10.4 Inference cost
At 6.7B scale with 8K sequence length, the recurrent form gives:
- Memory: 3.4 less GPU memory (RetNet’s state is constant, Transformer’s KV cache grows)
- Throughput: 8.4 higher (words per second)
- Latency: 15.6 lower (milliseconds per token)
RetNet’s inference latency is batch-size invariant — it stays nearly constant whether processing 1 or 8 sequences simultaneously. Transformer latency grows with batch size because the KV cache competes for GPU memory with the computation.
10.5 Comparison with other efficient architectures
At 200M parameters with 16 layers and hidden dimension 1024:
| Method | In-Domain PPL | PG22 | QMSum | GovReport | SummScreen |
|---|---|---|---|---|---|
| RWKV | 30.92 | 51.41 | 28.17 | 19.80 | 25.78 |
| H3 | 29.97 | 49.17 | 24.29 | 19.19 | 25.11 |
| Hyena | 32.08 | 52.75 | 28.18 | 20.55 | 26.51 |
| Linear Transformer | 40.24 | 63.86 | 28.45 | 25.33 | 32.02 |
| RetNet | 26.05 | 45.27 | 21.33 | 16.52 | 22.48 |
RetNet outperforms all other efficient architectures on both in-domain and out-of-domain corpora. The Linear Transformer (the Why Replace Attention blog’s architecture) is the weakest — confirming that replacing softmax with a simple kernel without decay or position encoding loses too much modeling capacity.
10.6 Context length results
RetNet maintains its advantage across different context lengths:
| Model | 512 | 1024 | 2048 |
|---|---|---|---|
| Transformer | 13.55 | 12.56 | 12.35 |
| RetNet | 13.09 | 12.14 | 11.98 |
RetNet consistently achieves lower perplexity, and the gap slightly widens with longer contexts. The exponential decay does not prevent the model from using long-range context — the heads with have effective windows of nearly 19,000 tokens, covering most practical sequence lengths.
11. The Hybrid Architecture Pattern
11.1 What makes an architecture hybrid
We can now define precisely what a hybrid architecture means in this context. A hybrid sequence model satisfies three properties:
- A single mathematical formula defines the input-output mapping. There is one function, not two.
- Multiple computation modes implement this formula. Each mode has different cost characteristics (parallel vs sequential, quadratic vs linear memory) suited to different hardware contexts.
- Exact equivalence between modes. The outputs are identical — not approximated, not distilled, not fine-tuned separately. The same trained weights produce the same outputs regardless of which mode is used.
RetNet’s retention satisfies all three:
Parallel (training): . Cost: . GPU-efficient matrix operations. Used when the full sequence is available.
Recurrent (inference): , . Cost: per token. Constant memory, constant compute. Used for autoregressive generation.
Chunkwise (long-sequence training): parallel within chunks of size , recurrent across chunks. Cost: . Balances parallelism and memory. Used when sequences are too long for the full parallel form.
We verified numerically that all three produce identical outputs for every token. The equivalence is a mathematical property of the retention formula itself, not an engineering trick.
11.2 Why the hybrid pattern is general
The retention mechanism is not the only formula with this property. The mathematical ingredients that enable the hybrid pattern are:
- A linear recurrence with state . Any linear recurrence can be unrolled into a sum (yielding a parallel form) or executed step by step (yielding a recurrent form).
- Associativity of matrix multiplication. The parallel form is just a different parenthesization of the same matrix product — vs .
- Decomposability into chunks. The sum in the unrolled form can be split at any chunk boundary, giving the chunkwise form.
Any mechanism built on a linear recurrence inherits this hybrid property. This is why the pattern appears repeatedly in the architectures that followed RetNet: Mamba (Gu and Dao, 2023), RWKV (Peng et al., 2023), Griffin (De et al., 2024), and others all have parallel training and recurrent inference modes derived from the same linear recurrence structure. The specific choices — what goes into the state, how the state decays, how position is encoded — differ across architectures, but the hybrid pattern is the same.
11.3 From the Why Replace Attention blog to RetNet
The Why Replace Attention blog showed that linear attention is an RNN:
This was the first hybrid architecture: it had a parallel form and a recurrent form. But it failed at the third vertex of the impossible triangle — strong performance — because the accumulate-only recurrence lost information and lacked position encoding.
RetNet’s retention is a direct modification of this recurrence:
The two changes — adding and dropping the kernel feature map — are small algebraically but large in effect. The decay factor bounds the state, encodes recency, and (through multi-scale heads) creates a rich set of temporal attention windows. Dropping the kernel and replacing the denominator normalization with GroupNorm gives the model more flexibility — the query-key interaction can be negative, and the normalization is data-adaptive rather than formula-fixed.
The position encoding via complex exponentials () arises naturally from diagonalizing the state transition matrix — it is not an add-on but a structural consequence of the recurrence.
RetNet is the first architecture to convincingly demonstrate that the hybrid pattern can achieve all three vertices of the impossible triangle. It established the template — linear recurrence + exponential decay + multi-scale heads + gating — that subsequent architectures have refined and extended.
Summary
The Why Replace Attention blog’s linear attention was the first hybrid architecture: one formula with both a parallel form and a recurrent form. But it failed at quality because the accumulate-only recurrence () grows without bound and has no position information. RetNet fixes both problems by adding exponential decay (bounding the state at via the geometric series limit) and relative position encoding via complex exponentials (, derived from diagonalizing the state transition matrix ). The result is a hybrid architecture with three equivalent computation paradigms — parallel for training (, cost ), recurrent for inference ( per token, constant memory), and chunkwise for long sequences () — all verified to produce identical outputs on a 4-token running example. Multi-scale retention assigns different decay rates per head ( from to for 8 heads), giving effective attention windows from 145 to 18,882 tokens, and the swish gate plus GroupNorm complete the architecture to match transformer parameter counts while achieving 8.4 faster inference, 15.6 lower latency, and competitive-or-better perplexity. This is the hybrid architecture pattern: one formula, multiple computation modes, exact equivalence — the template that Mamba, RWKV, Griffin, and other post-transformer architectures all follow.
Previous: Why Replace Attention? The Softmax Bottleneck and the Path to Linear Time
Next: Targeted Memory: The Delta Rule, Gated DeltaNet, and Kimi Delta Attention
Enjoyed this post?
Subscribe to get notified when I publish new posts. No spam, unsubscribe anytime.