Attention Residuals
contents
- deeper should be better
- the fix: skip connections
- proof it works
- the one line nobody questioned
- three problems with x = x + Layer(x)
- the fix: attention over depth
- the math (it's short)
- full attnres vs block attnres
- the code
- results
- when this doesn't work
- transformer++ upgrade list
- what else are we not questioning?
- references
Quick context about resnets: neural networks learn by backpropagating gradients through layers. The deeper the network, the more times those gradients get multiplied by small numbers (sigmoid derivatives, weight matrices). After enough layers, gradients shrink to zero and early layers stop learning. This is the vanishing gradient problem, and it's why stacking more layers didn't work for a long time.
By 2015, careful initialization and BatchNorm had fixed most of the vanishing gradient problem. Deeper networks still trained worse, and ResNet fixed that in 2015. Then everyone moved on. Ten years later, Moonshot AI (the Kimi team) looked at the fix.
deeper should be better
Stack more layers. Learn more complex features. Get better results. That's the intuition, and it's wrong.
In 2015, He et al. trained plain convolutional networks (no skip connections) of increasing depth on CIFAR-10. A 56-layer network has more capacity than a 20-layer network, so it should do better. It can represent everything the 20-layer net can (set the extra 36 layers to identity) plus more.
Figure: my reproduction of He et al.'s plain-network CIFAR-10 runs. Each deeper plain network has a higher test error.
More layers, worse accuracy. And this isn't overfitting: the training error is also higher for deeper networks. It isn't vanishing gradients either. He et al. trained these nets with BatchNorm and checked that the backward gradients had healthy norms. The optimizer can't find a good solution for the deeper net.
The degradation problem: theoretical capacity is there, but the optimizer can't reach it.
the fix: skip connections
Skip connections (explained here) let a block learn and output . When the shape changes, the shortcut pads the extra channels with zeros (the paper's option A) or uses a 1x1 conv (option B).
In theory, extra layers can't make things worse, because the worst case is identity. In practice there is a limit. The paper's 1202-layer ResNet got 7.93% test error on CIFAR-10, worse than the 110-layer one (6.43%), and the authors blame overfitting.
proof it works
Same architectures, same training setup, plus skip connections:

Figure: Plain-20 against ResNet-20 with option A and option B shortcuts, from my reproduction. Dashed lines are training error, solid lines are test error.

Figure: all four depths from my reproduction. Left: plain nets, where deeper is worse on both training and test error. Right: ResNets with option A shortcuts.
| Model | Test error (my run) | Test error (paper) |
|---|---|---|
| Plain-20 | 9.26% | not listed |
| ResNet-20 | 8.64% | 8.75% |
| Plain-56 | 13.58% | not listed |
| ResNet-56 | 7.47% | 6.97% |
The paper numbers come from its Table 6. The paper shows plain nets only as curves (Figure 6).
Plain-56 was the worst model. ResNet-56 is the best. Skip connections fix the degradation problem and let deeper networks use their capacity.
The full implementation with training code, plots, and all ResNet variants: deep-residual-learning-pytorch
x = x + F(x) became the default wiring for ResNets, transformers, and diffusion models alike. Researchers tried variants (Highway gates, ReZero, LayerScale, DenseFormer), but the plain sum stayed the default for ten years.
the one line nobody questioned
x = x + self.attn(self.norm1(x)) # this is in every LLM everBut the weight on every layer's contribution is exactly 1.0. Layer 1 gets the same importance as layer 64. The initial embedding gets the same weight as the final attention output. That's kinda dumb if you think about it.
Moonshot thought about it.
three problems with x = x + Layer(x)
1. magnitude growth
64-layer transformer. After all layers, your hidden state is:
h_64 = x_0 + F_1(x_0) + F_2(h_1) + ... + F_64(h_63)65 terms. All added with weight 1.0. What happens to the norm?
import torch
import torch.nn as nn
torch.manual_seed(42)
d = 512
n_layers = 64
x = torch.randn(1, 10, d)
layers = nn.ModuleList([nn.Linear(d, d, bias=False) for _ in range(n_layers)])
norms = [x.norm().item()]
for layer in layers:
with torch.no_grad():
x = x + layer(x)
norms.append(x.norm().item())
for i in [0, 8, 16, 32, 64]:
print(f"After layer {i:2d}: norm = {norms[i]:.1f}")Output: 72 -> 227 -> 725 -> 7241 -> 730954
About 10,000x growth (730954 / 71.7 = 10,190). No single layer does anything extreme. Each one multiplies the norm by about 1.155, and 64 of those compound in a running sum with no normalization.
The 1.155 is not an accident. nn.Linear starts its weights uniform in , so has about the norm of and points in an unrelated direction. Then , and each layer multiplies the norm by . Slide the depth. Watch the hidden norm explode under vanilla residuals.
2. information dilution
imagine a meeting with 64 people. everyone speaks for exactly one minute. at the end you write a summary but you're forced to weight everyone equally.
That's standard residuals. After 64 layers, each layer contributes ~1.5% of the final hidden state (1/65, if every term has the same size). Layer 47 found a critical pattern between two tokens. Same weight as layer 3, which just copied the embedding.
Figure: the residual sum holds the embedding plus n layer outputs. If all terms have the same size, one layer owns 1/(n + 1) of it.
The deeper your network, the less any individual layer matters. A 128-layer model gives each layer about half the share of a 64-layer model (1/129 against 1/65).
3. prenorm makes it worse
PreNorm should fix this. It normalizes the input of each sub-layer (the 2017 transformer used PostNorm, which normalizes after the add):
x = x + self.attn(self.norm1(x)) # norm bounds the inputThe input to attention has a fixed scale, so its output stays near a fixed size. But you're adding that output to x, which is the ever-growing running sum. Each new layer's signal is a smaller and smaller fraction of the total.
Figure: a toy PreNorm stack. The sum starts at 1 (the embedding), and each layer adds an output of size 1 in the same direction. The newest layer's share falls as 1/(l + 1).
In a 64-layer PreNorm transformer, the last layers own a small share of the sum. Bounded output, unbounded accumulator. The paper measures this in its baseline. The output size of each block grows with depth (Figure 5b). Deeper layers must learn bigger outputs to stay relevant.
PreNorm solved gradient flow but not dilution. It made dilution worse.
the fix: attention over depth
Fix: let the network learn the weights. Use attention, but attend over depth instead of over sequence positions. Before each layer, the network looks at the outputs of all earlier layers and decides which ones matter.
Figure: an illustration, not measured weights. The paper's Figure 8 shows the weights a trained model with 16 attention and 16 MLP layers learns.
Standard residual: every layer gets 12.5%. Attention residual: layer 2 gets 35%, layer 6 gets 25%, the rest share what's left. The network figures out what matters.
the math (it's short)
The paper counts each attention and each MLP as its own layer. Let be the input to layer , the token embedding, and layer without its residual add. A standard residual unfolds to an equal-weight sum:
Attention residual replaces this with:
Where:
- is the token embedding, and is the raw output of layer
- is the attention weight, a softmax over the sources with no scale
- is a learned query vector per layer, one -dim vector that does not depend on the input. The weights still depend on the input through the
RMSNorm (root-mean-square normalization) divides a vector by its RMS. So the scores depend on the direction of each layer's output, not its magnitude. It applies to the keys only: the values stay raw. Without it, layers with bigger outputs would dominate the softmax. In the paper's ablation, removing it raises the loss from 1.737 to 1.743.
is zero-initialized. When , all dot products are 0, softmax gives uniform weights. Start from democracy, learn to specialize. LoRA (low-rank adaptation) uses the same trick: its update matrix starts at zero.
Figure: one depth-attention step for layer 5 at step 0. The zero query gives every source the same score, so each weight is 0.2 and h5 is the average of the five raw sources.
import torch
import torch.nn.functional as F
w = torch.zeros(512) # zero-initialized query
keys = torch.randn(8, 512) # 8 checkpoint states
scores = keys @ w # one score per checkpoint
weights = F.softmax(scores, dim=0)
print("Weights:", [f"{v:.4f}" for v in weights.tolist()])
# [0.1250, 0.1250, 0.1250, 0.1250, 0.1250, 0.1250, 0.1250, 0.1250]-> all dot products are 0 -> softmax gives uniform 1/8 weights. You start from averaging everything equally (which is reasonable), then the model learns to specialize.
The zero-init of the last BatchNorm scale in each ResNet block (Goyal et al., 2017) follows the same principle.
full attnres vs block attnres
Full AttnRes lets every layer attend over all previous outputs. Per token, that costs compute and memory. On one GPU this is cheap, because backprop keeps those outputs in memory anyway. At scale it gets expensive: with activation recomputation and pipeline parallelism, the system must now keep all outputs and send them between devices.
# Full AttnRes: depth attention before EVERY layer
sources = [x] # v_0 = token embedding
for i, f in enumerate(layers): # f = one attention or MLP layer, no residual add
h = depth_attns[i](sources) # attend over all previous outputs
sources.append(f(h)) # list grows: 1, 2, 3, ... LLayer 32 attends over 32 sources (the embedding plus 31 outputs). Layer 64 attends over 64. The source list grows linearly, and each attention call scales with its length.
Block AttnRes is the version Moonshot trains at scale. Split the 64 layers into 8 blocks of 8. Inside a block, layer outputs add up into a partial sum, like a standard residual stream. Depth attention still runs before every layer, but only over the finished block sums and the current partial sum:
- is the token embedding
- Layers 1-8: layer 1 attends over , and each later layer attends over plus the partial sum. After layer 8, the partial sum becomes
- Layers 9-16: each layer attends over plus the partial sum. After layer 16, it becomes
- ...repeat. A layer in the last block attends over at most 9 sources: to plus the partial sum
Figure: Block AttnRes on a small 12-layer model with blocks of 4. Layer 11 attends over the embedding, the two finished block sums and the partial sum of layers 9 and 10. Its output joins the partial sum.
Magnitude grows only inside each block. The softmax-weighted average before the next layer resets it, and the paper's Figure 5b shows this repeating pattern.
the code
This is the whole thing. DepthAttention is ~15 lines, the rest is wiring it into the existing transformer:
import torch
import torch.nn as nn
import torch.nn.functional as F
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
class DepthAttention(nn.Module):
"""Softmax attention over earlier sources, one learned query per layer."""
def __init__(self, dim):
super().__init__()
self.query = nn.Parameter(torch.zeros(dim)) # zero-init!
self.norm = RMSNorm(dim)
def forward(self, sources):
# sources: list of (B, T, D) tensors
V = torch.stack(sources) # (N, B, T, D)
K = self.norm(V) # keys are normalized, values are not
scores = torch.einsum('d, n b t d -> n b t', self.query, K)
weights = F.softmax(scores, dim=0) # softmax over depth
return (weights.unsqueeze(-1) * V).sum(dim=0) # (B, T, D)
class TransformerBlock(nn.Module):
def __init__(self, dim, n_head, mlp_hidden_dim):
super().__init__()
self.norm1 = RMSNorm(dim)
self.attn = nn.MultiheadAttention(dim, n_head, batch_first=True)
self.norm2 = RMSNorm(dim)
self.mlp = nn.Sequential(
nn.Linear(dim, mlp_hidden_dim), nn.SiLU(),
nn.Linear(mlp_hidden_dim, dim),
)
def attn_out(self, x): # f for the attention layer (no residual add)
normed = self.norm1(x)
T = x.size(1)
mask = torch.triu(torch.ones(T, T, dtype=torch.bool, device=x.device), 1)
return self.attn(normed, normed, normed, attn_mask=mask)[0]
def mlp_out(self, x): # f for the MLP layer (no residual add)
return self.mlp(self.norm2(x))
def forward(self, x): # standard PreNorm residual
x = x + self.attn_out(x)
x = x + self.mlp_out(x)
return x
class TransformerWithBlockAttnRes(nn.Module):
def __init__(self, vocab_size, dim, n_layers, n_head, block_size=8):
super().__init__()
# the paper counts attention and MLP as separate layers: 2 per TransformerBlock
assert (2 * n_layers) % block_size == 0
self.block_size = block_size
self.token_embeddings = nn.Embedding(vocab_size, dim)
self.layers = nn.ModuleList([
TransformerBlock(dim, n_head, 4 * dim)
for _ in range(n_layers)
])
# one DepthAttention before every attention and MLP layer, plus one before the output
self.depth_attns = nn.ModuleList([
DepthAttention(dim) for _ in range(2 * n_layers + 1)
])
self.norm_final = RMSNorm(dim)
self.lm_head = nn.Linear(dim, vocab_size, bias=False)
def forward(self, idx):
blocks = [self.token_embeddings(idx)] # b_0 = token embedding
partial = None # running sum inside the current block
sublayers = [f for layer in self.layers for f in (layer.attn_out, layer.mlp_out)]
for i, f in enumerate(sublayers):
sources = blocks if partial is None else blocks + [partial]
h = self.depth_attns[i](sources)
out = f(h)
partial = out if partial is None else partial + out
if (i + 1) % self.block_size == 0: # block boundary
blocks.append(partial)
partial = None
h = self.depth_attns[-1](blocks if partial is None else blocks + [partial])
return self.lm_head(self.norm_final(h))# test it
model = TransformerWithBlockAttnRes(vocab_size=1000, dim=256, n_layers=32, n_head=4, block_size=8)
idx = torch.randint(0, 1000, (2, 64))
out = model(idx)
print(f"Input: {idx.shape}") # (2, 64)
print(f"Output: {out.shape}") # (2, 64, 1000)
print(f"Depth attention modules: {len(model.depth_attns)}") # 65The diff from a standard PreNorm transformer is small. TransformerBlock keeps its weights. Its forward splits into attn_out and mlp_out, so the model can call each layer without the residual add. You add DepthAttention modules and change the forward loop to track block sums. ~30 lines of new code. The test model has 32 transformer blocks, so 64 layers in 8 blocks of 8, the same shape as the example above.
The cost is small. Each layer adds one -dim query and one RMSNorm weight vector, so parameters. For the test model that is 33,280 extra parameters, 0.13% of its 25.8M. The compute per token per layer is one dot product and one weighted sum over at most 9 sources. The paper reports under 4% training overhead with pipeline parallelism, negligible overhead without it, and under 2% inference latency overhead.
results
Kimi Linear: a 48B-parameter mixture-of-experts model with 3B active parameters, trained on 1.4T tokens. Block AttnRes against the same model with standard residuals.
| Benchmark | Baseline | + AttnRes | Delta |
|---|---|---|---|
| MMLU | 73.5 | 74.6 | +1.1 |
| GPQA-Diamond | 36.9 | 44.4 | +7.5 |
| BBH | 76.3 | 78.0 | +1.7 |
| Math (Minerva) | 53.5 | 57.1 | +3.6 |
| HumanEval | 59.1 | 62.2 | +3.1 |
| MBPP | 72.0 | 73.9 | +1.9 |
These are 6 of the 15 benchmarks in the paper's Table 3. AttnRes matches or beats the baseline on all 15. In the scaling-law runs, Block AttnRes matches the loss of a baseline trained with 1.25x more compute. The +7.5 on GPQA-Diamond is wild for 30 lines of code.
Problem: these are Moonshot's internal runs at massive scale. The official repo has the paper and PyTorch-style pseudocode, not training code. Reproducing these numbers needs their data and compute.
When I run it on my system, trained as a character-level language model. The data is the markdown source of two of my posts (math and how ChatGPT works). The setup is dim 128 and 8 transformer blocks, so 16 layers in 4 AttnRes blocks of 4. Training uses AdamW at learning rate 1e-3 for 600 steps with batches of 32 sequences of 128 characters, on the M4 CPU.
The baseline is the same model with the standard residual forward pass. Validation loss is the mean over 20 held-out batches.
| Run | Val loss, seed 0 | Val loss, seed 1 | Wall time per run |
|---|---|---|---|
| Standard residual | 2.353 | 2.351 | 118 s, 106 s |
| Block AttnRes | 2.310 | 2.352 | 226 s, 203 s |
At laptop scale it's a coin flip. Seed 0 favors AttnRes by 0.04, seed 1 is a tie, and two seeds can't separate that from noise. AttnRes took about 2x the wall time, because my Python loop runs every depth attention as separate small ops. The paper's smallest model already has 194M active parameters and trains on 38.7B tokens. That's where the gains show up...
when this doesn't work
Ziming Liu (the KAN guy) makes a good no-free-lunch argument: if AttnRes wins on language modeling, it has to lose somewhere else.
He builds a toy experiment with MLP-only networks. He mixes the labels of a linear task and a random memorization task, then compares training loss at 4, 10 and 30 blocks. The result:
- On structured data (the linear end), AttnRes wins.
- On memorization data (random input-output pairs), standard residuals win. AttnRes hurts.
Depth makes the memorization gap worse. At 30 blocks on pure random labels, AttnRes ends at about 0.35 training loss against about 0.11 for standard residuals. At that depth its win on the linear end is gone. At 4 and 10 blocks, AttnRes reaches about 0.001 on the linear task against about 0.01 for standard residuals. I read these values off his log-scale plot.
Why? Liu offers a guess and calls it intuition, not proof. The zero-init trick that makes AttnRes safe also makes it dumb at the start. When , all weights are uniform: . That's pure averaging.
The model has to learn its way out of this averaging regime before it can do anything useful. For memorization, every layer must add its own signal, so that averaging phase may be a tax the model never recovers from. Liu also notes that his zero init may cause this bias, and a non-zero init may reduce it.
Liu frames the trade-off as stability vs expressivity. Softmax bounds the weights (they sum to 1), which stabilizes training but caps how much any single layer can contribute. Standard residuals let layers contribute unbounded signal. That gives messier gradients, but more raw capacity for brute-force memorization.
Language modeling is mostly structured (syntax, semantics, reasoning patterns). Liu reads Kimi's gains as a sign of that structure. But if your task is closer to lookup tables than language, don't assume this is a free upgrade.
transformer++ upgrade list
The running list of things that make modern LLMs better than the 2017 transformer:
- LayerNorm RMSNorm
- ReLU SwiGLU
- Absolute positional encoding RoPE (rotary position embeddings)
- Post-Norm Pre-Norm
- Standard residual Attention residual (new)
The attention and MLP code inside each layer stays the same. The change is one level up: how the model combines layer outputs into each layer's input.
what else are we not questioning?
The residual weight was 1.0 for a decade. Softmax temperature is always 1/sqrt(d). Position information is always added or rotated in, never concatenated. Layer count is always uniform across the model. Somewhere in there is another 30-line patch worth +7.5 on GPQA.
references
- Attention Residuals, Moonshot AI (Kimi team)
- When does Kimi's Attention Residuals work?, Ziming Liu's no-free-lunch analysis
- Attention Residuals repo (paper and pseudocode)
- Deep Residual Learning (ResNet)
- Accurate, Large Minibatch SGD, Goyal et al., the zero-init BatchNorm scale
- LoRA, Hu et al.
- My CIFAR-10 ResNet implementation
- Vanishing gradients explained, from my math post
- Backpropagation from scratch, from my neural networks post
- Transformers: attention, residuals in the transformer block
- AttnRes notebook, standalone implementation with weight heatmap visualizations, by Arjun