Attention Residuals: Letting Each Layer Pick What to Read From the Layers Before It
Attention Residuals (AttnRes) is Kimi's March 2026 fix for residual connections: it swaps the fixed weight-1 sum over earlier layers for softmax attention over their outputs. This post reviews the paper, recomputes its numbers and tests the idea on a small model.
On this page
- Why this paper is worth reading
- Background: what a PreNorm residual does
- The method: AttnRes
- Full AttnRes
- Block AttnRes
- Systems: making it fit training and inference
- Check it yourself: the numbers that can be recomputed
- The paper’s experiments and conclusions
- Hands-on: the three residual schemes in a small model
- Limitations and what comes next
- What to take from this paper
- Further reading
- FAQ
The paper “Attention Residuals” (Kimi Team, AttnRes below) changes the least conspicuous part of a Transformer: the residual connection. A standard PreNorm residual gives every layer the same input, the embedding plus the outputs of all earlier layers, each with weight 1. AttnRes replaces that equal-weight sum with softmax attention over the earlier layers’ outputs. Each layer adds one learned vector (a pseudo-query , initialized to zero) and uses it to decide, from content, which layers to read and how much. To make this affordable at scale, the paper groups the layers into about 8 blocks (Block AttnRes) and attends only at block level. It reports that Block AttnRes matches a baseline trained with 1.25 times the compute; added to Kimi Linear (48B total, 3B active parameters) and pre-trained on 1.4T tokens, it is at least as good as the baseline on all 15 downstream benchmarks, with GPQA-Diamond up 7.5 points; the extra training cost under pipeline parallelism is under 4% and the extra inference latency under 2%.
The paper appeared on arXiv on 16 March 2026 (v1, which this post follows). It is a technical report, and the code is at MoonshotAI/Attention-Residuals. The headline result needs a 48B training run, which I cannot reproduce. This post does two things. First, it recomputes the numbers that can be recomputed from formulas and the paper’s own parameters (the 1.25x in the scaling fits, Table 1’s reads and writes, pipeline communication, prefill memory, Table 3’s gains). Second, it implements the three residual schemes in a 1.4M-parameter byte-level model to see whether the paper’s qualitative effects show up at small scale. The recomputed numbers hold, except that “Full AttnRes beats mHC” fails at one scale in Table 2, and the 15 GB prefill example needs a hidden size of about 7,168 while Kimi Linear 48B has 2,304; at small scale, all six Full and Block AttnRes runs finish below the three baseline runs in validation bpb, by 0.0540 and 0.0328 on average (5.9 and 3.6 times the baseline’s seed-to-seed standard deviation of 0.0091), while the 0.0211 between Full and Block is within the noise; the baseline’s hidden-state magnitude grows with depth and the AttnRes inputs do not, but the paper’s “each layer looks hardest at its immediate predecessor” does not show up in this small model.
Why this paper is worth reading
- It changes a structure everyone has taken for granted for ten years. Residual connections give gradients a direct path, but they also decree that layer outputs are added with a fixed weight of 1, and almost nobody has touched that. HC and mHC change the width of the residual stream; AttnRes changes how depth is aggregated.
- The argument rests on a neat analogy. Residuals accumulate over depth the way an RNN accumulates over time. The Transformer replaced recurrence over time with attention, and AttnRes does the same over depth. The paper also argues, in the language of “depth-mixing matrices”, that the standard residual, Highway and HC can be seen as linear attention over depth and AttnRes as softmax attention.
- The cost is small and the mechanism is small. One vector and one RMSNorm per layer; blocks tie memory and communication to the block count rather than the layer count; and the systems design (cross-stage caching, two-phase inference) shows how it fits into real training and serving stacks.
- It sits next to two earlier posts on this site. The mHC explainer covers another route at the same spot, and the DeepSeek-V3 explainer covers the MoE and MLA backbone that Kimi Linear builds on.
Background: what a PreNorm residual does
The standard update is . The paper counts every self-attention and every MLP as a separate layer (so below is the number of sublayers, twice the usual “number of Transformer blocks”). Unrolling gives:
Every layer therefore receives the embedding plus all earlier outputs, with weight exactly 1. That is good for gradients (the identity term is always kept), but it has three limits for representations, which the paper lists:
- No selectivity. An attention layer and an MLP layer get the same sum, although they may want different mixes.
- Irreversible loss. Once the outputs are added, later layers cannot retrieve any single layer’s contribution.
- Growing outputs. PreNorm normalizes only the input to each sublayer, not the residual stream itself. The stream’s magnitude grows with depth (the paper says as ), and to be heard over an ever larger sum, later layers must learn ever larger outputs. The paper calls this PreNorm dilution.
The paper puts this in a bigger analogy: a residual stream squeezes all earlier information into one state over depth, just as an RNN squeezes it into a hidden state over time. The Transformer replaced the recurrence over time with attention, letting each position read all earlier positions by content; AttnRes does the same over depth. Depth is modest (), so attention over depth is affordable.
The method: AttnRes
Full AttnRes
The input to layer is no longer an equal-weight sum but a weighted sum over the earlier sources (the paper’s Eqs. 1 to 4):
The weights are softmax attention, with queries, keys and values chosen like this:
Three points matter:
- The query is one learned vector per layer (the pseudo-query ), independent of the current input; keys and values are the sources themselves, so the weights still vary with the input. In the paper’s ablation, projecting the query from the current hidden state lowers the loss further to 1.731, but it costs a projection per layer and forces sequential memory access in decoding, so the default is the learned vector.
- RMSNorm on the keys stops layers with large-magnitude outputs from dominating the softmax. Without it Full becomes 1.743 and Block 1.750 (against 1.737 and 1.746).
- Pseudo-queries must be initialized to zero, so the initial weights are uniform and AttnRes starts as an equal-weight average; the paper says this avoids training volatility, as validated experimentally.
Full AttnRes costs arithmetic and memory per token. In ordinary training the outputs have to be kept for backpropagation anyway, so there is no extra memory; but large-scale training uses activation recomputation and pipeline parallelism, which force these outputs to be kept explicitly and sent across stages, and the cost then grows as .
Block AttnRes
Block AttnRes splits the layers into blocks of layers. Inside a block the layer outputs are simply summed into one block representation ; attention happens only between blocks. With (the embedding is always a source), the sources for the -th layer of block are
where is the partial sum of the first layers of the current block. The output layer aggregates all block representations. The block count interpolates between two extremes: is Full AttnRes, and reduces to a plain residual with the embedding kept apart. The paper finds that recovers most of the gain, needing to store only eight hidden states per token.
Figure 1 looks at the three schemes through the “depth-mixing matrix” of the paper’s Section 6.2: row holds the weights layer gives its sources. The standard residual is an all-ones lower-triangular matrix. Highway and HC replace it with weights built from gates or small matrices multiplied together (semiseparable matrices whose rank is limited to 1 and respectively). Full AttnRes is a dense matrix whose weights depend on the input, that is, softmax attention over depth. Block AttnRes is block-structured, with an effective rank between and .
Systems: making it fit training and inference
For AttnRes to enter a real training stack, the paper spends a section on systems design. Here is the core.
Training: cross-stage caching. Under pipeline parallelism each stage needs all earlier block representations. The paper considers an interleaved schedule with physical stages and virtual stages each, chunks in all, and on average block representations produced per physical stage. The naive approach resends the full history at every stage transition, for a total communication (Eq. 7) of:
Cross-stage caching keeps the blocks received in earlier virtual stages in local memory so that later transitions send only the increment (Eq. 8):
The paper’s Figure 3 uses and and says caching removes 6 redundant transmissions; the code below recomputes that. The paper reports under 4% end-to-end overhead with pipeline parallelism on.
Inference: two-phase computation. The pseudo-queries do not depend on the forward pass, so the queries of one block can be batched against the finished block representations in one go (phase 1: one read of the block representations, returning the softmax max and log-sum-exp), and then, layer by layer inside the block, phase 2 attends over the evolving partial sum; an online softmax merges the two exactly. The per-layer, per-token reads and writes (the paper’s Table 1, with , , , ) become:
| Scheme | Reads and writes per layer | Typical value |
|---|---|---|
| Standard residual | ||
| mHC ( streams) | (plus 48 scalars) | |
| Full AttnRes | ||
| Block AttnRes |
The paper reports under 2% extra inference latency on typical workloads. Long-context prefill is a separate problem: the block representations take elements, which the paper says is 15 GB for a 128K-token sequence with 8 blocks. Sharding them along the sequence dimension across the tensor-parallel devices brings that to about 1.9 GB per device, and with 16K chunked prefill below 0.3 GB. The code below checks these numbers.
Check it yourself: the numbers that can be recomputed
The script below needs no GPU and runs in milliseconds. It recomputes seven groups of numbers: the 1.25x in the scaling fits; AttnRes against mHC-lite in Table 2; Table 1’s reads and writes; the pipeline communication of Eqs. 7 and 8; prefill memory; Table 3’s gains; and the differences in Table 4’s ablations. The paper’s numbers were transcribed from the PDF text and checked against the page layout.
Full code (about 100 lines)
"""Check the numbers in the Attention Residuals paper that can be recomputed."""
import math
# ---- 1. Scaling curves: L = A * C^(-alpha), C in PFLOP/s-days
fits = {"baseline": (1.891, 0.057), "block": (1.870, 0.058),
"full": (1.865, 0.057)}
C = 5.6
print(f"fitted loss at C={C} PFLOP/s-days")
for name, (A, a) in fits.items():
print(f" {name:8s} {A * C ** -a:.3f}")
A0, a0 = fits["baseline"]
for name in ("block", "full"):
A, a = fits[name]
target = A * C ** -a # AttnRes loss at C
c_base = (A0 / target) ** (1 / a0) # baseline compute needed
print(f" baseline needs C={c_base:.2f} to match "
f"{name} ({target:.3f}): {c_base / C:.3f}x")
# ---- 2. Validation-loss gaps to the baseline in Table 2
table2 = [ # baseline, Block, Full, mHC-lite (five sizes)
(1.931, 1.909, 1.899, 1.906), (1.895, 1.875, 1.874, 1.869),
(1.829, 1.809, 1.804, 1.807), (1.766, 1.746, 1.737, 1.747),
(1.719, 1.693, 1.692, 1.694)]
print("Table 2: baseline minus variant (positive = variant better)")
for row, act in zip(table2, ("194M", "241M", "296M", "436M", "528M")):
b = row[0]
print(f" {act} block {b - row[1]:.3f} full {b - row[2]:.3f}"
f" mHC-lite {b - row[3]:.3f}")
wins = {"block": 0, "full": 0}
for row in table2:
wins["block"] += row[1] < row[3]
wins["full"] += row[2] < row[3]
print(f"sizes (of 5) where the loss is below mHC-lite: block "
f"{wins['block']}, full {wins['full']}")
# ---- 3. Table 1: residual I/O per token per layer (in units of d)
L, N, m = 128, 8, 4
S = L // N
std = 3
mhc = 8 * m + 2 # + 2m^2 + 4m scalars
full = S + N
block = N / S + 5
print(f"L={L}, N={N}, S={S}, m={m}: standard {std}d, mHC {mhc}d "
f"(plus {2 * m * m + 4 * m} scalars), Full {full}d, Block {block}d")
# ---- 4. Pipeline communication (Eq. 7, 8, in units of Np*d)
def naive(P, V):
Cc = P * V
return Cc * (Cc - 1) // 2
def cached(P, V):
return P * (P - 1) // 2 + (V - 1) * P * P
for P, V in ((4, 2), (4, 4), (8, 2), (8, 4)):
print(f" P={P} V={V}: naive {naive(P, V):4d} cached {cached(P, V):4d}"
f" saved {naive(P, V) - cached(P, V):4d}"
f" ratio {naive(P, V) / cached(P, V):.2f}x")
# ---- 5. Block representations in prefill: N*T*d elements
T, bytes_ = 131072, 2 # 128K tokens, bfloat16
for d in (2304, 7168):
gb = N * T * d * bytes_ / 1e9
print(f"d={d}: {gb:.2f} GB, {gb / 8:.2f} GB per rank with 8-way TP")
print("the paper's 15 GB needs d*bytes =",
round(15e9 / (N * T)))
# ---- 6. Table 3: downstream scores of the 48B model (baseline -> AttnRes)
table3 = {
"MMLU": (73.5, 74.6), "MMLU-Pro": (52.2, 52.2),
"GPQA-Diamond": (36.9, 44.4), "BBH": (76.3, 78.0),
"ARC-Challenge": (64.6, 65.7), "HellaSwag": (83.2, 83.4),
"TriviaQA": (69.9, 71.8), "GSM8K": (81.7, 82.4),
"MGSM": (64.9, 66.1), "Math": (53.5, 57.1), "CMath": (84.7, 85.1),
"HumanEval": (59.1, 62.2), "MBPP": (72.0, 73.9),
"CMMLU": (82.0, 82.9), "C-Eval": (79.6, 82.5)}
gain = {k: round(b - a, 1) for k, (a, b) in table3.items()}
top = sorted(gain.items(), key=lambda kv: -kv[1])[:4]
print(f"{len(gain)} benchmarks, smallest gain {min(gain.values()):+.1f}, "
f"mean gain {sum(gain.values()) / len(gain):+.2f}")
print("four largest gains:", ", ".join(f"{k} {v:+.1f}" for k, v in top))
# ---- 7. Table 4: loss change against each reference (positive = worse)
t4 = [("baseline", 1.766, None), ("DenseFormer", 1.767, "baseline"),
("mHC", 1.747, "baseline"), ("Full", 1.737, "baseline"),
("Block S=4", 1.746, "baseline"), ("SWA 1+8", 1.764, "baseline"),
("Full, input query", 1.731, "Full"),
("Full, static mixing", 1.749, "Full"),
("Full, sigmoid", 1.741, "Full"),
("Full, no RMSNorm", 1.743, "Full"),
("Block, 16 heads", 1.752, "Block S=4"),
("Block, no RMSNorm", 1.750, "Block S=4")]
loss = {n: v for n, v, _ in t4}
print("Table 4: difference to the reference")
for n, v, ref in t4[1:]:
print(f" {n:20s} {v:.3f} vs {ref:9s} {v - loss[ref]:+.3f}")
Output:
fitted loss at C=5.6 PFLOP/s-days
baseline 1.714
block 1.692
full 1.691
baseline needs C=7.02 to match block (1.692): 1.254x
baseline needs C=7.14 to match full (1.691): 1.275x
Table 2: baseline minus variant (positive = variant better)
194M block 0.022 full 0.032 mHC-lite 0.025
241M block 0.020 full 0.021 mHC-lite 0.026
296M block 0.020 full 0.025 mHC-lite 0.022
436M block 0.020 full 0.029 mHC-lite 0.019
528M block 0.026 full 0.027 mHC-lite 0.025
sizes (of 5) where the loss is below mHC-lite: block 2, full 4
L=128, N=8, S=16, m=4: standard 3d, mHC 34d (plus 48 scalars), Full 24d, Block 5.5d
P=4 V=2: naive 28 cached 22 saved 6 ratio 1.27x
P=4 V=4: naive 120 cached 54 saved 66 ratio 2.22x
P=8 V=2: naive 120 cached 92 saved 28 ratio 1.30x
P=8 V=4: naive 496 cached 220 saved 276 ratio 2.25x
d=2304: 4.83 GB, 0.60 GB per rank with 8-way TP
d=7168: 15.03 GB, 1.88 GB per rank with 8-way TP
the paper's 15 GB needs d*bytes = 14305
15 benchmarks, smallest gain +0.0, mean gain +1.88
four largest gains: GPQA-Diamond +7.5, Math +3.6, HumanEval +3.1, C-Eval +2.9
Table 4: difference to the reference
DenseFormer 1.767 vs baseline +0.001
mHC 1.747 vs baseline -0.019
Full 1.737 vs baseline -0.029
Block S=4 1.746 vs baseline -0.020
SWA 1+8 1.764 vs baseline -0.002
Full, input query 1.731 vs Full -0.006
Full, static mixing 1.749 vs Full +0.012
Full, sigmoid 1.741 vs Full +0.004
Full, no RMSNorm 1.743 vs Full +0.006
Block, 16 heads 1.752 vs Block S=4 +0.006
Block, no RMSNorm 1.750 vs Block S=4 +0.004
Reading it item by item:
- The 1.25x holds. With the paper’s three fitted parameter sets, at the baseline is 1.714, Block 1.692 and Full 1.691, as in the text; to match Block the baseline needs , which is 1.254 times as much. The same arithmetic gives Full AttnRes 1.275 times, a number the paper does not state.
- The gap is almost constant across scales. At the five scales of Table 2, Block is 0.020 to 0.026 below the baseline and Full 0.021 to 0.032, with no clear trend up or down. The paper’s remark that the Full-to-Block gap shrinks with scale, to 0.001 at the largest size, does hold in the table (1.693 against 1.692).
- “Full beats mHC” fails at one scale. In the same table Full AttnRes has a lower loss than mHC-lite at 4 of the 5 scales; the exception is the 241M row, where mHC-lite is lower (1.869 against 1.874). Block AttnRes is below mHC-lite at only 2 of 5, so the paper’s wording “matches” fits better. With no seed-to-seed variation reported, I do not read anything into differences of this size (0.001 to 0.010).
- Table 1’s reads and writes all match: standard 3, mHC 34, Full 24, Block 5.5 (in units of ).
- Figure 3’s “removes 6” matches. With , the naive scheme sends 28 and the cached one 22, a difference of 6; the saving grows with , and at , it is 496 against 220, about 2.25 times.
- The 15 GB example needs a large hidden size. To get 15 GB, bytes in bytes must be about 14,305, that is in bfloat16. With the result is 15.03 GB, and 1.88 GB when sharded over 8 tensor-parallel ranks, matching the paper’s 1.9 GB (the “8” is my inference; the paper only says tensor-parallel devices). But Kimi Linear 48B has hidden size 2,304 (the
config.jsonon Hugging Face), for which the same calculation gives only 4.83 GB. The paper does not say which hidden size the example uses, so the 15 GB looks like an example for a larger model rather than a number for the 48B model itself. - Table 4’s differences are all against the same baseline, 1.766. Full is 0.029 lower, Block 0.020 and mHC 0.019; removing the key RMSNorm makes Full worse by 0.006 and Block by 0.004; DenseFormer and the sliding window give almost nothing (+0.001 and −0.002).
- Table 3’s gains have no negatives. The smallest of the 15 is 0.0 (MMLU-Pro, 52.2 against 52.2), the mean gain is 1.88 points, and the four largest are GPQA-Diamond, Math, HumanEval and C-Eval. The paper’s wording “Block AttnRes matches or outperforms the baseline on all benchmarks” holds. GPQA-Diamond has only 198 questions, so 7.5 points is about 15 questions; the paper does not say whether scores are averaged over several samples.
The paper’s experiments and conclusions
Scaling laws (Figure 2). Five scales (194M to 528M active parameters, 38.7B to 119.0B training tokens, Table 2); at each, the baseline, Full AttnRes and Block AttnRes with about 8 blocks are trained, with all three sharing the hyperparameters chosen for the baseline, which favours the baseline. The fitted power laws are for the baseline, for Block and for Full. The three slopes are almost identical and AttnRes sits lower throughout.
The main model and downstream benchmarks. The largest model is the full Kimi Linear 48B: 27 Transformer blocks (54 layers), 8 of 256 routed experts plus 1 shared expert, with KDA and MLA layers interleaved at roughly 3:1 (the Hugging Face config has 20 KDA and 7 MLA layers). The AttnRes version uses 6 layers per block, giving 9 blocks plus the embedding, 10 sources in all. The recipe follows Kimi Linear’s 1.4T-token run: the Muon optimizer, a WSD learning-rate schedule, a global batch of 8M tokens and a 4096-token context, 1T tokens of WSD pre-training followed by about 400B high-quality tokens of mid-training, then progressively longer sequences up to 32K. The AttnRes model is at least as good as the baseline on all 15 benchmarks, with the clearest gains on multi-step reasoning (GPQA-Diamond +7.5, Math +3.6) and code (HumanEval +3.1), and solid gains on knowledge benchmarks (MMLU +1.1, TriviaQA +1.9). The paper’s reading is that better information flow along depth helps compositional tasks, because later layers can selectively retrieve and build on earlier representations.
Training dynamics. The paper’s Figure 5 compares the two models over 1T tokens. AttnRes has the lower validation loss throughout, with the gap widening in the decay phase. In the baseline, each block’s output magnitude grows monotonically with depth, whereas Block AttnRes “resets” the accumulation at block boundaries and shows a bounded periodic pattern. The baseline’s earliest layers get disproportionately large gradients, while AttnRes spreads them more evenly. These conclusions come from plots, the paper gives no numbers for them, and I do not quote any.
Ablations (the 436M scale of Table 2, with 16 blocks and 16 heads; the paper’s Table 4).
| Variant | Validation loss |
|---|---|
| Baseline (PreNorm) | 1.766 |
| DenseFormer (fixed, input-independent coefficients) | 1.767 |
| mHC | 1.747 |
| Full AttnRes | 1.737 |
| Block AttnRes (block size 4) | 1.746 |
| Sliding window (last 8 layers plus embedding) | 1.764 |
| Full, input-dependent query | 1.731 |
| Full, input-independent scalar mixing | 1.749 |
| Full, sigmoid instead of softmax | 1.741 |
| Full, no key RMSNorm | 1.743 |
| Block, multi-head (16 heads) | 1.752 |
| Block, no key RMSNorm | 1.750 |
A few conclusions: input-dependent weights are the key (DenseFormer’s fixed coefficients gain nothing, and input-independent mixing is worse than AttnRes); softmax’s competitive normalization beats sigmoid; the sliding window helps only a little, so reading selectively from far-away layers matters more than reading many nearby ones; per-head depth aggregation is worse, which suggests the best depth mixture is largely the same across channels. Sweeping the block size from 1 (Full) to 32, sizes 2, 4 and 8 all land near 1.746, while 16 and 32 drift towards the baseline.
The best architecture (Figure 7). With compute and active parameters fixed, on a 5×5 grid of “width over block count, heads over block count”, AttnRes beats the baseline in all 25 configurations by 0.019 to 0.063. The optimum moves from for the baseline (loss 1.847) to about 45 (1.802), that is, towards deeper and narrower networks. The paper stresses that this is not a deployment recommendation, since deeper models have higher inference latency.
Learned patterns (Figure 8). Each layer looks hardest at its immediate predecessor (a dominant diagonal), while the embedding keeps a non-trivial weight throughout, and occasional “skip connections” appear (for example layer 4 looking back at early sources). Attention layers have a wider receptive field over depth and MLP layers depend more on nearby ones; the Block variant keeps this structure.
Hands-on: the three residual schemes in a small model
Can the paper’s qualitative effects be seen at small scale? The script below trains a 24-sublayer byte-level model on Python’s standard-library source and implements three variants: the PreNorm baseline, Full AttnRes and Block AttnRes (block size 4 sublayers, blocks; the paper uses about 8). The AttnRes implementation follows the pseudo-code in the paper’s Figure 2: zero-initialized pseudo-queries, RMSNorm on the keys (with its gain), and in Block mode the running partial sum of the current block as an extra source. To speed it up, the script computes each source’s RMS normalization once and caches it, then dots with (pseudo-query times key gain); this is mathematically identical to stacking and normalizing as in the paper, and the script first checks the two implementations on random inputs (maximum difference about , float32 rounding).
Setup: the data are the 155 top-level .py files of CPython 3.14.3’s standard library, 4,701,651 bytes, with the first 95% for training and the last 5% for validation (split by position); context 128, batch 64; AdamW (, weight decay 0.1, none on pseudo-queries and key gains), learning rate 3e-3 with 100 warmup steps and cosine decay to 10%, gradient clipping 1.0, 1,500 steps (about 12.3 million tokens); 3 seeds per variant (the seed controls initialization, and batch sampling uses a separate seed); all three variants share one set of hyperparameters and none was tuned individually, the learning rate being chosen on the baseline alone from 1.5e-3 and 3e-3 with a 600-step run, with short runs confirming that Block and Full do not diverge at it. The metric is validation bits per byte (bpb, lower is better). This is a toy-scale experiment (1.4M parameters, 1,500 steps); it can say whether an effect shows up at all, but it cannot confirm or refute the paper’s numbers.
Full code (about 230 lines)
"""Tiny byte-level LMs: PreNorm baseline, Full and Block AttnRes"""
import glob
import json
import math
import sysconfig
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
dev = "mps" if torch.backends.mps.is_available() else "cpu"
# 12 transformer blocks = 24 sublayers (attention, MLP, ...)
D, BLOCKS, HEADS, T, B = 96, 12, 4, 128, 64
NSUB = 2 * BLOCKS
STEPS, LR, WARM = 1500, 3e-3, 100
# Block AttnRes: 4 sublayers per block, N=6 blocks
S = 4
SEEDS = (0, 1, 2)
# data: first 6 MB of the top-level stdlib .py files
files = sorted(glob.glob(sysconfig.get_paths()["stdlib"] + "/*.py"))
raw = b"".join(open(f, "rb").read() for f in files)[:6_000_000]
data = torch.tensor(np.frombuffer(raw, dtype=np.uint8).astype(np.int64))
cut = int(len(data) * 0.95)
train, val = data[:cut], data[cut:]
print(f"{len(files)} files, {len(data):,} bytes; "
f"train {len(train):,}, val {len(val):,}")
class RMS(nn.Module):
def __init__(self, d):
super().__init__()
self.g = nn.Parameter(torch.ones(d))
def forward(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-6) * self.g
def rn(x):
# RMS normalisation without the gain
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-6)
class Attn(nn.Module):
def __init__(self):
super().__init__()
self.qkv = nn.Linear(D, 3 * D, bias=False)
self.proj = nn.Linear(D, D, bias=False)
def forward(self, x):
b, t, _ = x.shape
q, k, v = self.qkv(x).view(b, t, 3, HEADS, D // HEADS).unbind(2)
q, k, v = (z.transpose(1, 2) for z in (q, k, v))
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return self.proj(y.transpose(1, 2).reshape(b, t, D))
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.up = nn.Linear(D, 4 * D, bias=False)
self.down = nn.Linear(4 * D, D, bias=False)
def forward(self, x):
return self.down(F.gelu(self.up(x)))
class Net(nn.Module):
def __init__(self, mode):
super().__init__()
self.mode = mode # base | full | block
self.emb, self.pos = nn.Embedding(256, D), nn.Embedding(T, D)
self.subs = nn.ModuleList(
[Attn() if i % 2 == 0 else MLP() for i in range(NSUB)])
self.norms = nn.ModuleList([RMS(D) for _ in range(NSUB)])
self.fn, self.head = RMS(D), nn.Linear(D, 256, bias=False)
if mode != "base":
# a pseudo-query (zero init) and a key-norm gain per layer
self.q = nn.Parameter(torch.zeros(NSUB + 1, D))
self.kg = nn.Parameter(torch.ones(NSUB + 1, D))
for n, p in self.named_parameters():
if p.dim() == 2 and n.startswith(("subs", "head")):
small = "proj" in n or "down" in n
nn.init.normal_(p, 0, 0.02 / math.sqrt(NSUB) if small else 0.02)
nn.init.normal_(self.emb.weight, 0, 0.02)
nn.init.normal_(self.pos.weight, 0, 0.02)
def agg(self, V, K, part, i):
# softmax attention over sources; in Block mode the partial sum is one
if part is not None:
V, K = V + [part], K + [rn(part)]
w = self.q[i] * self.kg[i] # q'(g*k) = (q*g)'k
a = (torch.stack(K, 2) @ w).softmax(-1) # [B, T, n]
return (a.unsqueeze(2) @ torch.stack(V, 2)).squeeze(2), a
def forward(self, x, trace=None):
e = self.emb(x) + self.pos(torch.arange(x.shape[1], device=x.device))
h, V, K, part = e, [e], [rn(e)], None
for i in range(NSUB):
if self.mode != "base":
h, a = self.agg(V, K, part, i)
if trace is not None:
trace["hid"].append(h.pow(2).mean().sqrt().item())
if self.mode == "full":
trace["alpha"].append(a.mean((0, 1)).tolist())
f = self.subs[i](self.norms[i](h))
if self.mode == "base":
h = h + f
elif self.mode == "full":
V.append(f)
K.append(rn(f))
else:
part = f if part is None else part + f
if (i + 1) % S == 0:
V.append(part)
K.append(rn(part))
part = None
if self.mode != "base":
h, _ = self.agg(V, K, part, NSUB)
return self.head(self.fn(h))
def agg_ref(m, V, i):
# straight from the paper: stack, RMSNorm with gain, dot with q
X = torch.stack(V)
k = X * torch.rsqrt(X.pow(2).mean(-1, keepdim=True) + 1e-6) * m.kg[i]
a = torch.einsum("d,nbtd->nbt", m.q[i], k).softmax(0)
return torch.einsum("nbt,nbtd->btd", a, X)
torch.manual_seed(123)
m = Net("full").to(dev)
m.q.data.normal_(0, 1)
m.kg.data.normal_(1, 0.3)
Vs = [torch.randn(2, 8, D, device=dev) * (j + 1) for j in range(7)]
fast = m.agg(Vs, [rn(v) for v in Vs], None, 3)[0]
diff = (fast - agg_ref(m, Vs, 3)).abs().max().item()
print(f"two ways to aggregate, max difference {diff:.1e}")
def batch(rng):
ix = rng.integers(0, len(train) - T - 1, B)
x = torch.stack([train[i:i + T] for i in ix])
y = torch.stack([train[i + 1:i + T + 1] for i in ix])
return x.to(dev), y.to(dev)
starts = range(0, len(val) - T - 1, T)
VX = torch.stack([val[i:i + T] for i in starts])
VY = torch.stack([val[i + 1:i + T + 1] for i in starts])
@torch.no_grad()
def evaluate(model, trace=None):
model.eval()
tot, n = 0.0, 0
for j in range(0, len(VX), 128):
x, y = VX[j:j + 128].to(dev), VY[j:j + 128].to(dev)
lg = model(x, trace if j == 0 else None)
tot += F.cross_entropy(lg.reshape(-1, 256), y.reshape(-1),
reduction="sum").item()
n += y.numel()
model.train()
return tot / n / math.log(2) # bits per byte
def run(mode, seed):
torch.manual_seed(seed)
# batch sampling and init use different seeds
rng = np.random.default_rng(seed + 1000)
model = Net(mode).to(dev)
nd = ("q", "kg") # no weight decay
named = list(model.named_parameters())
decay = [p for n, p in named if p.dim() == 2 and n not in nd]
other = [p for n, p in named if p.dim() != 2 or n in nd]
opt = torch.optim.AdamW([{"params": decay, "weight_decay": 0.1},
{"params": other, "weight_decay": 0.0}],
lr=LR, betas=(0.9, 0.95))
t0 = time.time()
for step in range(STEPS):
cos = 0.5 * (1 + math.cos(math.pi * step / STEPS))
lr = LR * min(1, (step + 1) / WARM) * (0.1 + 0.9 * cos)
for g in opt.param_groups:
g["lr"] = lr
x, y = batch(rng)
loss = F.cross_entropy(model(x).reshape(-1, 256), y.reshape(-1))
opt.zero_grad(set_to_none=True)
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
trace = {"hid": [], "alpha": []}
bpb = evaluate(model, trace)
npar = sum(p.numel() for p in model.parameters())
return bpb, trace, npar, time.time() - t0
results = {}
for mode in ("base", "full", "block"):
for seed in SEEDS:
bpb, trace, npar, sec = run(mode, seed)
results[f"{mode}-{seed}"] = dict(bpb=bpb, trace=trace, params=npar)
print(f"{mode:5s} seed {seed}: val {bpb:.4f} bpb "
f"params {npar:,} {sec / 60:.1f} min", flush=True)
json.dump(results, open("attnres_train.json", "w"))
print("\nvalidation bits per byte (lower is better)")
base = np.array([results[f"base-{s}"]["bpb"] for s in SEEDS])
for mode in ("base", "full", "block"):
v = np.array([results[f"{mode}-{s}"]["bpb"] for s in SEEDS])
gap = base.mean() - v.mean()
print(f" {mode:5s} mean {v.mean():.4f} std {v.std(ddof=1):.4f} "
f"gap to baseline {gap:+.4f}")
# several sources exist from sublayer 2 on
A = results["full-0"]["trace"]["alpha"][1:]
print(f"\nFull AttnRes (seed 0): mean weight on the embedding "
f"{np.mean([a[0] for a in A]):.3f}, on the previous sublayer "
f"{np.mean([a[-1] for a in A]):.3f}")
print("\nhidden-state RMS entering each sublayer after training (seed 0)")
for mode in ("base", "full", "block"):
h = results[f"{mode}-0"]["trace"]["hid"]
print(f" {mode:5s} first {h[0]:.2f} mid {h[NSUB // 2]:.2f} "
f"last {h[-1]:.2f} max/first {max(h) / h[0]:.2f}")
Output:
155 files, 4,701,651 bytes; train 4,466,568, val 235,083
two ways to aggregate, max difference 6.2e-06
base seed 0: val 1.9082 bpb params 1,390,944 3.5 min
base seed 1: val 1.9185 bpb params 1,390,944 3.2 min
base seed 2: val 1.9003 bpb params 1,390,944 3.3 min
full seed 0: val 1.8630 bpb params 1,395,744 16.9 min
full seed 1: val 1.8595 bpb params 1,395,744 24.2 min
full seed 2: val 1.8427 bpb params 1,395,744 14.5 min
block seed 0: val 1.8953 bpb params 1,395,744 6.6 min
block seed 1: val 1.8573 bpb params 1,395,744 6.6 min
block seed 2: val 1.8759 bpb params 1,395,744 6.6 min
validation bits per byte (lower is better)
base mean 1.9090 std 0.0091 gap to baseline +0.0000
full mean 1.8551 std 0.0109 gap to baseline +0.0540
block mean 1.8762 std 0.0190 gap to baseline +0.0328
Full AttnRes (seed 0): mean weight on the embedding 0.232, on the previous sublayer 0.063
hidden-state RMS entering each sublayer after training (seed 0)
base first 0.08 mid 1.14 last 1.34 max/first 15.89
full first 0.08 mid 0.17 last 0.14 max/first 3.12
block first 0.08 mid 0.53 last 0.41 max/first 7.58
The training script saved all results in attnres_train.json; the short script below only reads that file and computes the statistics quoted afterwards, in a few milliseconds.
Full code (about 50 lines)
"""Statistics from the attnres_train.json saved by the training script."""
import json
import numpy as np
R = json.load(open("attnres_train.json"))
MODES = ("base", "full", "block")
bpb = {m: np.array([R[f"{m}-{s}"]["bpb"] for s in range(3)]) for m in MODES}
sd = bpb["base"].std(ddof=1)
best = bpb["base"].min()
worst = max(bpb["full"].max(), bpb["block"].max())
print(f"best baseline {best:.4f}, worst AttnRes {worst:.4f}, "
f"gap {best - worst:.4f}")
for m in ("full", "block"):
gap = bpb["base"].mean() - bpb[m].mean()
print(f" {m:5s} is {gap:.4f} below the baseline mean, "
f"{gap / sd:.1f}x the baseline std {sd:.4f}")
d = bpb["block"].mean() - bpb["full"].mean()
print(f" Block is {d:.4f} above Full on average; their stds are "
f"{bpb['full'].std(ddof=1):.4f} and {bpb['block'].std(ddof=1):.4f}")
# ---- hidden RMS (seed 0; entry i is the input of sublayer i)
H = {m: np.array(R[f"{m}-0"]["trace"]["hid"]) for m in MODES}
b, f, k = H["base"], H["full"], H["block"]
print(f"\nbaseline: input RMS of sublayers 2, 3, 24 is {b[1]:.2f}, "
f"{b[2]:.2f}, {b[-1]:.2f}")
print(f" sublayers below the previous one: {(np.diff(b) < 0).sum()}")
print(f"Full: maximum {f.max():.2f} (sublayer {f.argmax() + 1}), "
f"last {f[-1]:.2f}")
print(f"Block: sublayers 9 to 24 range from {k[8:].min():.2f} to "
f"{k[8:].max():.2f}")
# ---- Full AttnRes (seed 0): A[i] is sublayer i+1; source 0 is the embedding
A = R["full-0"]["trace"]["alpha"]
print(f"\nFull: sublayers 2, 3, 4 give the embedding "
f"{A[1][0]:.2f}, {A[2][0]:.2f}, {A[3][0]:.2f}")
top = [int(np.argmax(a)) for a in A[6:]]
print(f"sublayers 7-24: largest weight always on sublayer 1? "
f"{all(t == 1 for t in top)}")
late = A[12:]
print(f"sublayers 13-24: largest single weight "
f"{max(max(a) for a in late):.2f}")
print(f" mean weight on sublayer 1: {np.mean([a[1] for a in late]):.3f}"
f" (equal split {np.mean([1 / len(a) for a in late]):.3f})")
dist = {}
for i, a in enumerate(A):
for j in range(1, len(a)):
dist.setdefault(i + 1 - j, []).append(a[j])
mean_w = [np.mean(dist[d]) for d in range(1, 9)]
print(f"sources 1 to 8 sublayers back get a mean weight between "
f"{min(mean_w):.3f} and {max(mean_w):.3f}")
Output:
best baseline 1.9003, worst AttnRes 1.8953, gap 0.0050
full is 0.0540 below the baseline mean, 5.9x the baseline std 0.0091
block is 0.0328 below the baseline mean, 3.6x the baseline std 0.0091
Block is 0.0211 above Full on average; their stds are 0.0109 and 0.0190
baseline: input RMS of sublayers 2, 3, 24 is 0.13, 0.96, 1.34
sublayers below the previous one: 1
Full: maximum 0.25 (sublayer 10), last 0.14
Block: sublayers 9 to 24 range from 0.25 to 0.62
Full: sublayers 2, 3, 4 give the embedding 0.81, 0.84, 0.86
sublayers 7-24: largest weight always on sublayer 1? True
sublayers 13-24: largest single weight 0.21
mean weight on sublayer 1: 0.136 (equal split 0.056)
sources 1 to 8 sublayers back get a mean weight between 0.058 and 0.076
Scores: both AttnRes variants beat the baseline, by more than the seed noise at the means. The three baseline seeds reach 1.9003 to 1.9185 validation bpb with a standard deviation of 0.0091. All six Full and Block runs finish below the best baseline run, but the smallest margin is only 0.0050 (1.9003 against 1.8953, the Block seed 0 run), smaller than the baseline’s own spread. On the means Full is 0.0540 lower and Block 0.0328 lower, 5.9 and 3.6 times the baseline’s standard deviation. Full beating Block agrees in direction with the paper, but the difference of 0.0211 is of the same order as their own standard deviations (0.0109 and 0.0190), and three seeds cannot separate them. With three seeds per variant the standard deviations are themselves rough estimates, and “six below three” is a ranking, not a significance test. I ran the whole experiment once for each language version of this page, and the same seed does not give bit-identical results (reduction order on MPS is not fixed); for the AttnRes variants this rerun jitter is of the same order as their seed-to-seed standard deviation, so I do not interpret differences within 0.01.
Hidden state: the baseline grows with depth and the AttnRes inputs do not, but this is not the paper’s quantity (Figure 3). For seed 0, the baseline’s input RMS at sublayers 2, 3 and 24 is 0.13, 0.96 and 1.34: the growth happens mostly when the output of sublayer 2 is added, and from there the curve creeps from 0.96 to 1.34, with 1 sublayer below its predecessor. That is one big jump followed by slow growth, not the linear growth with depth that the paper describes, and I do not see the latter in this 24-sublayer model (I did not check why). Full peaks at 0.25 (sublayer 10) and ends at 0.14; from sublayer 9 on, Block ranges from 0.25 to 0.62, without the neat block-periodic shape of the paper’s Figure 5. Note that I measure the input of each sublayer, and an AttnRes input is a weighted average with weights summing to 1; averaging several independent outputs is smaller than summing them anyway. So the plot supports at most “the AttnRes inputs do not accumulate with depth”, not the paper’s claim about PreNorm dilution.
Learned weights: the embedding and sublayer 1 take most of the mass, with no dominant diagonal (Figure 4). In Full AttnRes (seed 0), sublayers 2, 3 and 4 give the embedding 0.81, 0.84 and 0.86; from sublayer 7 on, the largest weight always lies on the output of sublayer 1; in sublayers 13 to 24 the largest single weight is only 0.21, the mean weight on sublayer 1 is 0.136 and an equal split would be 0.056. Sources 1 to 8 sublayers back get a mean weight between 0.058 and 0.076, and the immediately preceding sublayer (0.063 in the training output) is no more favoured than farther ones. The paper’s Figure 8 is described as each layer looking hardest at its predecessor while the embedding keeps a non-trivial weight; only the second half matches here, with a mean weight of 0.232 on the embedding (that line of the training output, mostly from the first few sublayers). I did not check why they differ; the paper’s Figure 8 comes from a 54-layer 48B model, and this 24-sublayer, 1,500-step model should not be read as a reproduction.
Cost: this experiment does not measure the paper’s overhead. My implementation stacks the sources and runs attention over them with no optimization: a Full run takes 14.5 to 24.2 minutes, a Block run 6.6 minutes and a baseline run 3.2 to 3.5 minutes, and the timings swing with other load on the machine, so they neither verify the paper’s “under 4% with pipeline parallelism, under 2% at inference” nor say how slow AttnRes is in an optimized system. As for parameters, each AttnRes variant has 4,800 more (1,395,744 against 1,390,944).
Environment: Apple M2 Max (MPS backend, float32), Python 3.14.3, PyTorch 2.10.0, NumPy 2.4.2; no pretrained models. Nine training runs (three variants, three seeds), about 85 minutes in total; on other hardware or library versions the trained bpb may differ slightly (reduction order on MPS is not guaranteed to be bit-for-bit reproducible), while the arithmetic in part one is deterministic.
Limitations and what comes next
- Every comparison comes from one training run. The paper reports no seed-to-seed variation or error bars (none in the text I read). In the scaling experiments AttnRes’s edge over the baseline is of order 0.02; in the 48B comparison MMLU-Pro is tied and the other gains range from 0.2 to 7.5 points, and there is no way to tell which differences exceed noise.
- The baseline is tuned, but once. The paper says the three variants at each scale share hyperparameters selected on the baseline, which makes the comparison conservative; whether AttnRes has a better learning rate was not swept.
- The 48B comparison is a single pair of models. The largest single gain among the 15 benchmarks (GPQA-Diamond, +7.5) comes from an evaluation with only 198 questions.
- The training-dynamics claims come from plots, not numbers. “More uniform gradients” and “bounded output magnitudes” are shown in Figure 5 with no statistics or repeated runs.
- Full AttnRes was not used at scale. It is the best variant, but its communication is not practical under current parallelism schemes; the paper leaves “better interconnects make Full usable” to the future.
- The inference costs are the authors’ own measurements. The under-2% and under-4% figures depend on their kernels and system and may not reproduce on another stack; the hidden size behind the 15 GB prefill example is not given (see the check above).
- The comparison with mHC uses the mHC(-lite) labelled in the paper’s Table 2. The paper does not say how it differs from DeepSeek’s original mHC, so “Full beats mHC” should be read as “beats the mHC variant implemented in the paper”; Tables 2 and 4 give 1.747 for the same configuration but cite two different references.
- The small-model experiment only answers “did the effect show up”. Three seeds per variant, 24 sublayers and 1,500 steps: AttnRes ranking above the baseline is larger than the noise, the order of Full and Block cannot be told, and the shape of the learned weights differs from the paper’s Figure 8 for reasons I did not check.
- A preference for deeper, narrower networks is not a deployment recommendation. The paper says so itself.
What to take from this paper
- A residual is a recurrence over depth, and AttnRes is attention over depth. The analogy lays out a clear design space: equal-weight sums (standard residual), gates (Highway), multiple states (HC/mHC), softmax attention (AttnRes).
- Two small details make it trainable. Zero-initialized pseudo-queries give an equal-weight average at the start; RMSNorm on the keys stops large-magnitude layers from monopolizing the softmax. In the ablations, removing the latter costs 0.006 and 0.004.
- Block is an engineering compromise, and the systems work is what makes it usable. recovers most of the gain, while cross-stage caching and two-phase inference hold the extra cost to under 4% in training and under 2% in inference.
- Keep the layers of evidence apart. The arithmetic of the numbers can be checked (this post does); the scaling-law and 48B results are the authors’ single runs; what a small model shows only indicates the direction of the mechanism at small scale.
Further reading
- Kimi Team, Attention Residuals (arXiv:2603.15031, this post follows v1); official code: MoonshotAI/Attention-Residuals.
- Kimi Team, Kimi Linear (arXiv:2510.26692): the 48B backbone the paper uses, with KDA and MLA attention interleaved at roughly 3:1.
- Xie et al., mHC (see this site’s explainer): another route at the same spot.
- Pagliardini et al., DenseFormer (arXiv:2402.02622): the paper’s ablation baseline for fixed-coefficient cross-layer access.
- On this site: the wiki’s Transformer block (residuals and normalization) and modern LLM architecture.
FAQ
- How does Attention Residuals differ from a normal residual connection?
- In a PreNorm Transformer the input to layer l is the embedding plus the outputs of all earlier layers, every one with weight 1, so every layer sees the same sum. AttnRes replaces that equal-weight sum with softmax attention. Layer l has a learned pseudo-query vector w_l; it is dotted with each earlier source (the embedding or a layer output, passed through RMSNorm to act as the key), a softmax turns the scores into weights, and the weighted sum becomes the layer's input. Each layer adds one d-dimensional vector and one RMSNorm. All pseudo-queries are initialized to zero, so training starts from a plain average.
- Why Block AttnRes? Isn't Full AttnRes good enough?
- Full AttnRes is the strongest variant (in the paper's ablation on the 436M model of Table 2 it reaches 1.737, against 1.746 for Block and 1.766 for the baseline), but every layer reads all L earlier outputs. With activation recomputation and pipeline parallelism those L outputs must be kept alive and sent across stages, so memory and communication grow as O(Ld). Block AttnRes splits the L layers into N blocks, sums the outputs inside a block with an ordinary residual, and attends only over the N block representations plus the embedding. That brings the cost down to O(Nd); the paper uses N around 8 and says it keeps most of the gain.
- How many parameters and how much training or inference overhead does AttnRes add?
- On parameters, each layer adds one d-dimensional pseudo-query and one RMSNorm, which the paper calls negligible for its 48B model; in this post's 1.4M-parameter model it is 4,800 extra parameters on a baseline of 1,390,944. On cost, the paper reports almost no overhead for ordinary training, under 4% end-to-end overhead with pipeline parallelism (cross-stage caching keeps communication down), and under 2% extra inference latency on typical workloads (two-phase computation with an online-softmax merge). These are the authors' own measurements on their own system, and I cannot reproduce them.
- How is AttnRes related to mHC and hyper-connections (HC)?
- Both change how the residual stream accumulates. HC and mHC widen the stream into m parallel streams and let them exchange information through m-by-m mixing matrices, which makes the per-layer residual reads and writes more than ten times those of a plain residual (the paper's Table 1: 34d for mHC at m=4 against 3d). AttnRes keeps a single stream and attends over depth instead, reading each earlier layer's own output; the Block variant costs about 5.5d. In the paper's ablation mHC reaches 1.747, Full AttnRes 1.737 and Block AttnRes 1.746. Checking the paper's Table 2, this post finds that Full AttnRes does not beat mHC-lite at all five scales.
- How large is AttnRes's effect, and can the result be trusted?
- In the scaling-law experiments Block AttnRes has a fitted loss of 1.692 at 5.6 PFLOP/s-days against 1.714 for the baseline, equal to the baseline using 1.25 times the compute (this post recomputes 1.254). Kimi Linear 48B, after 1.4T tokens, is at least as good as its baseline on all 15 downstream benchmarks, with a mean gain of 1.88 points and the largest gains on GPQA-Diamond (+7.5), Math (+3.6) and HumanEval (+3.1). The caveat is that the paper reports no seed-to-seed variation: each scale and the 48B pair come from a single training run, so differences in the second decimal of the loss cannot be told from noise.