Attention Residuals: Replacing Fixed Skip Connections with Learned Depth-Wise Attention
Building Attention Residuals from scratch — why standard residuals dilute information, how softmax attention over depth fixes it, the block variant that makes it practical, and the structured-matrix view that unifies everything — all derived step by step with a 4-layer running example
Residual connections are the backbone of every modern deep network. The update rule is so universal that we rarely question it. But this simplicity hides a rigid design choice: every previous layer’s output is accumulated with a fixed weight of 1. There is no mechanism for a later layer to say “I need the embedding more than I need layer 3’s output” or “layer 7’s contribution is irrelevant to me.”
The Attention Residuals paper (Kimi Team, 2026) proposes a direct fix: replace the fixed accumulation with learned, input-dependent softmax attention over all previous layer outputs. The idea is clean — apply the same attention mechanism that Transformers use over the sequence dimension, but now over the depth dimension.
We will derive everything from scratch using a single running example: a tiny network with layers and scalar hidden states (). By the end, we will have built up to Full Attention Residuals, Block Attention Residuals, and the structured-matrix view that reveals standard residuals, Highway networks, Hyper-Connections, and AttnRes as points on a single spectrum.
1. Standard Residual Connections
1.1 The Recurrence
A residual connection adds the output of a layer to its input, preserving an identity path through the network. The hidden state at layer is:
where is the transformation applied by layer (an attention sub-layer or an MLP sub-layer in a Transformer), and is the token embedding.
Let us define (the embedding) and for (each layer’s output). Then we can unroll the recurrence.
1.2 Unrolling the Recurrence
For our 4-layer network:
The general form is:
Every layer receives the uniform sum of all previous layer outputs. The coefficient on every term is exactly 1 — no more, no less.
1.3 Numerical Check
Let our scalar example have , , , . Then:
Each hidden state is a simple running total. Layer 4 has no choice but to accept the sum . It cannot “turn down” or “amplify” .
1.4 The Depth Mixing Matrix
We can write the full system as a matrix equation. Define the depth mixing matrix where is the weight that layer assigns to the output of layer . For standard residuals, for all :
This is an all-ones lower-triangular matrix. Every entry below and including the diagonal is 1. There is zero selectivity.
1.5 Numerical Check (Matrix Form)
Using our values :
Checking row 4: . Matches.
2. Why Fixed Accumulation Is a Problem
2.1 The PreNorm Dilution Problem
In practice, modern LLMs use PreNorm — applying layer normalization before each sub-layer rather than after. PreNorm restores a clean identity path and stabilizes gradients, making it the dominant paradigm.
But PreNorm introduces a subtle problem. Since grows as with depth (by the unrolled recurrence above), and PreNorm normalizes before the transformation, each layer’s relative contribution gets progressively diluted. The embedding that was 100% of is only a fraction of .
For our example with : , and contributes . With , the embedding would contribute roughly of the hidden state magnitude.
This has a concrete consequence: deeper layers must learn increasingly larger outputs just to remain influential. Empirically, the paper shows that output magnitudes grow monotonically with depth in baseline models — a direct symptom of this dilution.
2.2 Three Limitations of Single-State Recurrence
Whether we use fixed weights (standard residuals) or learned gates (Highway networks), every approach that conditions only on shares three limitations:
-
No selective access. Different layer types (attention vs. MLP) receive the same aggregated state, despite potentially benefiting from different weightings of past layers.
-
Irreversible loss. Once information is mixed into the running sum, it cannot be selectively recovered. If partially cancels in the sum, layer 5 cannot “undo” this.
-
Output growth. Later layers must learn increasingly larger outputs to influence the accumulated residual, which can destabilize training.
3. The Time-Depth Duality
This is the central insight of the paper. It is worth slowing down for.
3.1 RNNs Compress Over Time
A recurrent neural network (RNN) processes a sequence by maintaining a single hidden state that compresses all past tokens:
This is structurally identical to the residual update . The RNN compresses over time steps ; the residual connection compresses over layers . Both maintain a single state that accumulates all prior contributions with fixed weights.
3.2 Attention Replaced RNNs Over Time
The Transformer solved the RNN bottleneck by replacing the fixed recurrence with attention: each position can selectively access all previous positions with learned, data-dependent weights. This was the linear-to-softmax transition for the sequence dimension.
3.3 AttnRes Applies the Same Fix Over Depth
Attention Residuals propose the exact same transition for depth. Instead of compressing all previous layers into a single running sum, each layer selectively attends to all previous layer outputs with learned, input-dependent weights via softmax.
The analogy is precise:
| Sequence (RNN → Transformer) | Depth (Residual → AttnRes) | |
|---|---|---|
| State | (hidden state) | (hidden state) |
| Sources | Past tokens | Past layer outputs |
| Fixed mixing | RNN recurrence | Residual sum |
| Selective mixing | Sequence attention | Depth attention (AttnRes) |
Standard residuals and prior recurrence-based variants can all be shown to perform depth-wise linear attention. AttnRes generalizes them to depth-wise softmax attention — completing for depth the same linear-to-softmax transition that proved transformative for sequences.
4. Full Attention Residuals
4.1 The Attention Weights
We now define the attention mechanism over depth. For each layer , the attention weight that layer assigns to source is:
where is a kernel function. The paper uses:
This is the standard softmax attention formula — the softmax function ensures the weights sum to 1 across all sources. The RMSNorm inside prevents layers with naturally larger outputs from dominating the attention weights.
4.2 Queries, Keys, and Values
For each layer , we define:
Query: , a learned -dimensional vector specific to layer . This is a pseudo-query — it is a parameter, not a function of the hidden state.
Keys and Values:
The keys and values are identical — both are the individual layer outputs. This is a deliberate design choice: the pseudo-query is decoupled from the forward computation, meaning attention weights for all layers in a group can be computed in parallel.
4.3 The Full AttnRes Formula
The input to layer is then:
Compare this with the standard residual: . The only change is replacing the fixed coefficient 1 with the learned attention weight . But because these weights are softmax-normalized and input-dependent, each layer can now selectively emphasize or suppress any previous layer’s contribution.
4.4 Numerical Example
Let us work through Full AttnRes for our 4-layer scalar example. Since , each query and each key is a scalar. Suppose:
- Layer outputs: , , ,
- Pseudo-queries: , , ,
For simplicity, let us skip the RMSNorm (in it just normalizes to ) and compute raw directly on unnormalized values for illustration.
Layer 2 attends over sources with query :
Compare with the standard residual: . AttnRes produces a weighted combination that sums to a different value — and crucially, the weights are normalized so the magnitude does not grow uncontrollably.
4.5 The Depth Mixing Matrix for Full AttnRes
For Full AttnRes, the mixing matrix has entries :
(Each row is normalized by its row sum.) This is a dense, input-dependent, lower-triangular matrix with rank — the maximum possible. Contrast this with the all-ones matrix of standard residuals.
4.6 Overhead and Feasibility
Full AttnRes requires computation and memory to store all layer outputs. The computation cost is modest because in practice (unlike sequence length which can reach millions). The memory overlaps entirely with activations already retained for backpropagation in standard training.
However, at scale with pipeline parallelism and activation recomputation, every layer output must be kept alive and transmitted across pipeline stages, making the memory and communication prohibitive. This motivates the Block variant.
5. Block Attention Residuals
5.1 The Idea: Compress Within Blocks, Attend Across Blocks
Block Attention Residuals (Block AttnRes) partition the layers into blocks of layers each. Within each block, layer outputs are accumulated via standard summation. Across blocks, we apply full attention over the block-level representations.
This reduces memory from to and computation from to .
5.2 Intra-Block Accumulation
We divide our layers into blocks of layers each. Let and . The block representation is the sum of layer outputs within the block:
For our example:
We also track partial sums within each block. Define as the partial sum over the first layers in block :
5.3 Inter-Block Attention
For the first layer in block , the value matrix consists of all previous block representations plus the embedding :
For subsequent layers within block , we additionally include the current block’s partial sum :
Keys and attention weights follow the same kernel from Eq. 2 and Eq. 3 (Section 4.1–4.2), with the block representations serving as both keys and values.
5.4 Walking Through Block AttnRes
For our , example with and :
Layer 3 (first layer of block 2) attends over :
Layer 4 (second layer of block 2) attends over where . So it sees sources instead of , gaining one extra source for the intra-block partial sum.
5.5 The Block AttnRes Mixing Matrix
For our , example, the mixing matrix is:
Notice the key difference from Full AttnRes: layers within a completed block share the same combined key . The individual layer-level granularity is lost in exchange for a dramatic reduction in the number of sources from to approximately .
5.6 Interpolating Between Extremes
The block count controls a smooth interpolation:
- : Each block has one layer (). Every layer output is its own block. This recovers Full AttnRes.
- : All layers are in one block. Intra-block summation reduces to standard addition. This recovers standard residual connections with the embedding isolated as .
Empirically, recovers most of the gain of Full AttnRes. For the 48B-parameter Kimi Linear model with 54 layers, Block AttnRes uses 6 layers per block, producing 9 blocks plus the token embedding for a total of 10 depth-wise sources.
6. The Two-Phase Computation Strategy
A naive implementation of Block AttnRes would compute attention at every layer, each requiring a full pass over all preceding blocks — resulting in total memory accesses. The paper introduces a two-phase strategy that exploits a key property: the pseudo-queries are learned parameters decoupled from the forward computation.
6.1 Phase 1: Parallel Inter-Block Attention
Because the pseudo-queries are parameters (not functions of ), we can batch all queries within a block and compute their attention over all previous blocks simultaneously:
This single batched attention call returns, for each layer in the block, the inter-block attention output along with its softmax statistics (the max and log-sum-exp ). This amortizes the memory reads from reads down to 1 read per block.
6.2 Phase 2: Sequential Intra-Block Attention with Online Softmax Merge
Phase 2 processes layers sequentially within the block. For each layer (after the first in the block), it computes intra-block attention over the evolving partial sum , obtaining output with statistics and .
The two sets of attention outputs are then merged using the online softmax algorithm. This is a numerically stable method for combining two softmax computations that were performed independently. The merge computes:
This is mathematically equivalent to computing softmax over all sources jointly, but avoids materializing the full attention matrix. The subtraction of from both exponents prevents numerical overflow — this is the same log-sum-exp trick used in FlashAttention and standard stable softmax implementations.
6.3 Numerical Check of Online Softmax Merge
Suppose Phase 1 gives with , , and Phase 2 gives with , .
The key property: this gives the same result as if we had computed softmax attention over all sources jointly. The online merge introduces zero approximation error.
6.4 Memory Access Cost
The total per-layer memory access cost for Block AttnRes with the two-phase strategy is:
| Read | Write | |
|---|---|---|
| Phase 1 (amortized) | ||
| Phase 2 | ||
| Total |
With typical values , , : total reads = , total writes = , for a grand total of . Compare this with standard residuals at — the overhead is modest. The end-to-end inference latency overhead is less than 2% on typical workloads.
7. The Structured-Matrix View: Unifying All Residual Variants
This is the part that ties everything together. We have seen that standard residuals, Highway networks, Hyper-Connections, and AttnRes all compute for different choices of the depth mixing matrix . The paper formalizes this and shows that the variants differ in three properties: whether the weights are fixed or learned, whether they are input-dependent, and the semiseparable rank of .
7.1 Standard Residuals: All-Ones Matrix
As derived in Section 1.4:
Weights: fixed. Input-dependent: no. The matrix has the simplest possible structure.
7.2 Highway Networks: Gated Carry Products
Highway networks introduce element-wise gates that interpolate between the identity path and the transformation:
For scalar clarity, define the carry product . This represents how much of source ‘s output survives through all subsequent gates to reach layer . The mixing matrix entries are:
7.3 Numerical Check of Highway Carry Products
Let , , , . Compute the carry products for layer 4:
Wait — we need to be careful about indexing. Let us redo this with the paper’s convention. The gate is applied at layer . The carry product from source to layer is:
For (embedding reaching layer 4):
The Highway mixing matrix for our example:
The key structural property: since the cumulative products factor through scalar gates, is 1-semiseparable — the same rank as the standard residual, but with input-dependent weights. The weights sum to 1 by construction (each row partitions probability mass between “carry” and “transform”), making Highway a softmax-free, depth-wise instance of stick-breaking attention.
7.4 (m)Hyper-Connections: Multi-Stream Matrices
Hyper-Connections (HC) and their manifold-constrained variant mHC widen the recurrence to parallel streams. The update is:
where is a learned transition matrix, mixes streams into a single input for , and distributes the output back across streams.
Unrolling this recurrence gives:
where is the cumulative matrix product of transitions. The transitions render -semiseparable. mHC further constrains each to be doubly stochastic (by the Birkhoff–von Neumann theorem, every doubly stochastic matrix is a convex combination of permutation matrices), stabilizing the cumulative products across depth.
7.5 Full AttnRes: Dense, Input-Dependent
Full AttnRes computes:
where are the layer outputs. This yields a dense, rank- lower-triangular matrix. Every entry is input-dependent (through the keys) and the weights are softmax-normalized.
7.6 Block AttnRes: Controlled Rank
Block AttnRes shares weights within completed blocks: for all in a completed block , (the same weight for all sources in the block). Within the current block, each layer additionally attends to the evolving partial sum . The effective rank of lies between and , interpolating between standard residuals () and Full AttnRes ().
7.7 The Spectrum
We can now arrange all variants along a spectrum of increasing expressiveness:
| Method | Weight type | Input-dependent? | Rank of |
|---|---|---|---|
| Standard Residual | Fixed (all 1s) | No | 1 |
| Highway | Learned (gates) | Yes | 1 |
| (m)HC | Learned (matrices) | Yes | |
| Block AttnRes | Learned (softmax) | Yes | to |
| Full AttnRes | Learned (softmax) | Yes |
The insight is that these are not separate inventions — they are points on a single axis of increasing rank in the depth mixing matrix, with AttnRes at the maximum.
8. Prior Residuals as Depth-Wise Linear Attention
This section makes the time-depth duality from Section 3 mathematically precise.
8.1 The (m)HC Weight as Linear Attention
Recall the unrolled (m)HC weight from Section 7.4:
This admits a natural interpretation as linear attention over depth. The vector plays the role of a query issued by layer . The vector serves as a key summarizing the contribution of layer . The cumulative transition acts as a depth-relative positional operator governing the query-key interaction across intervening layers.
The parallel streams correspond to state expansion along the depth axis, expanding the recurrent state from to . This is directly analogous to how multi-head attention expands representation capacity along the sequence axis.
8.2 From Linear to Softmax Attention Over Depth
Standard residuals and Highway networks perform depth-wise attention with rank-1 matrices — the simplest case. (m)HC extends this to rank- linear attention. AttnRes goes further and replaces the linear kernel with softmax normalization via the kernel .
This is the same transition that took RNNs (linear attention with state compression) to Transformers (softmax attention with direct access) — but applied to the depth dimension rather than the sequence dimension.
9. Initialization and Training Dynamics
9.1 Zero Initialization of Pseudo-Queries
A critical implementation detail: all pseudo-query vectors must be initialized to zero. When for all :
for all sources . This means:
At initialization, every layer assigns equal weight to all previous sources — AttnRes starts as a uniform average, then learns to specialize during training. This prevents training volatility from random initial attention patterns.
9.2 How AttnRes Fixes PreNorm Dilution
Recall the dilution problem from Section 2.1: in standard residuals, grows as because every layer output is added with weight 1. With AttnRes, the weights sum to 1 by the definition of softmax. The hidden state is a convex combination of previous outputs rather than their sum:
The last inequality follows from the triangle inequality and the fact that (this is the convexity of the weighted average). The hidden state magnitude is bounded by the largest individual layer output, not their cumulative sum.
For Block AttnRes, the selective aggregation resets at block boundaries, confining the growth within each block. The paper shows empirically that this yields a bounded periodic pattern in output magnitudes — a dramatic improvement over the monotonic growth of the baseline.
9.3 Gradient Distribution
With standard residuals, the gradient with respect to an intermediate hidden state is:
All residual weights are fixed at 1, so there is no mechanism to regulate gradient flow across depth. This leads to disproportionately large gradients in the earliest layers.
With AttnRes, the learnable softmax weights introduce competition among sources for probability mass. This naturally distributes gradients more uniformly across depth — the paper shows substantially more uniform gradient magnitudes across transformer blocks compared to the baseline.
10. Learned Attention Patterns
10.1 What the Network Actually Learns
The paper visualizes the learned weights for a 16-head model with both Full and Block AttnRes. Three patterns emerge:
Preserved locality. Each layer attends most strongly to its immediate predecessor — the diagonal of the attention matrix dominates. This makes sense: the standard residual (which is purely local) works well, so the learned weights should stay close to it unless there is reason to deviate.
Selective long-range connections. Despite the diagonal dominance, selective off-diagonal concentrations emerge. For example, layer 4 attending to early sources, or layers 15–16 reaching back to the first few layers. These are learned skip connections beyond the standard residual path.
Embedding persistence. The token embedding (source 0) retains non-trivial weight throughout the network, especially in pre-attention layers. This is consistent with the embedding carrying fundamental token identity information that remains relevant at all depths.
10.2 Attention vs. MLP Specialization
Pre-attention inputs show broader receptive fields (attending to sources across a wider range of depths), while pre-MLP inputs show sharper diagonal reliance on recent representations. This specialization is consistent with attention layers operating more globally across depth while MLPs refine locally — a distinction that standard residuals cannot express.
11. Experimental Results
11.1 Scaling Laws
The paper trains five model sizes (194M to 528M activated parameters) with three variants each: PreNorm baseline, Full AttnRes, and Block AttnRes ().
Fitting power-law curves (where is compute in PFLOP/s-days):
- Baseline:
- Block AttnRes:
- Full AttnRes:
All three variants share similar scaling exponents, but AttnRes achieves consistently lower loss across the entire compute range. At the largest scale (5.6 PFLOP/s-days), Block AttnRes reaches 1.692 versus the baseline’s 1.714 — equivalent to a compute advantage.
11.2 48B Parameter Model
The full-scale model uses Block AttnRes on the Kimi Linear architecture (48B total / 3B activated parameters), pre-trained on 1.4T tokens. Results across 16 benchmarks:
- General knowledge: MMLU +1.1, BBH +1.7, GPQA-Diamond +7.5
- Math and code: GSM8K +0.7, Math +3.6, CMath +0.4, HumanEval +3.1, MBPP +1.9
- Chinese: CMMLU +0.9, C-Eval +2.9
Block AttnRes matches or outperforms the baseline on every benchmark. The improvements are particularly pronounced on multi-step reasoning tasks (GPQA-Diamond, Math), consistent with the hypothesis that improved depth-wise information flow benefits compositional tasks where later layers need to selectively retrieve and build upon earlier representations.
11.3 Ablation Highlights
Key ablation findings on a 16-layer model:
| Variant | Loss |
|---|---|
| Baseline (PreNorm) | 1.766 |
| DenseFormer (fixed cross-layer weights) | 1.767 |
| mHC ( streams) | 1.747 |
| Full AttnRes | 1.737 |
| Block AttnRes () | 1.746 |
| w/ input-dependent query | 1.731 |
| w/ input-independent mixing | 1.749 |
| w/ sigmoid instead of softmax | 1.741 |
| w/o RMSNorm on keys | 1.743 |
DenseFormer grants cross-layer access but with fixed, input-independent coefficients — it shows no gain over the baseline, highlighting the importance of input-dependent weighting. Replacing softmax with sigmoid degrades performance, which the paper attributes to softmax’s competitive normalization forcing sharper selection among sources. Removing RMSNorm on keys degrades both Full and Block AttnRes, confirming that preventing large-magnitude layers from dominating the attention weights is essential.
12. Summary
Standard residual connections accumulate all previous layer outputs with fixed unit weights, producing an all-ones depth mixing matrix that offers zero selectivity and causes hidden-state magnitudes to grow as under PreNorm — the dilution problem. Attention Residuals replace this fixed accumulation with learned softmax attention over depth, where each layer uses a single pseudo-query vector to selectively weight all previous layer outputs, yielding a dense, input-dependent mixing matrix with maximum rank. Block AttnRes makes this practical at scale by compressing layers into blocks with standard summation within blocks and full attention across block representations, reducing memory from to while recovering most of the gain with — a two-phase computation strategy with online softmax merging keeps inference overhead below 2%.
Previous: Mixture of Experts from Scratch — Part 2
Next: Mathematical Prerequisites for Mixture of Experts — Part 3
Enjoyed this post?
Subscribe to get notified when I publish new posts. No spam, unsubscribe anytime.