models

Transformer Architecture

Understand what each block reads, what it writes and what the output head can express.

Published 2024-09-27 · Updated 2026-10-28
On this page

A Transformer repeatedly updates a vector for each token. Attention combines information from accessible positions. A feedforward network transforms each token separately. Residual connections keep an accumulated state between these operations.

These parts solve different problems. Normalization controls input statistics. Initialization sets the initial scale. An output head turns the final state into token probabilities. Changing one part does not automatically fix a limitation in another.

From token IDs to a next-token distribution

Let B be batch size, T sequence length, d hidden width and V vocabulary size. An embedding lookup maps integer IDs of shape (B,T) to vectors of shape (B,T,d). A bigram table predicts from the current token alone. Contextual attention lets the model use a longer prefix.

  1. Embed(B,T) IDs → (B,T,d) states
  2. Normalize → causal attention → addRead prefix positions; write a d-vector
  3. Normalize → feedforward → addTransform each token; write a d-vector
  4. Repeat blocks → final normalizationPreserve the residual width
  5. Vocabulary projection(B,T,d) → (B,T,V) logits
Common decoder-only Pre-Norm anatomy, not a universal Transformer specification. Skip additions carry the incoming state around each sublayer.

In a conventional head, Q,K,V have per-head width p. Attention computes softmax⁡(QK⊤p+M)V\operatorname{softmax}\left(\frac{QK^\top}{\sqrt p}+M\right)V. The additive mask MM excludes future keys before softmax. Concatenated head outputs are projected back to d. GQA and MLA change the key/value representation; see Attention →.

Training shifts the target by one token. For [A,B,C,D], input [A,B,C] predicts [B,C,D]. All three positions can be trained together because the causal mask prevents target leakage. Generation appends one sampled token and repeats; a KV cache avoids recomputing earlier keys and values.

# Shape pseudocode; attention applies the causal mask internally.
x = embedding(ids)                    # B,T,d
for block in blocks:
    x = x + block.attention(block.norm1(x))
    x = x + block.ffn(block.norm2(x))
logits = final_norm(x) @ output_weight.T  # B,T,V
loss = cross_entropy(logits, next_token_targets)

Without positional information, unrestricted self-attention is permutation-equivariant: permuting inputs permutes outputs. A causal mask already breaks unrestricted permutation symmetry. Position mechanisms add explicit order or relative-distance structure; see Positional Encodings →. Equivariance is not the same as invariance.

Why keep an identity path?

xℓ+1=xℓ+Fℓ(xℓ)∂xℓ+1∂xℓ=I+JFℓ\begin{aligned}x_{\ell+1}&=x_\ell+F_\ell(x_\ell)\\\frac{\partial x_{\ell+1}}{\partial x_\ell}&=I+J_{F_\ell}\end{aligned}
Fₗ produces a same-shaped update. The identity term supplies a direct derivative path.

Without skips, backpropagation multiplies sublayer Jacobians. Many contractions can shrink gradients; many expansions can increase them. With a residual, a layer can start near the identity instead of learning that identity through every weight matrix.

The identity term helps but does not guarantee stable gradients. Products of I+J can still contract or expand. A branch can cancel a direction. Initialization, normalization, optimizer settings and depth remain coupled.

Unrolling gives xL=x0+∑ℓ=0L−1Fℓ(xℓ)x_L=x_0+\sum_{\ell=0}^{L-1}F_\ell(x_\ell). This is an exact sum of the actual updates, not a sum of independent random variables. A state can grow while each normalized branch input remains bounded.

Choose which statistics to share

Before choosing a normalization method, specify the axes. BatchNorm (2015) shares feature statistics across examples. LayerNorm (2016) computes statistics within one example. In a Transformer, LayerNorm usually operates over one token's d features. RMSNorm (2019) keeps the same token-local axis but omits centering.

μ=1d∑ixi,σ2=1d∑i(xi−μ)2LN⁡(x)i=γixi−μσ2+ε+βiRMSNorm⁡(x)i=γixi1d∑jxj2+ε\begin{aligned}\mu&=\frac1d\sum_i x_i,&\sigma^2&=\frac1d\sum_i(x_i-\mu)^2\\\operatorname{LN}(x)_i&=\gamma_i\frac{x_i-\mu}{\sqrt{\sigma^2+\varepsilon}}+\beta_i\\\operatorname{RMSNorm}(x)_i&=\gamma_i\frac{x_i}{\sqrt{\frac1d\sum_jx_j^2+\varepsilon}}\end{aligned}
d is a positive feature count and ε>0. γ is learned gain; β is learned bias where present; ε protects division. RMSNorm commonly omits β.

BatchNorm uses the corresponding batch mean and variance per feature, then applies gain and bias. In a CNN, its reduction often also includes spatial positions. Training generally updates running statistics; inference uses those stored statistics. Forward variance and running-variance estimators can differ by implementation.

μf=1B∑b=1Bxb,f,σf2=1B∑b=1B(xb,f−μf)2yb,f=γfxb,f−μfσf2+ε+βf\begin{aligned}\mu_f&=\frac1B\sum_{b=1}^B x_{b,f},\qquad \sigma_f^2=\frac1B\sum_{b=1}^B(x_{b,f}-\mu_f)^2\\y_{b,f}&=\gamma_f\frac{x_{b,f}-\mu_f}{\sqrt{\sigma_f^2+\varepsilon}}+\beta_f\end{aligned}
BatchNorm training formula for B examples and feature f. Reduce across the batch, not across token features as in LayerNorm. Uses the biased forward variance; running estimates are separate.

The original BatchNorm motivation was to reduce changes in layer-input distributions during training. Later work studied smoother optimization landscapes as an explanation of its benefits. These are explanations to test, not guarantees for every model. BatchNorm and optimization smoothness ↗

Small batches can make BatchNorm statistics noisy. Synchronizing them across workers adds communication. Pooling sequence positions requires careful masking and causality. This is not proof that BatchNorm cannot work in language models.

LayerNorm and RMSNorm do not depend on other batch examples for their statistics. Their identical train/test normalization rules do not mean the whole network is context-independent. Attention still couples token representations.

“Internal covariate shift” was BatchNorm's original motivation, not a settled explanation of all its benefits. Avoid assuming a normalization change always permits a higher learning rate. RMSNorm's paper reports model-dependent running-time reductions of 7–64%; that is not a guaranteed modern-kernel or end-to-end speedup. RMSNorm report ↗

Centering and scaling are different operations

Take one vector and add the same offset to every feature. LayerNorm discards that offset. RMSNorm does not. Both methods divide by a statistic computed from all four features.

One shared offset

Use ε=10−5, γ=1, β=0\varepsilon=10^{-5},\ \gamma=1,\ \beta=0.

One token, four features
QuantityLayerNormRMSNorm
Input[-3.000, -1.000, 1.000, 3.000][-3.000, -1.000, 1.000, 3.000]
Subtracted mean0.0000
Divisor2.2362.236
Output[-1.342, -0.447, 0.447, 1.342][-1.342, -0.447, 0.447, 1.342]

Offset 0: LayerNorm removes a common shift. RMSNorm retains the direction of the shifted vector while controlling its root mean square. Neither operation mixes tokens.

Positive common rescaling approximately cancels in both methods, subject to ε. Common shifts cancel only in LayerNorm. Learned gain and bias can change the normalized mean and variance afterward. For a constant vector, LayerNorm produces zero before its affine transform; RMSNorm can retain a nonzero constant direction.

These operations couple feature derivatives. For normalized outputs before learned gain and bias, define s and r as the corresponding divisors.

s=σ2+ε,r=1d∑kxk2+ε∂uiLN∂xj=δij−1/ds−(xi−μ)(xj−μ)d s3∂uiRMS∂xj=δijr−xixjd r3∂tanh⁡(axi)∂xj=δij a[1−tanh⁡2(axi)]\begin{aligned}s&=\sqrt{\sigma^2+\varepsilon},\qquad r=\sqrt{\frac1d\sum_k x_k^2+\varepsilon}\\\frac{\partial u_i^{\mathrm{LN}}}{\partial x_j}&=\frac{\delta_{ij}-1/d}{s}-\frac{(x_i-\mu)(x_j-\mu)}{d\,s^3}\\\frac{\partial u_i^{\mathrm{RMS}}}{\partial x_j}&=\frac{\delta_{ij}}r-\frac{x_i x_j}{d\,r^3}\\\frac{\partial\tanh(a x_i)}{\partial x_j}&=\delta_{ij}\,a\big[1-\tanh^2(a x_i)\big]\end{aligned}
δij is one for i=j and zero otherwise. LayerNorm and RMSNorm couple features; the bare elementwise tanh map has a diagonal Jacobian. Learned affine gains multiply the corresponding output rows.

Replacing normalization therefore changes optimization, not only runtime. A trainable tanh scale can control saturation without recreating coordinate coupling.

Pre-Norm and Post-Norm change the gradient path

Same normalization family, different placement
LayoutOne sublayerImplication
Pre-Normx+F(Norm⁡(x))x+F(\operatorname{Norm}(x))Unnormalized skip retains a direct identity derivative
Post-NormNorm⁡(x+F(x))\operatorname{Norm}(x+F(x))Normalization sits on the main gradient path
Final normNorm⁡(xL)\operatorname{Norm}(x_L) before headControls final read; does not normalize every earlier skip

Pre-Norm controls what the branch reads, not the magnitude of the accumulated state. As that state grows, a similarly sized update can become a smaller relative change. This can reduce effective depth in some regimes. Post-Norm controls the resulting state's scale but changes backward propagation.

Neither is universally stronger or more stable. DeepNorm couples a modified Post-Norm skip with initialization. Its form is LN⁡(αx+F(x))\operatorname{LN}(\alpha x+F(x)), not simply a small branch multiplier. For an M-block decoder-only configuration, the report uses α=(2M)1/4\alpha=(2M)^{1/4} and selected Xavier gains β=(8M)−1/4\beta=(8M)^{-1/4}; Q/K gains remain 1. Do not transplant this recipe into a different block without checking its derivation. DeepNet Figure 2 ↗

Keep depth and width scales separate

Suppose a linear projection sums d independent unit-variance inputs with independent zero-mean weights. Weight variance 1d\frac1d keeps each output variance near 1. This is a width calculation. Nonlinearities, weight sharing and correlated inputs change its assumptions.

E∥∑ℓ=1LΔℓ∥22=Lσ2,E∥∑ℓΔℓ∥22=σL\mathbb E\left\|\sum_{\ell=1}^L\Delta_\ell\right\|_2^2=L\sigma^2,\qquad\sqrt{\mathbb E\left\|\sum_\ell\Delta_\ell\right\|_2^2}=\sigma\sqrt L
Assumes zero-mean, uncorrelated updates with equal expected squared norm σ². Perfectly aligned updates can instead have norm proportional to L; cross terms determine accumulation.

A branch multiplier of order 1L\frac1{\sqrt L} controls accumulated energy under the uncorrelated model. Coherent accumulation calls for a different analysis. This generic scaling argument is not the DeepNorm formula.

BERT-style 0.02 initialization is a model recipe, not a universal width law. At d=768d=768, 1d≈0.036\frac1{\sqrt d}\approx0.036. This numerical comparison alone does not explain why a particular training run succeeds. Biases, nonlinearities, normalization placement and warmup matter.

Likewise, p\sqrt p attention scaling follows from a specific independent-coordinate dot-product variance calculation. Real queries and keys can be correlated. The derivation and its limits belong in Attention →.

What does an activation change?

Composing only affine layers remains affine. A nonlinearity lets a feedforward branch build a richer token-wise transformation. Its value and derivative shape which signals and gradients pass through.

Scalar activations; x is a preactivation. On narrow screens, scroll horizontally
FunctionDefinitionMain distinction
ReLUmax⁡(0,x)\max(0,x)Negative branch has zero derivative
Leaky ReLU{xx≥0axx<0\begin{cases}x&x\ge0\\ax&x<0\end{cases}Small positive a keeps a negative slope
Sigmoidσ(x)=11+e−x\sigma(x)=\dfrac1{1+e^{-x}}Bounded 0–1; derivative σ(1−σ) saturates
Tanhtanh⁡(x)\tanh(x)Bounded −1–1; derivative 1−tanh² saturates
GELUxΦ(x)x\Phi(x)Smooth probabilistic gate; Φ is normal CDF
Swish / SiLUxσ(βx)x\sigma(\beta x); SiLU uses β=1\beta=1Smooth gate with a non-monotone negative region
Hardtanhclamp⁡(x,−1,1)\operatorname{clamp}(x,-1,1)Slope 1 inside; 0 outside; endpoints nondifferentiable
Hardtanh⁡a,b(x)={ax<axa≤x≤bbx>bddxHardtanh⁡a,b(x)={1a<x<b0x<a or x>b\begin{aligned}\operatorname{Hardtanh}_{a,b}(x)&=\begin{cases}a&x<a\\x&a\le x\le b\\b&x>b\end{cases}\\\frac{d}{dx}\operatorname{Hardtanh}_{a,b}(x)&=\begin{cases}1&a<x<b\\0&x<a\ \text{or}\ x>b\end{cases}\end{aligned}
a<b are fixed clipping bounds; defaults are −1 and 1. The mathematical derivative is undefined at a and b. A framework chooses a backward convention there.

A ReLU unit can receive zero branch gradients when its preactivations remain negative. This “dying ReLU” state is not necessarily permanent: upstream changes can move its inputs. Leaky ReLU changes that local derivative; it does not guarantee global optimization success.

Sigmoid and tanh still serve as output links and gates. Saturating tails do not make them obsolete. A sigmoid output maps one logit to a binary-class probability; stable training uses a logits-based loss. Binary cross-entropy → Hardtanh replaces smooth saturation with clipping; quantization or bounded-state applications need their own accuracy and gradient checks.

Read the activation curve

42−2−4−404xf(x)x=-1.00 → 0.0000

The plot uses one common scale: x∈[−4,4], vertical units unchanged between functions. Leaky slope is 0.1; Swish uses β=1. GELU uses the stated tanh approximation, not the exact normal CDF.

GELU⁡(x)≈x2[1+tanh⁡(2π(x+0.044715x3))]\operatorname{GELU}(x)\approx\frac x2\left[1+\tanh\left(\sqrt{\frac2\pi}(x+0.044715x^3)\right)\right]
The displayed approximation is distinct from exact xΦ(x).

Softmax couples several logits and normalizes them to a probability vector; it is not an independent scalar activation. Sparsemax and entmax use different geometries and matched losses; see Losses and Objectives →. No curve establishes a universally best activation or a universal variance guarantee.

From an activation to a gated feedforward layer

FFN⁡(x)=Wdown ϕ(Wupx+bup)+bdownSwiGLU⁡(x)=Wdown[(Wupx)⊙SiLU⁡(Wgatex)]\begin{aligned}\operatorname{FFN}(x)&=W_{\rm down}\,\phi(W_{\rm up}x+b_{\rm up})+b_{\rm down}\\\operatorname{SwiGLU}(x)&=W_{\rm down}\big[(W_{\rm up}x)\odot\operatorname{SiLU}(W_{\rm gate}x)\big]\end{aligned}
Column-vector notation. Up and gate map d→m; down maps m→d. Biases are optional.

A gated linear unit (GLU) multiplies one linear branch by a sigmoid-transformed branch. SwiGLU changes that gate to SiLU. The gate scales values; it is not a sampled probability that a neuron fires. SwiGLU gates can be negative or exceed 1.

An ordinary two-projection FFN has about 2dm parameters. A three-projection gated FFN has about 3dm. Matching this parameter budget requires reducing gated m to about two-thirds of the ordinary m. Equal hidden ratios are not equal budgets.

MoE makes the feedforward transformation conditional on expert routing. It does not remove the gate or residual design choices. See Mixture of Experts → for routing, balancing and expert layout.

A residual stream also mixes information across depth

The ordinary skip does more than help gradients. Its running sum gives every preceding update coefficient 1. Individual contributions can cancel. Once only the sum remains, a later layer cannot retrieve one contribution separately.

hℓ=∑i<ℓvi⟶∑i<ℓαi→ℓvisi→ℓ=wℓ⊤RMSNorm⁡(vi),αi→ℓ=softmax⁡i(s)\begin{aligned}h_\ell&=\sum_{i<\ell}v_i\quad\longrightarrow\quad\sum_{i<\ell}\alpha_{i\to\ell}v_i\\s_{i\to\ell}&=w_\ell^\top\operatorname{RMSNorm}(v_i),\qquad\alpha_{i\to\ell}=\operatorname{softmax}_i(s)\end{aligned}
Attention Residuals replaces uniform accumulation with a selective read over depth. v₀ is the embedding; subsequent vᵢ are sublayer outputs.

Each layer learns a pseudo-query wl. Its keys depend on the token's earlier states. Therefore a fixed learned query can still produce token-dependent weights. Keys are RMS-normalized for scoring; values remain the original source vectors.

Token attention chooses positions. Depth attention chooses earlier sublayer outputs. Full Attention Residuals (AttnRes, 2026) retains every source. For L sublayers and width d, depth retrieval adds O(L²d) arithmetic and O(Ld) history per token. Counting attention and MLP separately avoids a factor-of-two ambiguity.

The proposing team's target is Pre-Norm dilution. A convex depth mixture avoids an unbounded all-ones sum of fixed sources. The sources themselves can still grow. This is an architecture change, not a post-hoc patch for an existing checkpoint.

Read a source, not just the accumulated sum

Four sources can cancel without being identical

Four separately stored illustrative sources; scores use RMS-normalized keys
Source valueScoreWeight
[1.000, 0.000]0.0000.2500
[0.000, 1.000]0.0000.2500
[-1.000, 0.000]0.0000.2500
[0.000, -1.000]0.0000.2500

Layer pseudo-query w=[0.000, 0.000]. Weighted read=[0.000, 0.000]. The ordinary sum is always [0,0]; separate sources still contain distinguishable directions.

Weights sum to 1. Values stay unnormalized. This synthetic two-dimensional example changes the learned query between cases; it does not simulate training. In a trained layer, the query stays fixed and token-dependent sources change.

A zero pseudo-query initially produces uniform weights, not the ordinary unit-weight sum. Normalization changes the read's scale as well as its source preference. Key normalization reduces magnitude-based score domination; learned gains and source norms still need monitoring.

Compress history into block summaries

Full history is costly to retain and communicate. Block AttnRes sums sublayer outputs within a block. A later layer attends to the embedding, completed block summaries and the current block's partial sum.

bn=∑j∈Bnfj(hj)hℓ=DepthAttention⁡(embedding,completed bn,current partial sum)\begin{aligned}b_n&=\sum_{j\in\mathcal B_n}f_j(h_j)\\h_\ell&=\operatorname{DepthAttention}(\text{embedding},\text{completed }b_n,\text{current partial sum})\end{aligned}
Compress writes within blocks; keep selective reads between blocks.

With N blocks of roughly S=LNS=\frac LN sublayers, history storage becomes O(Nd)O(Nd) per token. N=LN=L approaches Full AttnRes. N=1N=1 retains the embedding separately and is close to ordinary accumulation, but is not identical to it.

A block boundary changes which sources are stored, not the meaning of an attention versus MLP operation. Compute a sublayer's read before updating its partial sum. At a boundary, append the finished summary once and begin a fresh partial sum. Do not count the same output in both sources.

The report's ablations find about eight blocks recover most Full AttnRes gains across its tested scales. A few distant summaries outperform retaining only nearby individual outputs in those comparisons. Block count is an empirical architecture/system choice, not a universal constant.

Make depth retrieval practical

Without recomputation, training already retains many activations. With recomputation or pipeline parallelism, additional history changes the storage and transfer pattern. The report caches summaries on physical pipeline ranks and transfers newly completed blocks rather than retransmitting the full history.

For P physical and V virtual stages, its peak transition transfer falls from O(PV) to O(P) chunks under that schedule. This is a transfer-count comparison, not a complete byte or latency model. Measured Block AttnRes training overhead is negligible without pipeline parallelism and under 4% with it on the reported stack.

At inference, fixed pseudo-queries permit a two-phase schedule. First batch all S queries against completed blocks. Then compute the sequential intra-block partial source and merge it with the precomputed result.

m=max⁡(ma,mb)ℓ=ema−mℓa+emb−mℓbo=ema−mℓaoa+emb−mℓbobℓ\begin{aligned}m&=\max(m_a,m_b)\\\ell&=e^{m_a-m}\ell_a+e^{m_b-m}\ell_b\\o&=\frac{e^{m_a-m}\ell_a o_a+e^{m_b-m}\ell_b o_b}{\ell}\end{aligned}
Stable online-softmax merge for nonempty groups with finite maxima and ℓ>0. Each group stores maximum m, shifted mass ℓ and normalized value o. A masked empty group must be skipped; if both are empty, use an explicit masked-row policy rather than dividing by zero.

For L=128,N=8,S=16L=128, N=8, S=16, estimated residual I/O per token per sublayer is 3d3d elements for ordinary residuals, 5.5d5.5d for Block AttnRes, 24d24d for scheduled Full AttnRes and 34d34d for four-stream mHC. These are residual-mechanism estimates, not whole-model traffic.

The report measures under 2% inference-latency overhead on its typical workloads. Long-context prefill adds NTdNTd history elements: its 128K, eight-block example is about 15 GB before sharding. Sequence sharding across P devices reduces that cache to NTPdN\frac TP d elements per device, with integration into reduce-scatter/all-gather. See Distributed Training and Parallelism →.

What the Attention Residuals experiments establish

The proxy study uses MoE models with 194M–528M activated non-embedding parameters, 38.7B–119B tokens, 12–17 attention layers plus equally many MLP layers, and 8K context. Its fitted curves describe proxy training loss, not serving latency.

Lbaseline=1.891C−0.057LBlock=1.870C−0.058LFull=1.865C−0.057\begin{aligned}L_{\mathrm{baseline}}&=1.891C^{-0.057}\\L_{\mathrm{Block}}&=1.870C^{-0.058}\\L_{\mathrm{Full}}&=1.865C^{-0.057}\end{aligned}
C>0 is training compute in the report’s PFLOP/s-day units, not wall-clock days. The fits describe the stated proxy runs; extrapolation beyond them is not established.

At 5.6 PFLOP/s-days, the fitted Block loss is 1.692 versus baseline 1.714. The inferred 1.25× compute advantage is a curve comparison, not a universal wall-clock saving. At the largest proxy point, measured validation losses are baseline 1.719, Block 1.693 and Full 1.692.

Ablations in the report’s 436M-active proxy setting; lower validation loss is better
MethodLoss
Pre-Norm1.766
DenseFormer static mixing1.767
mHC1.747
Full AttnRes1.737
Input-dependent query1.731
Input-independent mixing1.749
Sigmoid rather than softmax1.741
Full without key RMSNorm1.743
Block, size 41.746
Block, 16 heads1.752
Block without key RMSNorm1.750

The input-dependent query improves this loss but requires a d×d projection and sequential reads. The simpler pseudo-query supports batched inference. The multi-head result suggests shared depth choices are useful in this setting; it does not prove channel-specific retrieval is never useful.

The larger controlled experiment is Kimi Linear: 48B total, 3B active parameters; 27 Transformer blocks counted as 54 sublayers; eight of 256 routed experts plus one shared expert. Six sublayers per AttnRes block produce nine block summaries plus the embedding. Training uses Muon, WSD, an 8M-token global batch, 1T pretraining tokens at 4K, about 400B high-quality mid-training tokens and context extension to 32K.

Base-model downstream comparison; score changes are percentage points
BenchmarkBaselineBlock AttnResChange
MMLU73.574.6+1.1
MMLU-Pro52.252.20.0
GPQA-Diamond36.944.4+7.5
BBH76.378.0+1.7
MATH53.557.1+3.6
HumanEval59.162.2+3.1
MBPP72.073.9+1.9
CMMLU82.082.9+0.9
C-Eval79.682.5+2.9

The method matches or improves every listed score; MMLU-Pro ties. Larger reasoning/code gains are consistent with the team's compositional-retrieval hypothesis, not proof of that mechanism. This is not a controlled post-training or agent comparison.

Learned weights are mainly local, with long skips and persistent embedding reads. Attention sublayers use broader depth histories; MLP reads are more concentrated near recent sources. Some sources become depth-wise attention sinks. Block summaries may regularize as well as compress, but that causal interpretation remains a hypothesis.

Residual mechanisms change different accessible-history rules
MethodHistoryWeights
Standard residualOne accumulated streamFixed unit additions
ReZero / LayerScaleOne accumulated streamLearned static branch scale
HighwayRecurrent streamInput-dependent gate
Hyper-Connections / mHCMultiple recurrent streamsInput-dependent mixing
DenseFormerEarlier individual outputsStatic learned weights
Full AttnResEvery individual outputToken-dependent softmax
Block AttnResSummaries and partial blockToken-dependent softmax

The report interprets recurrent multi-stream mechanisms as structured depth mixers, unlike dense cross-layer access. Stronger residual baselines matter. No independent replication is established here. Its largest controlled model has 3B active parameters; fitted compute and custom-kernel overheads must not be generalized to larger or unoptimized deployments. Deeper/narrower proxy preferences also increase serial inference depth. Attention Residuals report ↗ · Implementation ↗

Gated Residual: spend extra capacity on the read

A single residual sum gives every new sublayer the same accumulated state. Widening that stream creates separate paths, but each path also costs memory traffic. Qwen separates two questions: does width help, and which read/write machinery justifies its cost?

A simple four-branch baseline reads a learned scalar mixture and writes to one branch in round-robin order. It already improves loss. Hyper-Connections adds data-dependent reads, writes and branch mixing. Gated Residual (GR) keeps richer reads and writes but removes the explicit branch-mixing matrix.

The gate builds on GatedNorm, which supplies an explicit feature-dependent rescaling after normalization:

GatedNorm⁡(u)=RMSNorm⁡(u)⊙σ ⁣(W2SiLU⁡(W1RMSNorm⁡(u)))\operatorname{GatedNorm}(u)=\operatorname{RMSNorm}(u)\odot\sigma\!\left(W_2\operatorname{SiLU}(W_1\operatorname{RMSNorm}(u))\right)
W1 and W2 form a low-rank bottleneck. The sigmoid gate is elementwise. GR applies this idea to a widened stream, with the exact branch-wise normalization and averaging below.
R^i=RMSNorm⁡(Ri;γi),i=1,…,4G=unvec⁡σ(WuSiLU⁡(14Wdvec⁡(R^)))x=14∑i=14Gi⊙R^iy=F(x)s=2σ(14Wwvec⁡(R^))Ri′=Ri+siy\begin{aligned}\widehat R_i&=\operatorname{RMSNorm}(R_i;\gamma_i),\quad i=1,\ldots,4\\G&=\operatorname{unvec}\sigma\left(W_u\operatorname{SiLU}\left(\tfrac14W_d\operatorname{vec}(\widehat R)\right)\right)\\x&=\tfrac14\sum_{i=1}^{4}G_i\odot\widehat R_i\\y&=F(x)\\s&=2\sigma\left(\tfrac14W_w\operatorname{vec}(\widehat R)\right)\\R'_i&=R_i+s_i y\end{aligned}
R has shape 4 × d per token. Read gates G have shape 4 × d; write strengths s have shape 4. Wd is (d/8) × 4d, Wu is 4d × (d/8), and Ww is 4 × 4d.

Normalize each branch independently, with its own gain. Predict gates from all branches rather than pooling first. Each read gate lies between zero and one; each write strength lies between zero and two. Read weights are not a softmax distribution and need not sum to one. GR replaces the sublayer pre-normalization; adding another ordinary Pre-Norm would change the architecture.

  1. Four residual branchesKeep four d-vectors per token.
  2. Normalize → gate → averageOne feature-specific read produces a d-vector.
  3. Attention or MoEThe sublayer still consumes and produces width d.
  4. Four gated additionsWrite the same output with four independent scalar strengths.
Original schematic of GR, based on report Equations 30–34. Four residual branches do not mean four attention or MLP evaluations.
Table 5: 25B-A3B, 560B tokens; nine-task arithmetic mean
ResidualTraining lossMean accuracy
Pre-Norm1.61750.91
Static mHC1.59652.49
Dynamic mHC1.59454.47
GR1.5954.66

The dynamic variant reduces loss only 0.002 relative to static mHC, but improves mean accuracy by 1.98 percentage points. Width and data dependence therefore look different under loss and downstream evaluation. GR and dynamic mHC are close at this scale; the argument for GR also includes memory traffic and stability, not a decisive quality margin alone.

Channel-specific reads help; channel-specific writes add almost nothing. Branch mixing adds no significant benefit after improving the read/write path. Removing that operator saves one full residual-state read per block. Standard random initialization suffices in the final GR configuration; a learned static term adds no useful gain. Each attention and MLP sublayer has its own GR module.

Comparison with Attention Residuals and GatedNorm
Table 6: 28 layers, loss; S counts sublayers per Block AttnRes summary
DesignWithout GatedNormWith GatedNorm
Pre-Norm1.7891.787
Block AttnRes, S=41.7731.768
Block AttnRes, S=21.7701.766
Full AttnRes1.7621.758
GR, four branchesNot a separate setting1.762

At 48 layers, Block AttnRes with S=4 reaches 1.711 versus 1.707 for GR. Full AttnRes plus GatedNorm is better on the 28-layer loss comparison, while storing a different amount of depth history. Do not summarize this table as GR universally beating depth attention.

What do the extra paths preserve?

In a matched 20-layer probe, the authors decompose writes into later reads at the gates taken by the actual forward pass. Across five GR checkpoints, one branch carries long-range paths; the others remain more local. The branch identity is exchangeable, not assigned in advance.

The normalized contribution of layer-0 GDN to layer-15 attention rises from 0.020 to 0.138. Typical long-range skips are 10.9 layers versus 3.4–3.9 for other branches. These contribution magnitudes are descriptive, not causal attribution or probabilities that a specific fact survives. The average skip changes little; GR redistributes influence toward selected short and long paths.

Reading only the two highest-gated branches looks nearly harmless during pretraining but degrades post-training quality. They reject that shortcut. FP8 residual storage instead halves this state's bytes relative to BF16 with almost no reported quality loss. This does not halve all activation memory or establish FP8 arithmetic throughout the model. Read and write are separately fused. Gates under stress → · Residual traffic →.

Qwen3.8-Next architecture report, §2.2, Tables 5–6 and Figure 7, pp. 10–14 (26 August 2026) ↗.

Sharing embeddings changes the parameter budget

Input embeddings and an ordinary output matrix both have V×d parameters. Tying uses the same matrix for both. A tied head projects h against the rows used for token lookup; it does not skip the vocabulary projection.

Puntied=2Vd,Ptied=Vd,ΔP=VdP_{\rm untied}=2Vd,\qquad P_{\rm tied}=Vd,\qquad \Delta P=Vd
Excludes biases, factorized embeddings and unequal input/output dimensions.

At V=50,000 and d=2,048, tying saves 102.4M parameters. That can be substantial in a small model. In a larger backbone, it is a smaller fraction of the budget.

Compare two distinct experiments. Keeping the backbone fixed isolates the extra freedom and extra parameters of untying. Keeping total parameters fixed requires reallocating width, depth or another part. Those comparisons answer different questions.

Tying can regularize or reduce quality in a particular setting. Untying can improve freedom without removing the output-rank limit. Large-model parameter fractions alone do not establish a quality benefit.

Why softmax cannot recover every distinction

A bias-free linear head factors logits through width d. Log normalization subtracts one scalar per context, so it adds at most one rank-one term.

Z=HW⊤,rank⁡(Z)≤dsc=log⁡∑xexp⁡(Zc,x)log⁡P=Z−s1⊤,rank⁡(log⁡P)≤d+1\begin{aligned}Z&=HW^\top,\qquad \operatorname{rank}(Z)\le d\\s_c&=\log\sum_x\exp(Z_{c,x})\\\log P&=Z-s\mathbf1^\top,\qquad\operatorname{rank}(\log P)\le d+1\end{aligned}
H: N×d context states; W: V×d output embeddings; s: N-vector. The bound concerns log probabilities, not the rank of P.

The sharper test removes these row constants. Choose a reference token r. The log-odds matrix Dc,x=log⁡p(x∣c)p(r∣c)D_{c,x}=\log\frac{p(x\mid c)}{p(r\mid c)} equals hc⊤(wx−wr)h_c^\top(w_x-w_r). Its rank is at most d. The probability matrix P itself can have higher rank; that is not a contradiction.

A positive target distribution from two contexts; token C is the reference. On narrow screens, scroll horizontally
Contextp(A)p(B)p(C)log A/Clog B/C
112\dfrac1214\dfrac1414\dfrac14log⁡2\log 20
214\dfrac1412\dfrac1214\dfrac140log⁡2\log 2

This 2×2 log-odds matrix has determinant (log⁡2)2(\log 2)^2 and rank 2. A bias-free d=1d=1 head cannot represent it. Increasing Transformer depth without increasing the final factorization width cannot repair that exact limitation.

A=log⁡P∗,F(A)={A+λ1⊤:λ∈RN},d≥min⁡A′∈F(A)rank⁡(A′)A=\log P^*,\quad\mathcal F(A)=\{A+\lambda\mathbf1^\top:\lambda\in\mathbb R^N\},\quad d\ge\min_{A'\in\mathcal F(A)}\operatorname{rank}(A')
Assumes strictly positive target probabilities and a bias-free linear head; sufficient representability also needs a context network capable of the required factorization.

A row shift changes rank by at most one. Thus d<rank⁡(A)−1d<\operatorname{rank}(A)-1 is a sufficient obstruction. Output bias adds a shared vocabulary term of rank at most one. It changes these precise bounds; the two-context example above is deliberately bias-free.

Mix distributions after normalization

A mixture of contexts combines hidden states first: h′=∑kπkhkh'=\sum_k\pi_k h_k, then softmax⁡(h′W⊤)\operatorname{softmax}(h'W^\top). This is still one d-dimensional state. A mixture of softmaxes (MoS) normalizes each component separately, then adds probability vectors.

pMoC=softmax⁡ ⁣[(∑kπkhk)W⊤]pMoS=∑kπksoftmax⁡(hkW⊤),πk≥0,∑kπk=1\begin{aligned}p_{\rm MoC}&=\operatorname{softmax}\!\left[\left(\sum_k\pi_k h_k\right)W^\top\right]\\p_{\rm MoS}&=\sum_k\pi_k\operatorname{softmax}(h_kW^\top),\quad\pi_k\ge0,\quad\sum_k\pi_k=1\end{aligned}
Only the second order escapes the original shared linear-softmax factorization. It does not guarantee useful high rank for every parameter choice.

Two modes versus their averaged state

Shared output embeddings w=[−1,0,1]; component states −2 and +2
TokenComponent −2Component +2Mix states → softmaxSoftmax → mix
00.86680.01590.33330.4413
10.11730.11730.33330.1173
20.01590.86680.33330.4413

Weight on component −2: 0.50. At π=0.5, mixing states gives h=0 and probabilities [1/3,1/3,1/3]. Mixing distributions gives approximately [0.4413,0.1173,0.4413]. Two plausible extremes need not make the middle token equally plausible.

One context demonstrates operation order, not matrix rank. The multi-context rank argument is given above.

Output modifications affect different limits
ChangeEffect
More depth / MLP before same-width headImproves context function; rank bound remains
Larger final output widthRaises factorization capacity
Untied embeddingsAdds parameter freedom; width bound remains
Output biasAdds a rank-one vocabulary term
Mixture of contextsDoes not break the factorization
Mixture of softmaxesCan express higher-rank log probabilities
Suitable nonlinear logitsCan change rank; analyze the actual function
Sampled softmaxChanges objective computation, not this head family
Hierarchical softmaxChanges factorization; no automatic higher-rank guarantee

MoS is not MoE. A routed FFN changes how h is produced. MoS changes how the final distribution is formed. A model can use either, both or neither.

Separate algebraic rank from useful probability error

Yang et al.'s ICLR 2018 work evaluates RNN language models, not contemporary large Transformers. On Penn Treebank with 10,000 tokens, reported empirical log-probability ranks are 400 for a width-400 softmax, 280 for width-280 MoC and 9,981 for width-280 MoS. Numerical rank depends on the threshold.

Additional components initially improve rank and likelihood, but can stop helping or overfit. The original settings report roughly 2–3× slower training with up to 15 components. These experiments establish a useful counterexample, not a recommendation that every LLM replace its head. Softmax bottleneck: theory and PTB evidence ↗

High exact rank can be dominated by tiny singular values. The practical question is probability error in the discarded directions. The true language distribution's high rank is a hypothesis, not an observable theorem. Computing vocabulary logits can also be expensive; that computational bottleneck is separate from representational rank.

For a diagnostic, collect diverse contexts and a fixed token subset. Compute stable log probabilities, subtract one reference-token column, and inspect the singular-value spectrum. Report precision, threshold and matrix dimensions. Too few contexts or tokens cap measured rank. Better rank alone does not guarantee better cross-entropy.

A gradient boundary is not a teacher update

sg⁡(x)=x,∂sg⁡(x)∂x=0L=∥s−sg⁡(t)∥22,∂L∂s=2(s−t),∂L∂t=0\begin{aligned}\operatorname{sg}(x)&=x,&\frac{\partial\operatorname{sg}(x)}{\partial x}&=0\\\mathcal L&=\|s-\operatorname{sg}(t)\|_2^2,&\frac{\partial\mathcal L}{\partial s}&=2(s-t),\quad\frac{\partial\mathcal L}{\partial t}=0\end{aligned}
Stop-gradient changes derivative paths without changing the target value.

A self-supervised matching loss can compare two augmented views of the same input. The student predicts the detached target representation. Detachment changes the backward path, not either view's forward value.

A detached target branch can still share parameters with the student. Gradients through the student path update those shared parameters. Detaching one tensor does not freeze every use of its weights.

An exponential moving average (EMA) teacher is a separate update rule.

θteacher←aθteacher+(1−a)θstudent\theta_{\mathrm{teacher}}\leftarrow a\theta_{\mathrm{teacher}}+(1-a)\theta_{\mathrm{student}}
Apply this parameter update outside differentiation. Momentum a lies in [0,1]; a=1 leaves the teacher unchanged, while a=0 copies the student.

BYOL and DINO use momentum targets. SimSiam uses stop-gradient without a momentum teacher. Stop-gradient does not inherently require storing two parameter copies. SimSiam ↗

For a plain matching loss, a constant output can still minimize disagreement. Stop-gradient alone is not a general anti-collapse proof. Predictors, normalization, centering, variance objectives or negatives change the full system. Self-Supervised Vision Learning connects DINO, BYOL, SimSiam, LeJEPA and variance regularization to their complete anti-collapse objectives.

Reconstruct activations instead of storing every layer

Ordinary x+F(x) is not automatically invertible. Reversible blocks impose an additive coupling structure. Split channels into x₁,x₂, then update them in sequence. This Feistel-like additive coupling is a reversible data path, not an encryption scheme.

y1=x1+f(x2),y2=x2+g(y1)x2=y2−g(y1),x1=y1−f(x2)\begin{aligned}y_1&=x_1+f(x_2),&y_2&=x_2+g(y_1)\\x_2&=y_2-g(y_1),&x_1&=y_1-f(x_2)\end{aligned}
Invert the second write first. f and g themselves need not be invertible.

Forward writes and reverse reconstruction

Follow a scalar pair through the same equations used for channel vectors.

Keep the input

02132—3—

Cell order: x₁, x₂, y₁, y₂. A dash means not yet computed or not needed in that reconstruction step.

f(x)=2x, g(x)=−x/2. The functions themselves need not be invertible in general.

Exact small input, not a speed benchmark. Step order follows the algorithm; playback is optional. All input/output roles are named; this sequence illustrates exact arithmetic, not floating-point error.

Under the ideal reversible-stack assumptions, saved boundary activations can become O(1) in depth rather than O(L). Parameters, gradients, optimizer states, temporary branch activations and non-reversible boundaries still consume memory.

Backward reconstructs an input, recomputes the local forward and differentiates that local computation. Ordinary eager autograd may still retain the whole forward graph unless a custom backward/storage strategy is used. Reconstruction is not a gradient approximation in exact arithmetic.

The original RevNet operation count estimates 4N versus ordinary 3N: about 33% extra. With roughly equal GPU forward/backward costs, the paper discusses about 50% instead. Neither is a universal measured overhead. Checkpointing makes a related recomputation/storage tradeoff without requiring this architecture. RevNet: coupling and recomputation ↗

Floating-point subtraction can accumulate reconstruction error. Recompute dropout with the same random state. Store or checkpoint non-reversible operations. Verify reconstructed values and parameter gradients against a stored-activation baseline before claiming memory savings.

Count the actual architecture

Use conventional attention geometry d=hpd=hp, with h query heads, hkvh_{\mathrm{kv}} key/value heads and p head width. GQA usually requires h divisible by hkvh_{\mathrm{kv}}. Some architectures use a different attention-inner width; the following formulas must then change.

Pattn≈2d2(1+hkvh)PFFN≈{2dmordinary3dmgatedPtotal≈L(Pattn+PFFN)+cVd,c={1tied2untiedMKV≈2LBT hkvp belem\begin{aligned}P_{\rm attn}&\approx2d^2\left(1+\frac{h_{\rm kv}}h\right)\\P_{\rm FFN}&\approx\begin{cases}2dm&\text{ordinary}\\3dm&\text{gated}\end{cases}\\P_{\rm total}&\approx L(P_{\rm attn}+P_{\rm FFN})+cVd,\quad c=\begin{cases}1&\text{tied}\\2&\text{untied}\end{cases}\\M_{\rm KV}&\approx2LBT\,h_{\rm kv}p\,b_{\rm elem}\end{aligned}
Biases, normalization, positional parameters and auxiliary heads are omitted. Cache assumes retained keys and values at all positions/layers; b_elem is bytes per stored element.

Depth scales this parameter estimate linearly. Width generally contributes quadratically when head geometry and FFN ratio scale with it. KV cache instead depends directly on key/value heads and context length. Local-window eviction changes cache only if the serving implementation actually evicts those states.

Valid illustrative geometries, not optimal training recipes. On narrow screens, scroll horizontally
dQuery headsKV headspGated m
2,048164128~5,461
3,0722461288,192
4,09632812814,336
4,0966486414,336

A 4,096-wide model with 32 heads cannot use p=64p=64 under d=hpd=hp. For p=64p=64, use 64 query heads or explicitly change attention-inner width. The 14,336 FFN width is 3.5d3.5d: its gated cost is 10.5d210.5d^2, not the ordinary 4d4d FFN's 8d28d^2.

Head sizes 64 or 128 and GQA ratios 2,4,8 are candidate configurations, not quality or hardware guarantees. Profile kernels and compare trained quality. Use a dense baseline before attributing benefits to sparse layouts, shared experts or dense/MoE interleaving.

Parameter count is not wall-clock cost. MoE has distinct total and active parameters; looped models can reuse parameters while increasing compute. MTP, multimodal frontends, state-space mixers and nonuniform layer widths change accounting. Do not force MLA, OpenELM or Mamba into these conventional formulas.

Match data, batch size, optimizer, token budget and evaluation when comparing shapes. Critical batch size and FP8 behavior require their own training analysis. A depth-before-width heuristic must be tested against serial latency and the residual mechanism, not treated as a universal allocation law.

Turn a budget into testable designs

Choose deployment memory, latency and context requirements first. Then choose width and depth together, validate head geometry, set KV sharing, and tune feedforward capacity. These are experiment axes, not an optimal recipe.

Design candidates and their failure checks
CandidateWhy consider it?What can invalidate it?
Dense baselineSimple always-on transformationsCompare trained quality and actual throughput before adding routing complexity
Long-context hybridLocal layers reduce access cost; periodic global layers retain direct retrievalA five-local/one-global cadence is a report example, not a universal ratio
Interleaved dense/MoEAlways-on transformations plus large conditional capacityCommunication, shared-expert choices, drop policy and router balance can dominate
Looped MoEReuse stored weights while changing selected experts across passesRouting must actually vary; trained exit boundaries do not guarantee safe early stopping

Count unique parameters for storage, executed active parameters for arithmetic, and repeated passes for total compute. Dense interleaving can make shared experts less necessary in a tested design; it does not prove shared experts are useless. Dropless routing still needs a declared capacity and imbalance policy.

Loop boundaries can be candidates for early exit when training exposes those states to output objectives. Evaluate stopping quality and latency rather than assuming every reused block is output-ready. Recurrent and Looped Models → · Routing and expert layout →

Increasing batch size beyond the useful critical regime can reduce returns. The critical regime depends on the data, loss and optimizer. Compare more steps, different data or architecture changes at matched compute. Optimization → · Scaling Laws →

Measure widths, precision formats and kernel support on the actual stack. Nonuniform layer widths, latent-compression models, sparse multimodal frontends and state-space mixers require their own accounting. Precision → · Local/global access → · Performance accounting →

Checks before scaling the model

Start with tensor contracts: residual additions must match shapes; heads must match the declared inner width; training targets must be shifted. Confirm causal masks with a future-token perturbation test.

Then measure hidden-state RMS, branch-output RMS and gradient RMS by depth. Change normalization placement and initialization together only with an explicit rationale. A bounded branch input is not proof of a bounded residual stream.

Check tied weight identity, vocabulary shape and parameter counts. Distinguish rank limitation from numerical softmax stability. For reversible execution, compare values and gradients and measure peak memory, not only the number of saved tensors.

Finally measure complete training and serving cost. A lower loss at matched FLOPs can lose its advantage through communication, memory traffic or deeper serial execution. Use the parallelism reader to connect architecture to placement and communication.

Sources and connected notes

BatchNorm (2015) ↗ · LayerNorm (2016) ↗ · RMSNorm (2019) ↗ · DeepNorm (2022) ↗ · Attention Residuals (2026) ↗

Softmax bottleneck (2017 / ICLR 2018) ↗ · Monotonic nonlinear logits ↗ · Sigsoftmax ↗ · Reversible networks ↗ · SimSiam ↗

Smol training playbook ↗ · Initialization and parameterization ↗ · BERT’s 0.02 initialization ↗ · DeepNorm discussion ↗ · Pre-Norm versus Post-Norm ↗ · Tanh versus normalization ↗

Attention Residuals ↗ · Kimi Linear ↗.