Skip to content
AIAI Wranglers

28 Neural Network Tricks

The gap between a neural network that works in theory and one that works in practice is often a single trick. A carefully chosen initialisation scheme, a normalization layer inserted in exactly the right place, a learning rate schedule that warms up before it decays, each of these is a small engineering decision, easy to overlook, yet capable of transforming a divergent training run into a state-of-the-art result. The history of deep learning is littered with breakthroughs that were, at their core, tricks: ideas that are easy to implement, hard to discover, and disproportionately impactful.

In 5, we introduced the raw building blocks of deep neural networks (feedforward layers, convolutional layers, residual connections, normalisation layers, and the Transformer's attention mechanism). Those building blocks provide the architecture; the tricks in this chapter provide the engineering wisdom that makes the architecture trainable, stable, and efficient. Without Xavier initialisation, networks deeper than five layers collapse during training. Without residual connections, gradients vanish long before they reach the early layers. Without mixed-precision training, modern LLMs would require twice the memory and twice the time. The tricks are not optional flourishes layered atop a working system; they are the system.

We organise this chapter around fifteen tricks, presented roughly in the order a practitioner encounters them when building a modern neural network. The first five tricks (Trick #1 - Initialize Wisely- Trick #4 - Add Skip Connections Everywhere) address the foundational challenge of getting gradients to flow: how to initialise weights, choose activation functions, normalise intermediate representations, connect layers with gates, and build skip connections. The next five tricks (Trick #6 - Encode Position Cleverly- Trick #10 - Train in Low Precision) tackle the Transformer era's central concerns: encoding position, attending efficiently, regularising creatively, scheduling the learning rate, and training in low precision. The final five tricks (Trick #11 - Distill Knowledge- Trick #15 - Combine Tricks Synergistically) address the deployment challenge of trillion-parameter models: distillation, quantisation, pruning and routing, fast decoding, and the art of combining tricks synergistically.

fig:tricks:timeline provides a serpentine timeline showing when each trick was introduced, revealing how the field has evolved from the foundational ideas of the 1980s, through the Transformer revolution, to the efficiency innovations that dominate current research.

A serpentine timeline of neural network tricks from 1986 to 2025. Row 1 (1986–2015): foundational ideas (backpropagation, initialisation, regularisation, and skip connections) that made deep training possible. Row 2 (2015–2021): the Transformer era brought an explosion of new tricks for activations, normalisation, gating, position encoding, and low-precision training. Row 3 (2022–2025): efficiency refinements for trillion-parameter models, including Flash Attention, grouped-query attention, speculative decoding, and quantisation.

Trick #1 - Initialize Wisely

Weight initialisation is the first decision a practitioner makes when building a neural network, and for decades it was one of the most poorly understood. The consequences of getting it wrong are immediate and catastrophic: activations explode to NaN within a few forward passes, or gradients shrink to machine epsilon within a few backward passes, and the network learns nothing. The consequences of getting it right are equally dramatic: a well-initialised 100-layer network trains as smoothly as a 5-layer one.

Historical Note.

The dark age of random initialisation. Before 2010, the standard advice for weight initialisation was astonishingly vague: “draw from a uniform distribution, maybe [0.5,0.5], maybe [1,1]; experiment and see what works.” LeCun et al. [1] had noted as early as 1998 that the variance of the weights should be related to the fan-in of each layer, but the recommendation was buried in a long technical report and rarely followed. As a result, deep networks (anything beyond 3–5 layers) routinely failed to train. Researchers attributed the failure to “the difficulty of deep learning” rather than to the mundane cause of poor initialisation.

The breakthrough came in 2010. Glorot and Bengio [2] published a systematic analysis of signal propagation through deep networks, deriving the condition under which activations and gradients neither explode nor vanish. Their “Xavier initialisation” was the first principled scheme, and it immediately enabled the training of networks with 10–20 layers. Five years later, He et al. [3] extended the analysis to ReLU networks, and the era of 100-layer networks began. In retrospect, the key insight is almost embarrassingly simple: match the variance of the weights to the fan-in so that the variance of activations is preserved layer to layer. But this simple idea was the single most important enabler of deep learning.

Variance Propagation Analysis

The central question of initialisation theory is: how does the variance of activations change as a signal propagates through a deep network? To answer it, we analyse a simple linear network (no activation functions) and then extend the analysis to nonlinear networks with ReLU.

Consider an L-layer feedforward network with layer widths n0,n1,,nL. At layer l, the pre-activation is (Forward Preact)𝒛(l)=𝑾(l)𝒂(l1), where 𝑾(l)nl×nl1 is the weight matrix and 𝒂(l1)nl1 is the activation from the previous layer (with 𝒂(0)=𝒙). We omit biases for clarity; they are typically initialised to zero and do not affect the variance analysis.

Under the assumptions that (i) the weights Wij(l)𝒩(0,σl2) are i.i.d., (ii) the weights are independent of the activations, and (iii) the activations have zero mean (𝔼[ai(l1)]=0), the variance of a single pre-activation component is (VAR Single Layer)𝖵ar(zj(l))=i=1nl1𝖵ar(Wij(l))𝖵ar(ai(l1))=nl1σl2𝖵ar(ai(l1)). This is the fundamental variance recursion: the variance at each layer is scaled by a factor of nl1σl2 relative to the previous layer.

After L layers, the variance accumulates multiplicatively: (VAR L Layers)𝖵ar(zj(L))=𝖵ar(xi)l=1L(nl1σl2). Each factor nl1σl2 acts as a gain: if it exceeds 1, the variance grows exponentially with depth; if it is less than 1, the variance shrinks exponentially. Only when nl1σl2=1 for every layer does the variance remain constant.

Remark 1.

The same analysis applies to the backward pass. Let δ(l)=/𝒛(l) denote the gradient of the loss with respect to the pre-activations. Then δ(l1)=(𝑾(l))δ(l) (for linear activations), and (VAR Backward)𝖵ar(δi(l1))=nlσl2𝖵ar(δj(l)). Now the gain factor is nlσl2: the fan-out replaces the fan-in. For the gradients to be preserved, we need nlσl2=1.

We face a tension: the forward pass requires σl2=1/nl1 (fan-in), while the backward pass requires σl2=1/nl (fan-out). These coincide only when nl1=nl, i.e., all layers have the same width. For networks with varying widths, a compromise is needed.

Xavier/Glorot Initialisation

Glorot and Bengio [2] proposed resolving the fan-in versus fan-out tension by taking the harmonic mean.

Definition 1 (Xavier/Glorot Initialisation).

Let nin and nout denote the fan-in and fan-out of a layer. Xavier initialisation draws the weights from (Xavier Normal)Wij𝒩(0,2nin+nout), or equivalently from a uniform distribution (Xavier Uniform)Wij𝒰(6nin+nout,6nin+nout), where the uniform bounds are chosen so that the variance matches (Xavier Normal): for a uniform distribution on [a,a], 𝖵ar(W)=a2/3.

Proposition 1 (Variance Preservation under Linear Activation).

Under Xavier initialisation with linear activations, the variance of the pre-activations satisfies (Xavier VAR FWD)𝖵ar(zj(l))=2nl1nl1+nl𝖵ar(ai(l1)). When nl1=nl, the variance is exactly preserved. More generally, the multiplicative factor 2nl1/(nl1+nl) remains close to 1 whenever the fan-in and fan-out are of similar magnitude.

Proof.

From the variance recursion (VAR Single Layer), 𝖵ar(zj(l))=nl1σl2𝖵ar(ai(l1)). Substituting σl2=2/(nl1+nl): 𝖵ar(zj(l))=nl12nl1+nl𝖵ar(ai(l1))=2nl1nl1+nl𝖵ar(ai(l1)). When nl1=nl=n, this reduces to 2n/(n+n)=1, so the variance is exactly preserved.

For the backward pass, the analogous calculation gives a factor of 2nl/(nl1+nl), which also equals 1 when nl1=nl. The Xavier variance 2/(nin+nout) is the unique choice that simultaneously makes both factors as close to 1 as possible; it is the harmonic mean of the forward-only choice 1/nin and the backward-only choice 1/nout.

Remark 2.

Xavier initialisation assumes linear (or tanh) activations, because the derivation relies on 𝔼[ai]=0 and 𝖵ar(ai)=𝖵ar(zi). For tanh, this is approximately satisfied near the origin where tanh(z)z. For ReLU, the assumption fails dramatically: half the activations are zeroed out, effectively halving the effective fan-in.

Kaiming/He Initialisation

He et al. [3] observed that for ReLU activations, Xavier initialisation causes the variance to halve at each layer, because ReLU zeroes out negative activations. To compensate, they derived a modified variance that accounts for the ReLU's asymmetry.

The key calculation is the second moment of a ReLU-transformed Gaussian. If z𝒩(0,σ2), then a=max(0,z), and (RELU Second Moment)𝔼[max(0,z)2]=0z212πσ2exp(z22σ2)dz=σ22=𝖵ar(z)2. The integral follows from the half-Gaussian second moment: for a standard Gaussian, 𝔼[Z2𝟏Z>0]=1/2, and scaling by σ2 gives σ2/2.

Since 𝔼[max(0,z)]0 for the ReLU (the mean is σ/2π), we have (RELU Variance)𝖵ar(max(0,z))=𝔼[max(0,z)2](𝔼[max(0,z)])2=σ22σ22π=σ22(11π). For the purpose of the initialisation derivation, the simpler bound 𝔼[max(0,z)2]=𝖵ar(z)/2 suffices, because we want 𝖵ar(z(l))𝖵ar(z(l1)) for the pre-activations.

Definition 2 (Kaiming/He Initialisation).

For a layer with fan-in nin and ReLU activation, He initialisation draws the weights from (HE INIT)Wij𝒩(0,2nin). For the backward-pass variant (“fan-out mode”), the variance is 2/nout.

The factor of 2 compensates for the ReLU halving: each layer's forward-pass gain is ninσ212=nin2nin12=1, so the variance of the pre-activations is preserved exactly.

Remark 3.

For Leaky ReLU with negative slope α, the second moment becomes 𝔼[LeakyReLU(z)2]=𝖵ar(z)(1+α2)/2, and the corrected variance is σ2=2/((1+α2)nin). Setting α=0 recovers He initialisation; setting α=1 (the identity function) recovers Xavier with fan-in only.

Orthogonal Initialisation

Xavier and He initialisations control the average variance propagation, but they do not guarantee that all singular values of the weight matrix are well-behaved. A Gaussian random matrix has singular values that follow the Marchenko–Pastur distribution, which means some directions may amplify signals while others suppress them. Orthogonal initialisation eliminates this variability entirely.

Definition 3 (Orthogonal Initialisation).

To initialise a weight matrix 𝑾m×n:

  1. Generate a random Gaussian matrix 𝑮m×n with entries Gij𝒩(0,1).

  2. Compute the thin SVD: 𝑮=𝑼𝚺𝑽.

  3. If mn, set 𝑾=𝑼 (the left singular vectors). If m>n, set 𝑾=𝑽 (the right singular vectors).

The resulting matrix has orthonormal rows (or columns), so 𝑾𝑾=𝑰 (if mn) or 𝑾𝑾=𝑰 (if m>n).

The key property is dynamical isometry : all singular values of 𝑾 are exactly 1. For a product of L orthogonal matrices, 𝑾(L)𝑾(L1)𝑾(1), all singular values of the product remain exactly 1 (since the product of orthogonal matrices is orthogonal), so the signal is preserved perfectly, not merely in expectation, but for every input direction.

Saxe et al. [5] proved that orthogonal initialisation produces exact solutions to the learning dynamics of deep linear networks, showing that the training trajectories can be solved in closed form. The gradient flow decomposes along the singular vectors, with each mode converging independently, a remarkable simplification that holds exactly for linear networks and approximately for networks with smooth nonlinearities.

Remark 4.

Orthogonal initialisation produces the theoretically optimal conditioning at the point of initialisation: the condition number of each weight matrix is exactly 1, and the Jacobian of the entire network has singular values concentrated at 1. In practice, this advantage is most pronounced for RNNs, where the recurrent weight matrix is multiplied by itself many times (one per time step), making the exponential compounding of non-unit singular values especially damaging. For feedforward networks, orthogonal initialisation provides moderate improvements over He initialisation, particularly for very deep networks (L>50).

Layer-Sequential Unit-Variance (LSUV)

The methods above derive the initialisation variance from theoretical analysis under simplifying assumptions (linear activations, Gaussian inputs, independence). In practice, nonlinearities, batch normalisation, and complex architectures violate these assumptions. Mishkin and Matas [6] proposed a pragmatic alternative: measure the actual variance empirically and correct it.

Algorithm 1: Layer-Sequential Unit-Variance (LSUV) Initialisation.

[H]

  1. Input: Network with L layers, mini-batch of data , tolerance ε>0, maximum iterations T
  2. Output: Each layer's output has unit variance
  3. for l=1,2,,L
  4. Initialise 𝑾(l) with orthogonal initialisation (Definition 3)
  5. for t=1,2,,T
  6. Forward pass: compute activations 𝒂(l) for the mini-batch through layers 1,,l
  7. Compute v𝖵ar(𝒂(l)) Variance over all elements and batch samples
  8. if |v1|<ε
  9. break
  10. 𝑾(l)𝑾(l)/v Rescale to achieve unit variance

The algorithm proceeds layer by layer (sequentially), so that when layer l is calibrated, layers 1,,l1 have already been fixed to produce unit-variance outputs. The orthogonal initialisation in step 2 provides a good starting point; the iterative rescaling corrects for the effects of nonlinearities and architectural peculiarities. In practice, convergence to |v1|<0.01 typically requires only 2–3 iterations per layer.

Remark 5.

LSUV is architecture-agnostic: it works for CNNs, RNNs, and even exotic architectures that defy closed-form variance analysis. The cost is a single forward pass per layer (per iteration), which is negligible compared to the training budget. The main limitation is that it calibrates only the initial variance; as training progresses, the variance may drift. This is where normalisation layers (Trick #3 - Normalise Everything) take over, maintaining stable statistics throughout training.

Fixup Initialisation

For deep residual networks, standard initialisation causes the variance of residual outputs to grow linearly with depth (each residual branch adds variance). Zhang et al. [7] proposed Fixup initialisation: scale the last layer of each residual branch by L1/(2m2), where L is the total number of residual blocks and m is the number of layers per block. This factor ensures that the sum of L residual contributions has O(1) variance, eliminating the need for batch normalisation entirely. Fixup was demonstrated on ResNets with up to 110 layers, matching the performance of batch-normalised networks without any normalisation layers.

Remark 6.

The Fixup scaling factor L1/(2m2) is derived from the requirement that l=1L𝖵ar(fl(𝒙))=O(1), where fl is the residual function of block l. If each fl is an m-layer sub-network with He-initialised weights, then 𝖵ar(fl)𝑾m(l)2𝑾1(l)2. Scaling the last weight matrix by α reduces this to α2C. Setting Lα2C=O(1) yields α=O(L1/2); the refined exponent 1/(2m2) accounts for the interaction between multiple layers within each block.

Maximal Update Parameterisation (μPmuP)

All the schemes above address a single question: how to start training. Yang and Hu [4] asked a deeper question: how should initialisation, learning rate, and parameterisation co-scale with model width so that the optimal hyperparameters of a small model transfer to a large one?

Standard parameterisation (SP) initialises all layers with the same variance scaling and uses the same learning rate everywhere. Under SP, the optimal learning rate depends on model width: a learning rate that works for a 128-dimensional model is suboptimal for a 1024-dimensional one. This means that hyperparameter tuning must be repeated for every model size, an enormous cost when the target model has billions of parameters.

Definition 4 (Maximal Update Parameterisation (μP)).

Let n be the model width (hidden dimension). Under the maximal update parameterisation (μP), the initialisation scale and learning rate are set per layer type as follows:

1.3

Layer typeInit scale (σ)Learning rate (η)
Input embeddingO(1)ηbase
Hidden (width n)O(1/n)ηbase/n
Output projectionO(1/n)ηbase
The key constraint is that the update Δ𝑾 to each weight matrix should have size Θ(1/n) relative to the weight itself, ensuring that the feature-learning dynamics remain width-independent as n.

The name “maximal update” reflects the fact that μP is the unique parameterisation that (i) ensures stable forward and backward passes and (ii) allows each layer to make the largest possible update without destabilising the network. Under standard parameterisation, hidden-layer updates scale as O(1/n), which shrinks to zero as the model grows, effectively turning large models into “lazy” networks that learn slowly. Under μP, updates remain O(1/n) in the feature space (the space of activations), which is the correct scaling for feature learning.

Proposition 2 (Hyperparameter Transfer under μP).

Under μP, the optimal learning rate, optimal batch size, and optimal training dynamics are width-independent: if η is optimal for a proxy model of width n0, then η is also optimal (up to O(1/n) corrections) for a target model of width nn0.

Proof sketch.

The proof proceeds via the tensor programs framework [4]. The key idea is to track the scaling of every quantity (weights, activations, gradients, updates) as n. Under μP:

  1. The pre-activations 𝒛(l)=𝑾(l)𝒂(l1) have 𝖵ar(zj(l))=O(1) because nσ2𝖵ar(ai)=n(1/n)O(1)=O(1).

  2. The weight update ΔWij(l)=ηl/Wij(l) has size O(1/n) because ηl=O(1/n) and the gradient is O(1).

  3. The resulting change in the pre-activations is Δzj(l)=iΔWij(l)ai(l1)=O(n(1/n)1)=O(1): each layer's output changes by a width-independent amount.

Since all quantities are O(1) in the infinite-width limit, the loss landscape and its optima are width-independent.

Remark 7.

μP allows tuning hyperparameters on a small proxy model (e.g., 10M parameters) and transferring them directly to a large target model (e.g., 10B parameters), saving orders of magnitude in compute. Cerebras demonstrated this by tuning on a 40M-parameter model and training a 6.7B-parameter model with the transferred hyperparameters, achieving results competitive with models tuned directly at scale [4].

Visualising Variance Propagation

fig:tricks:var-propagation illustrates the effect of different initialisation schemes on the variance of activations as a signal propagates through a 10-layer network.

Variance propagation through a 10-layer network under three initialisation schemes. Top: random initialisation with σ2>1/nin causes the variance to grow exponentially, leading to numerical overflow. Middle: Xavier initialisation preserves variance exactly for linear activations. Bottom: He initialisation compensates for the ReLU halving effect (σ symbols denote ReLU activations between layers), maintaining unit variance despite the nonlinearity. Colour encodes variance: green = unit variance, red = exploding variance.

Comparative Summary

Table 1 summarises the initialisation methods discussed in this section.

MethodActivation𝝈2PropertyYear
LeCun [1]tanh1/ninForward-only1998
Xavier [2]Linear / tanh2/(nin+nout)Fwd + Bwd2010
He [3]ReLU2/ninReLU-corrected2015
Orthogonal [5]LinearAll σi=1Dyn. isometry2013
LSUV [6]AnyData-drivenEmpirical 𝖵ar=12016
Fixup [7]ReLU (ResNet)He + L1/(2m2)No norm needed2019
μP [4]AnyWidth-dep.HP transfer2022
Comparison of initialisation methods. “Activation” indicates the activation function for which the method was designed. “Variance” shows the per-element weight variance σ2. “Year” gives the publication year.

Key Idea.

The trick is to start in a dynamically neutral state. Every initialisation method in this section pursues the same goal: ensure that signals neither explode nor vanish as they propagate forward through the network (preserving activation variance) and backward through the network (preserving gradient variance). The methods differ in how they achieve this: Xavier uses the harmonic mean of fan-in and fan-out; He compensates for ReLU halving; orthogonal initialisation enforces unit singular values; LSUV measures and corrects empirically; Fixup accounts for residual accumulation; μP co-scales initialisation with learning rate for width-independent dynamics. But the underlying principle is universal: at initialisation, every layer should act as a near-isometry, transforming its input without changing its scale. A network initialised in this dynamically neutral state is free to learn; a network initialised poorly is dead before training begins.

Trick #2 - Make It Gated

Gates are the switches of deep learning. A gate is nothing more than a learned function that outputs values between 0 and 1, multiplied element-wise with a signal to selectively amplify or suppress each dimension. This deceptively simple mechanism (multiply by a number between zero and one) turns out to be arguably the single most important trick in the entire field. Gates appear in recurrent networks, feedforward layers, attention mechanisms, and highway connections. Every major architecture breakthrough of the past decade has either introduced a new kind of gate or applied an existing gate in a new place.

Historical Note.

From LSTM gates to gated attention: three decades of gating. The idea of gating information flow traces back to Hochreiter and Schmidhuber's Long Short-Term Memory (LSTM) [8] in 1997, which introduced input, forget, and output gates to control information flow through a recurrent cell. For nearly two decades, the LSTM gate remained the canonical example. Then the pace accelerated: Cho et al. [9] simplified the LSTM into the Gated Recurrent Unit (GRU, 2014) with two gates instead of three. Srivastava et al. [10] introduced Highway Networks (2015), applying gates to feedforward skip connections. Dauphin et al. [11] proposed the Gated Linear Unit (GLU, 2017), gating feedforward layers without recurrence. Shazeer [12] revisited GLU with modern activations (SwiGLU, 2020), creating the feedforward layer now standard in every major LLM. Most recently, Qiu et al. [13] showed that adding a single sigmoid gate to attention heads eliminates attention sinks and dramatically improves long-context performance (Gated Attention, 2025, NeurIPS Best Paper). The trajectory is clear: wherever there is a bottleneck in expressiveness or information flow, adding a gate resolves it.

We met gates in the LSTM (Definition 11), where input, forget, and output gates control information flow through the recurrent cell. Here we formalise the general gating mechanism and trace its evolution through the architectures that define modern deep learning.

The General Gating Mechanism

At its core, every gate has the same structure: project the input, apply a sigmoid, and multiply element-wise.

Definition 5 (General Gating Mechanism).

Given an input 𝒙d, a gating mechanism produces (GATE)𝒙out=𝒙σ(𝑾g𝒙+𝒃g), where 𝑾gd×d and 𝒃gd are learnable parameters, σ() is the logistic sigmoid, and denotes element-wise (Hadamard) multiplication. The gate 𝒈=σ(𝑾g𝒙+𝒃g)[0,1]d acts as a learnable soft switch: each dimension k is independently amplified (when gk1) or suppressed (when gk0).

The gate's power comes from its data dependence: the same network dimension may be opened wide for one input and shut for another. This is fundamentally different from a fixed mask or a global scaling factor. The sigmoid activation is the natural choice because its range [0,1] makes it interpretable as a “proportion of signal to let through.”

Remark 8.

Why does gating help gradient flow? Consider the gradient of 𝒙out with respect to 𝒙. By the product rule, (GATE GRAD)𝒙out𝒙=diag(𝒈)+diag(𝒙)diag(𝒈(1𝒈))𝑾g. The first term diag(𝒈) provides a direct path for gradients, analogous to the residual connection's identity shortcut. When 𝒈1, gradients flow through unchanged. When 𝒈0, the dimension is suppressed but the second term still provides a learning signal to open the gate.

Highway Networks

Before ResNets, before skip connections became ubiquitous, Srivastava et al. [10] proposed the first architecture to successfully train networks with dozens of layers by using gates to control the information highway.

Definition 6 (Highway Layer).

A highway layer computes (Highway)𝒚=𝑻(𝒙)𝑯(𝒙)+(1𝑻(𝒙))𝒙, where 𝑻(𝒙)=σ(𝑾T𝒙+𝒃T) is the transform gate, 𝑯(𝒙)=ReLU(𝑾H𝒙+𝒃H) is a nonlinear transformation, and (1𝑻(𝒙)) is sometimes called the carry gate.

Remark 9.

Highway networks preceded ResNets [14] by several months. The connection is revealing: when 𝑻(𝒙)1 everywhere, 𝒚𝑯(𝒙) (pure transform); when 𝑻(𝒙)0, 𝒚𝒙 (pure carry, i.e., identity skip). A ResNet is a special case where 𝑻=1 everywhere: 𝒚=𝑯(𝒙)+𝒙. The highway network is strictly more expressive because the gate can learn how much to transform versus carry at each layer and each dimension. In practice, however, ResNets' simpler structure proved easier to train at scale, and the extra expressiveness of the highway gate was not needed when combined with batch normalisation.

Gated Recurrent Unit

Cho et al. [9] proposed the GRU as a simpler alternative to the LSTM, reducing three gates to two while retaining comparable modelling power.

Definition 7 (Gated Recurrent Unit).

The Gated Recurrent Unit (GRU) updates its hidden state as follows: (GRU Update)𝒛t=σ(𝑾z[𝒉t1,𝒙t]),(update gate)𝒓t=σ(𝑾r[𝒉t1,𝒙t]),(reset gate)𝒉~t=tanh(𝑾[𝒓t𝒉t1,𝒙t]),(candidate)𝒉t=(1𝒛t)𝒉t1+𝒛t𝒉~t,(output) where [,] denotes concatenation, σ is the sigmoid function, and is element-wise multiplication.

The update gate 𝒛t plays the role of both the LSTM's input gate and forget gate: when 𝒛t0, the hidden state is carried unchanged from the previous step (𝒉t𝒉t1); when 𝒛t1, the hidden state is replaced by the candidate 𝒉~t. The reset gate 𝒓t controls how much of the previous hidden state to expose when computing the candidate: when 𝒓t0, the candidate depends only on the current input, effectively “resetting” the memory.

Remark 10.

Two gates versus three: the GRU has approximately 25% fewer parameters than the LSTM for the same hidden dimension, because it eliminates the output gate entirely (the full hidden state is always exposed). Empirically, neither architecture consistently dominates the other [9]. The GRU tends to perform comparably on tasks with moderate-length dependencies and trains faster due to its reduced parameter count. The LSTM retains an advantage on tasks requiring fine-grained control over what to expose versus what to remember, thanks to its separate output gate.

Gated Linear Units and the SwiGLU Family

Dauphin et al. [11] introduced the Gated Linear Unit for language modelling, demonstrating that gating could accelerate convergence even in non-recurrent architectures. The idea is beautifully simple: split the feedforward computation into two parallel paths, one of which passes through a gate.

Definition 8 (Gated Linear Unit).

The Gated Linear Unit (GLU) is defined as (GLU)GLU(𝒙)=(𝒙𝑾1+𝒃1)σ(𝒙𝑾2+𝒃2), where 𝑾1,𝑾2d×d and 𝒃1,𝒃2d are learnable parameters, σ is the sigmoid function, and denotes element-wise multiplication. The left factor 𝒙𝑾1+𝒃1 is the value path; the right factor σ(𝒙𝑾2+𝒃2) is the gate path.

The key insight is that the gate operates on a linear projection of the input: there is no nonlinearity applied to the value path before gating. This “linear” qualifier is what gives the GLU its name and its gradient-friendly properties: the value path preserves a direct linear pathway for gradients.

Shazeer [12] systematically explored replacing the sigmoid gate with other activation functions, discovering that SiLU-gated variants (SwiGLU) consistently outperformed alternatives. Table 2 summarises the family.

VariantGate activation fIntroduced byUsed in
GLUSigmoid σ(x)Dauphin et al. [11]Original paper
ReGLUReLU max(0,x)Shazeer [12]-
GEGLUGELU xΦ(x)Shazeer [12]GPT-J, GPT-NeoX
SwiGLUSiLU xσ(x)Shazeer [12]LLaMA, Qwen, DeepSeek
Variants of the Gated Linear Unit. The gate activation replaces σ in (𝒙𝑾1)f(𝒙𝑾2); biases are omitted for clarity. SwiGLU is the dominant choice in modern LLMs.

SwiGLU (Definition 20) is now the standard feedforward layer in all major open-weight LLMs, including LLaMA, Mistral, Qwen, and DeepSeek. The SwiGLU FFN ((Swiglu)) replaces the traditional two-layer FFN with a three-matrix computation that includes a gated branch, typically using a hidden dimension of 83d (rounded to the nearest multiple of 256) to keep the parameter count comparable to the ungated alternative.

Remark 11.

The gated FFN has three weight matrices (𝑾1, 𝑾2, 𝑾3) instead of two, so the parameter count per layer increases unless the hidden dimension is reduced. The standard practice is to set the hidden dimension to 83dmodel rather than 4dmodel: (3×83d×d)=8d2, exactly matching the 2×(4d×d)=8d2 parameters of the ungated FFN.

Gated Attention: A Deep Dive

Definition 18 defined gated attention; we now examine why it works. Qiu et al. [13] showed that adding a single sigmoid gate to each attention head resolves a fundamental expressiveness bottleneck in multi-head attention and eliminates the infamous “attention sink” phenomenon.

The low-rank bottleneck.

In standard multi-head attention, each head k computes (MHA HEAD)𝒐i(k)=(jSij(k)𝒙j𝑾V(k))𝑾O(k), where Sij(k) is the softmax-normalised attention weight from token i to token j, 𝑾V(k)d×dk is the value projection, and 𝑾O(k)dk×d is the output projection. The effective per-head transformation of the value is 𝑾V(k)𝑾O(k)d×d, but this matrix has rank at most dk=d/h, where h is the number of heads. For a model with d=4096 and h=32, each head projects through a rank-128 bottleneck. This limits the expressiveness of each individual head.

Five gating positions.

Qiu et al. [13] systematically evaluated five positions for inserting a gate into the attention computation:

  1. G1: Gate after SDPA output. 𝒀=𝒀σ(𝑿𝑾θ), where 𝒀 is the output of scaled dot-product attention. The gate operates on the full d-dimensional output, breaking the per-head low-rank constraint.

  2. G2: Gate value projection. 𝑽=𝑽σ(𝑿𝑾θ), applied before the attention weighted sum.

  3. G3: Gate key projection. 𝑲=𝑲σ(𝑿𝑾θ), modulating key representations.

  4. G4: Gate query projection. 𝑸=𝑸σ(𝑿𝑾θ), modulating query representations.

  5. G5: Gate output projection. 𝒐=𝒐σ(𝑿𝑾θ), applied after the final linear projection.

Of these, G1 performed best, consistently improving perplexity, long-context recall, and training stability. The reason is geometric: G1 is the only position where the gate operates on the full-rank attention output, allowing it to break the per-head rank bottleneck. Gates at positions G2–G5 operate within the low-rank subspace of individual heads and therefore cannot resolve the fundamental expressiveness limitation.

Proposition 3 (Expressiveness of Gated Attention).

In standard multi-head attention with softmax, the output for token i in head k lies in the convex hull of the value vectors: (Convex HULL)𝒐i=j=1nSij𝒗jconv(𝒗1,,𝒗n), since Sij0 and jSij=1 by the softmax normalisation. In gated attention (G1), the output becomes (Gated Output)𝒐igated=𝒈i𝒐i,𝒈i=σ(𝒙i𝑾θ)[0,1]d, which can produce outputs outside conv(𝒗1,,𝒗n).

Proof.

In standard attention, the softmax constraints Sij0 and jSij=1 ensure that 𝒐i is a convex combination of the value vectors, and therefore 𝒐iconv(𝒗1,,𝒗n).

For gated attention, let gi,k<1 for some dimension k. Then oi,kgated=gi,koi,k<oi,k. If oi,k=minjvj,k (i.e., the convex combination attains the minimum value in dimension k), then scaling by gi,k<1 produces oi,kgated<minjvj,k, which is strictly below the convex hull in dimension k. More generally, since conv(𝒗1,,𝒗n) is a convex set containing 𝒐i, scaling individual dimensions toward zero can exit the hull whenever the origin is not itself in the hull.

The attention sink problem.

The softmax normalisation forces jSij=1: the model must attend somewhere, distributing its full attention budget across the available tokens, even when no token is genuinely relevant to the current query. In practice, this forces the model to concentrate excess attention mass on a convenient “dump” token (typically the first token or the beginning-of-sequence token), creating what Xiao et al. [58] termed an attention sink.

Attention sinks are problematic for three reasons:

  1. Wasted capacity: the first token's value vector is mixed into every output, injecting irrelevant information.

  2. KV cache dependency: the first token's key and value must be retained forever, complicating sliding-window and streaming inference.

  3. Long-context degradation: as the context grows, the sink absorbs an increasingly large fraction of the attention mass, diluting the signal from genuinely relevant tokens.

The gate provides an elegant resolution. When no token is relevant, the gate can simply output 𝒈i0, producing a near-zero output without needing to “waste” attention mass on a sink token. The model no longer needs a dump token because it has an alternative mechanism for expressing “nothing here is relevant.”

Remark 12.

At 15B MoE scale (400B training tokens), Qiu et al. [13] measured that gated attention reduced the fraction of attention concentrated on the first token from 46.7% to 4.8%, a near-complete elimination of the attention sink phenomenon.

Empirical results.

The gains from gated attention are substantial and consistent across scales:

  • Perplexity: at 15B MoE / 400B tokens, PPL decreased from 6.026 to 5.761 (0.265).

  • Long-context recall: on the RULER 128k benchmark, accuracy jumped from 31.65 to 58.82 (+27.17 points).

  • Training stability: gated attention enabled larger learning rates without training divergence, effectively expanding the feasible hyperparameter space.

  • Overhead: the single sigmoid gate adds fewer than 2% to wall-clock training time.

Insight.

A single sigmoid gate per attention head, costing fewer than 2% of compute, eliminated attention sinks and improved 128k context recall by 27 points. The gate does not change the attention pattern; it changes what the model does with the attention output. By providing a “volume knob” on each dimension, the gate lets the model express “I attended to these tokens but their information is not useful” without corrupting the output with sink-token noise. This is a recurring theme: the most impactful tricks are often the simplest, adding a single nonlinear operation at exactly the right bottleneck.

Four gating architectures compared. (a) LSTM: three gates (forget f, input i, output o) control flow around the cell state 𝒄t. (b) Highway: a single transform gate 𝑻 splits the signal between a nonlinear path 𝑯(𝒙) and an identity carry path. (c) GLU: the input is projected twice; one path passes through a sigmoid gate and is multiplied element-wise with the other. (d) Gated Attention (G1): the SDPA output is gated by a sigmoid applied to a learned projection of the input. In all panels, amber boxes denote gate operations and blue boxes denote data paths.

Trick #3 - Normalise Everything

Deep networks are prone to a fundamental instability: as activations propagate through dozens or hundreds of layers, their magnitudes can drift, growing without bound or collapsing to zero. Even when residual connections (Trick #4 - Add Skip Connections Everywhere) prevent gradient death, the activations themselves may still drift to extreme scales, making optimisation difficult. Normalisation layers solve this by enforcing consistent activation statistics at every point in the network.

BatchNorm (Definition 5), LayerNorm (Definition 6), and RMSNorm (Definition 19) were defined in earlier chapters. Here we explore why normalisation works (the answer is more subtle than originally claimed), survey the full family of normalisation methods, and examine the critical question of where to normalise within a Transformer block.

The Covariate Shift Debate

Historical Note.

The covariate shift hypothesis and the great debate. Ioffe and Szegedy [15] introduced BatchNorm in 2015 with a compelling narrative: training is difficult because the distribution of each layer's inputs changes as the parameters of the preceding layers are updated, a phenomenon they called internal covariate shift. By normalising each layer's inputs to zero mean and unit variance, BatchNorm would stabilise these distributions and accelerate training. The paper was enormously influential: BatchNorm was adopted universally and became a cornerstone of deep learning practice.

Three years later, Santurkar et al. [16] challenged this narrative head-on. Their experiments showed that BatchNorm does not reduce internal covariate shift; in fact, networks with BatchNorm sometimes exhibit more covariate shift than those without it. What BatchNorm actually does, they demonstrated, is something far more fundamental: it makes the loss landscape smoother.

Remark 13 (What Does Batch Normalisation Actually Do?).

Santurkar et al. [16] proved that BatchNorm makes the loss function more Lipschitz-continuous: the gradient varies more smoothly as a function of the parameters. Formally, for a loss and parameters 𝜽, (Lipschitz)(𝜽1)(𝜽2)L𝜽1𝜽2 for a smaller Lipschitz constant L when BatchNorm is used. This smoothness has a direct practical consequence: a smoother landscape means that the gradient at the current point is a more reliable predictor of what the gradient will be after a step, which in turn means that larger learning rates can be used without the optimiser overshooting and diverging. This, not the reduction of covariate shift, is why BatchNorm enables faster training.

Group Normalisation

BatchNorm's Achilles' heel is its dependence on the batch dimension: the mean and variance are computed across all samples in a mini-batch. When the batch size is small, as in detection and segmentation tasks where high-resolution images consume most of GPU memory, the batch statistics become noisy, and performance degrades sharply. Wu and He [59] proposed Group Normalisation (GN) to eliminate this dependency.

Definition 9 (Group Normalisation).

Given a feature tensor 𝒙N×C×H×W (batch, channels, height, width), divide the C channels into G groups of size C/G. For each sample n and group g, define the set of indices 𝒮g={(c,h,w):c[(g1)CG,gCG),h[H],w[W]}. Group Normalisation computes (Groupnorm Stats)μg=1|𝒮g|(c,h,w)𝒮gxn,c,h,w,σg2=1|𝒮g|(c,h,w)𝒮g(xn,c,h,wμg)2, and normalises each element as (Groupnorm NORM)y^n,c,h,w=xn,c,h,wμgσg2+ϵ,(c,h,w)𝒮g, followed by learnable affine parameters yn,c,h,w=γcy^n,c,h,w+βc.

Remark 14.

Group Normalisation is a unifying framework. Setting G=1 (a single group containing all channels) recovers Layer Normalisation: the statistics are computed over all channels and spatial dimensions for each sample independently. Setting G=C (each channel is its own group) recovers Instance Normalisation: each channel of each sample is normalised independently. GroupNorm interpolates between these extremes, and G=32 is the recommended default for convolutional networks.

Instance Normalisation

Ulyanov et al. [60] introduced Instance Normalisation for neural style transfer, where removing instance-specific contrast information proved essential for transferring artistic styles.

Definition 10 (Instance Normalisation).

Instance Normalisation normalises each channel of each sample independently. For sample n and channel c, (Instancenorm)x^n,c,h,w=xn,c,h,wμn,cσn,c2+ϵ, where μn,c and σn,c2 are the mean and variance computed over the spatial dimensions (H,W) only: μn,c=1HWh,wxn,c,h,w.

Remark 15.

Why does Instance Normalisation help style transfer? Each channel in a convolutional feature map captures a particular visual pattern (edges, textures, colours). The mean of a channel captures the overall “amount” of that pattern in the image, a style-dependent quantity. The variance captures the contrast. By subtracting the mean and dividing by the standard deviation, Instance Normalisation strips away the original image's style-specific statistics, making the features more amenable to being recombined with a different style.

Comparison of Normalisation Methods

MethodNormalise overBatch-indep.?Primary use case
BatchNorm(N,H,W) per channelNoVision (training)
LayerNorm(C,H,W) per sampleYesTransformers
GroupNorm(C/G,H,W) per groupYesVision (small batch)
InstanceNorm(H,W) per channel per sampleYesStyle transfer
RMSNorm(C) per sample (no mean)YesLLMs
Comparison of normalisation methods. “Normalise over” indicates the axes across which the mean and variance are computed. “Batch-independent” methods do not require multiple samples, making them suitable for small batches and inference.

The trend in the field is clear: modern architectures have moved away from batch-dependent normalisation. Transformers use LayerNorm or RMSNorm exclusively, because batch-level statistics are incompatible with autoregressive generation (batch size 1 at inference) and variable-length sequences. RMSNorm ((Rmsnorm)) has emerged as the preferred choice for large language models because it omits the mean subtraction step, saving approximately 10–15% of the normalisation cost while performing comparably [61].

QK-Norm: Normalising Attention Logits

As model dimension dmodel grows, the attention logits 𝑸𝑲 can grow unboundedly in magnitude, even with the 1/dk scaling. Henry et al. [62] proposed a simple fix: normalise the queries and keys before computing attention.

Definition 11 (QK Normalisation).

QK Normalisation applies LayerNorm to the query and key projections before computing the attention scores: (Qknorm)𝑸^=LayerNorm(𝑸),𝑲^=LayerNorm(𝑲), so that the attention computation becomes (Qknorm ATTN)Attention(𝑸,𝑲,𝑽)=softmax(𝑸^𝑲^dk)𝑽. After LayerNorm, each row of 𝑸^ and 𝑲^ has approximately zero mean and unit variance, which bounds the dot product magnitudes and prevents attention logit explosion.

Remark 16.

Without QK-Norm, the dot product 𝒒i𝒌j scales as O(dk) in the worst case (when the vectors are aligned). After normalisation, each vector has norm dk, and by Cauchy–Schwarz, |𝒒^i𝒌^j|dk, but in practice the magnitudes are O(dk) due to the approximate orthogonality of random high-dimensional vectors. The combination of QK-Norm and the 1/dk scaling factor ensures that the attention logits remain O(1) regardless of model dimension, eliminating a common source of training instability at large scale.

DeepNorm: Scaling Normalisation to 1000 Layers

Standard Post-LN Transformers struggle to train beyond approximately 100 layers due to gradient instability. Wang et al. [17] introduced DeepNorm, a modified normalisation scheme that enables stable training of Transformers with up to 1000 layers.

Definition 12 (DeepNorm).

Let N denote the total number of sub-layers (each attention or FFN sub-layer counts as one). DeepNorm modifies the residual connection as (Deepnorm)𝒙l+1=LN(α𝒙l+F(𝒙l)), where α=(2N)1/4 is a depth-dependent residual scaling factor, F denotes the sub-layer function (attention or FFN), and F is initialised with Xavier initialisation scaled by β=(8N)1/4.

The choice of α and β is not arbitrary; it emerges from an analysis of the expected output magnitude across layers.

Proposition 4 (DeepNorm Stability).

Under DeepNorm initialisation with α=(2N)1/4 and β=(8N)1/4, the expected output magnitude remains O(1) regardless of depth N.

Proof sketch.

Consider the unnormalised residual 𝒖l+1=α𝒙l+F(𝒙l) at layer l+1. At initialisation, the sub-layer output F(𝒙l) has variance proportional to β2=(8N)1/2. After N layers (without the LayerNorm renormalisation), the accumulated contribution from the sub-layers has variance (Deepnorm VAR)𝖵ar[l=1NFl]Nβ2=N(8N)1/2=N1/28=O(N1/2). The residual path contributes a scaling factor of αN, but the LayerNorm at each step renormalises the hidden state to have unit variance. The perturbation from each sub-layer Fl relative to the normalised residual scales as β/α=(8N)1/4/(2N)1/4=1/(2N), so the relative perturbation per layer is O(N1/2). Summing over N layers, the total relative perturbation is O(N1/2)O(N1/2)=O(1), ensuring bounded variance throughout the network.

Remark 17.

Using DeepNorm, Wang et al. [17] trained a 1000-layer Transformer that outperformed a standard 200-layer Post-LN Transformer on machine translation, demonstrating that depth alone, when properly stabilised, can improve model quality.

Pre-Norm vs Post-Norm

The question of where to place normalisation within a Transformer block has been debated since the architecture's inception. The two dominant approaches, and a more recent hybrid, differ in a single design choice that has profound consequences for training dynamics.

Post-norm (original Transformer).

The original Transformer [24] placed LayerNorm after the residual addition: (Postnorm)𝒙l+1=LN(𝒙l+F(𝒙l)). This was noted in Algorithm 2.

Pre-norm (modern standard).

Most modern Transformers place LayerNorm before the sub-layer: (Prenorm)𝒙l+1=𝒙l+F(LN(𝒙l)).

Why pre-norm converges faster.

Xiong et al. [63] analysed the gradient flow in both architectures at initialisation and found a crucial difference. In the post-norm configuration, the gradient of the loss with respect to layer l must pass through the LayerNorm Jacobian at every subsequent layer. The LayerNorm Jacobian is a projection matrix that subtracts the mean and rescales; this introduces a contraction at each step, causing gradients to shrink as they propagate backward.

In the pre-norm configuration, the residual path 𝒙l+1=𝒙l+F(LN(𝒙l)) provides an unobstructed identity path for gradients. By the chain rule, (Prenorm GRAD)𝒙L𝒙l=𝑰+k=lL1Fk(LN(𝒙k))𝒙k, where the identity matrix 𝑰 ensures that the gradient magnitude is at least 1 regardless of depth, analogous to the residual connection's role in gradient preservation.

The quality trade-off.

Despite pre-norm's training advantages, post-norm often achieves better final quality when training succeeds. The reason is subtle: the LayerNorm Jacobian in the post-norm path acts as a form of adaptive regularisation, preventing any single sub-layer from dominating the residual stream. This regularisation effect is lost in pre-norm, where the residual stream is unconstrained and can grow unboundedly, a phenomenon that necessitates the use of a final LayerNorm after the last layer.

Caution.

Changing normalisation order without adjusting the learning rate and other hyperparameters can cause training to diverge entirely. Pre-norm and post-norm architectures have fundamentally different gradient scales at initialisation. A learning rate that is optimal for pre-norm is typically too large for post-norm (causing divergence) or too small for post-norm-to-pre-norm switches (causing slow convergence). When switching normalisation order, always re-tune the learning rate from scratch.

Three normalisation placement strategies in a Transformer block. (a) Post-norm (original Transformer): LayerNorm is applied after the residual addition. Gradients must pass through the LN Jacobian at every layer. (b) Pre-norm (modern standard): LayerNorm is applied before the sub-layer. The residual path provides an unobstructed identity shortcut for gradients. (c) Sandwich-LN: an additional LayerNorm after each sub-layer (before the residual add) constrains the sub-layer output magnitude, combining pre-norm's fast convergence with post-norm's quality. Dashed lines indicate the residual skip connections.
Sandwich normalisation.

A natural question arises: can we get the best of both worlds? The Sandwich-LN configuration adds a second LayerNorm after each sub-layer (but before the residual addition): (Sandwich)𝒙l+1=𝒙l+LNpost(F(LNpre(𝒙l))). The inner LN (pre-norm) ensures stable input to the sub-layer; the outer LN (post-norm) constrains the sub-layer's output magnitude before it enters the residual stream. This prevents the unbounded growth of the residual stream that plagues pre-norm architectures at very large depth. The cost is two additional normalisation operations per block, a negligible overhead at the scale of modern Transformers.

Remark 18.

The practical consensus as of 2025: use Pre-RMSNorm for most LLM applications (fast convergence, simple implementation), QK-Norm when training at large dmodel or with FP8 (prevents attention logit explosion), and consider DeepNorm or Sandwich-LN only when pushing to extreme depths (>100 layers). The original post-norm configuration is rarely used in new architectures.

Trick #4 - Add Skip Connections Everywhere

The basic residual block 𝒚=𝒙+F(𝒙) was defined in Definition 9, and the forward pass equation was given in (Residual). In this section we trace the evolution of skip connections from Kaiming He's original insight to the sophisticated multi-stream architectures used in today's largest language models, and explain why the simple act of adding the input back to the output has such a profound effect on trainability.

Historical Note.

He's 152-layer revolution (2015). Before ResNet, networks deeper than roughly 20 layers were essentially untrainable. The problem was not overfitting; deeper networks produced higher training error than their shallower counterparts, a phenomenon He et al. [18] termed the degradation problem. At ILSVRC 2015, He's 152-layer ResNet won every track by a landslide: 3.57% top-5 error on ImageNet (the first superhuman result), first place in detection, first place in localisation. The margin of victory stunned the community. A 56-layer plain network had higher error than a 20-layer one; a 152-layer ResNet dramatically outperformed both.

The key insight was deceptively simple: make it easy for the network to learn the identity function. If the optimal transformation at a given layer is close to the identity, a plain network must learn weights that produce F(𝒙)𝒙, a nontrivial optimisation target. A residual network need only learn F(𝒙)0, which is trivially achieved by driving the weights to zero.

Highway networks (Definition 6) preceded ResNets by several months [10], introducing a gating mechanism (Trick #2 - Make It Gated) to control the flow of information along skip paths. But the simplicity of ResNet's ungated additive shortcut proved more influential: no learnable gating parameters, no additional hyperparameters, just 𝒚=𝒙+F(𝒙). This simplicity enabled scaling to depths that were previously unthinkable.

The Unraveled View of Residual Networks

Veit et al. [64] and Greff et al. [14] offered an elegant reinterpretation: a ResNet is not a single deep computation, but an exponential ensemble of shallow paths.

Proposition 5 (Unraveled View of ResNets).

A residual network of depth L can be decomposed into 2L implicit paths of varying lengths. Specifically, the output of the network is (Unraveled)𝒚=(Id+FL)(Id+F1)(𝒙)=S{1,,L}(lSFl)(𝒙), where each subset S defines a path through precisely the layers in S, and the product is taken in increasing order of indices.

Proof.

Expand the composition directly. For L=2: (Id+F2)(Id+F1)(𝒙)=𝒙+F1(𝒙)+F2(𝒙)+F2(F1(𝒙)), which has 22=4 terms corresponding to the four subsets of {1,2}: (the identity path 𝒙), {1}, {2}, and {1,2}. The general case follows by induction: each additional layer (Id+Fl+1) doubles the number of paths by either including or excluding Fl+1.

The critical empirical finding is that most gradient in practice flows through short paths of length 3–5 layers, not through the full-depth path. This explains why ResNets behave more like ensembles of moderately deep networks than like a single very deep one.

Remark 19.

Removing a single layer from a trained ResNet causes only mild accuracy degradation, consistent with the iterative refinement interpretation, where each layer makes a small correction to the running representation, rather than the hierarchical abstraction view where each layer builds qualitatively new features. This robustness stands in stark contrast to plain networks, where removing any layer causes catastrophic failure.

Pre-activation Residual Blocks

He et al. [65] identified a subtle but consequential design flaw in the original ResNet: the ReLU after the addition corrupts the identity shortcut.

Definition 13 (Pre-activation Residual Block).

The pre-activation residual block applies normalisation and activation before the weight layers: (Preact)𝒚=𝒙+F(BN(ReLU(𝒙))), where F denotes the weight layers (convolutions or linear maps). This contrasts with the post-activation design of the original ResNet: (Postact)𝒚=ReLU(𝒙+F(𝒙)). The key difference: in (Preact), the skip path carries a pure identity: no nonlinearity on the shortcut.

Why does this matter? The answer lies in the gradient flow.

Proposition 6 (Unimpeded Gradient Flow).

In a pre-activation ResNet with L blocks, the gradient of the loss with respect to the activations at layer l is (Preact GRAD)𝒙l=𝒙Lk=lL1(𝑰+Fk𝒙k). The identity term 𝑰 ensures that gradient flows directly from the loss to any layer without multiplicative decay.

Proof.

Since 𝒙k+1=𝒙k+Fk(𝒙k), the Jacobian of each block is 𝒙k+1/𝒙k=𝑰+Fk/𝒙k. Applying the chain rule from layer L to layer l: 𝒙l=𝒙Lk=lL1(𝑰+Fk𝒙k). Expanding this product yields a sum of 2Ll terms, each containing at least one copy of /𝒙L (the direct gradient path). Even if all Jacobians Fk/𝒙k are small, the identity term guarantees a non-vanishing gradient signal.

Remark 20.

In the post-activation design ((Postact)), the ReLU after the addition clips negative values on the skip path, introducing a multiplicative factor diag(1[𝒙+F(𝒙)>0]) that can zero out gradient components. Pre-activation removes this obstruction entirely.

DenseNet: Concatenation Instead of Addition

Huang et al. [66] pushed skip connections to their logical extreme: connect every layer to every preceding layer.

Definition 14 (Dense Block).

In a dense block, the l-th layer receives the concatenation of all preceding feature maps as input: (Densenet)𝒙l=Hl([𝒙0,𝒙1,,𝒙l1]), where [] denotes channel-wise concatenation and Hl is a composite function (typically BN–ReLU–Conv). Each layer Hl produces k new feature maps, where k is called the growth rate. After l layers within a dense block, the total number of channels is k0+lk, where k0 is the number of input channels.

The crucial difference from ResNet is concatenation instead of addition. Addition merges information destructively: two feature maps are collapsed into one. Concatenation preserves all information, allowing later layers to directly access the raw features from any earlier layer. This direct access path encourages feature reuse: later layers can build on features computed at any earlier stage without recomputing them.

Remark 21.

DenseNet achieves comparable accuracy to ResNet with significantly fewer parameters, precisely because of feature reuse. A DenseNet-BC with 0.8M parameters matches the accuracy of a ResNet with 10M parameters on CIFAR-10. The tradeoff is memory: storing all intermediate feature maps for concatenation requires substantially more activation memory during training.

ReZero: Initialise as the Identity

Bachlechner et al. [67] proposed the simplest possible modification to residual connections: multiply the residual branch by a learnable scalar initialised to zero.

Definition 15 (ReZero).

The ReZero connection replaces the standard residual update with (Rezero)𝒙l+1=𝒙l+αlFl(𝒙l), where αl is a learnable scalar initialised to αl=0 for all layers l.

At initialisation, αl=0 for every layer, so the entire network computes the identity function: 𝒙l+1=𝒙l for all l. The signal propagates through the network without distortion, and the gradients flow back without attenuation. As training progresses, the scalars αl gradually grow from zero, allowing the network to learn increasingly nontrivial transformations.

Remark 22.

ReZero eliminates the need for learning rate warmup. With standard initialisation, the residual branches produce outputs of magnitude Θ(1), and these accumulate across L layers, creating an Θ(L) signal at the output. Warmup is needed to prevent this accumulated signal from causing instability. ReZero sidesteps the problem entirely: the network starts as the identity and deviates smoothly.

Hyper-Connections: Multi-Stream Residuals

Standard residual connections maintain a single residual stream of dimension d. Zhu et al. [68] proposed hyper-connections, which expand the residual stream to n parallel copies and mix them through learnable matrices.

Definition 16 (Hyper-Connection).

A hyper-connection expands the residual stream from d to nd dimensions. The update at layer l is (Hyperconn)𝒙l+1=𝑯lres𝒙l+(𝑯lpost)Fl(𝑯lpre𝒙l), where:

  1. 𝑯lresn×n mixes the n expanded streams (applied block-diagonally to nd);

  2. 𝑯lpre1×n aggregates n streams into a single d-dimensional layer input;

  3. 𝑯lpost1×n distributes the d-dimensional layer output back to the n streams.

The additional expressiveness comes at a cost: the matrices 𝑯lres are unconstrained. When composed across L layers, their product l=1L𝑯lres can have spectral norm far exceeding 1. Zhu et al. measured the Amax Gain, the maximum amplification factor of the residual stream, and found values approaching 3000 in a 27B-parameter Mixture-of-Experts model. Such amplification causes severe training instability: loss spikes, divergent gradients, and wasted compute.

Manifold-Constrained Hyper-Connections

Xie et al. [69] proposed a principled solution: constrain the mixing matrices to the Birkhoff polytope, the set of doubly stochastic matrices.

Definition 17 (Manifold-Constrained Hyper-Connection (mHC)).

A manifold-constrained hyper-connection restricts each 𝑯lres in (Hyperconn) to the Birkhoff polytope n: (Birkhoff)n={𝑴n×n:𝑴1=1,1𝑴=1,𝑴0}. Each 𝑯lresn is a doubly stochastic matrix: its rows and columns each sum to 1, and all entries are non-negative.

Doubly stochastic matrices appeared in our treatment of optimal transport (Theorem 2), where the Sinkhorn factorisation theorem establishes that any matrix with positive entries can be scaled to a doubly stochastic matrix by alternating row and column normalisation. Here, the same structure provides stability guarantees for deep residual networks.

Proposition 7 (mHC Stability).

If each 𝑯lresn, then:

  1. 𝑯lres21 (spectral norm bounded);

  2. l=1L𝑯lresn (closure under multiplication);

  3. 𝑰n (subsumes standard residual connections).

Proof.

(a) By the Birkhoff–von Neumann theorem, n=conv(𝒫n), where 𝒫n is the set of n×n permutation matrices. Permutation matrices are orthogonal, so 𝑷2=1 for all 𝑷𝒫n. For 𝑴=iλi𝑷i with λi0 and iλi=1: 𝑴2iλi𝑷i2=iλi=1.

(b) Let 𝑨,𝑩n. Then (𝑨𝑩)1=𝑨(𝑩1)=𝑨1=1, and 1(𝑨𝑩)=(1𝑨)𝑩=1𝑩=1. Since 𝑨,𝑩0, we also have 𝑨𝑩0. Hence 𝑨𝑩n.

(c) 𝑰1=1, 1𝑰=1, and 𝑰0, so 𝑰n.

Property (b) is the crucial one: no matter how many layers we stack, the composed mixing matrix remains doubly stochastic with spectral norm at most 1. This eliminates the exponential amplification that plagued unconstrained hyper-connections.

Sinkhorn–Knopp projection.

In practice, the raw parameters 𝑯~lres are unconstrained. To project onto n, we apply the Sinkhorn–Knopp algorithm (Algorithm 1): (MHC Sinkhorn)𝑴(0)=exp(𝑯~lres),𝑴(t)=𝒯r(𝒯c(𝑴(t1))),t=1,,T, where 𝒯r divides each row by its sum and 𝒯c divides each column by its sum. The exponential ensures positivity; alternating normalisation converges to a doubly stochastic matrix. In practice, T=5 iterations suffice for n8.

Insight.

The Birkhoff constraint bounds Amax Gain from 3000 (unconstrained) to 1.6 (mHC), while retaining the expressiveness of multi-stream residual connections. The constraint does not eliminate the ability to route information differentially across streams; it merely prevents any stream from being amplified without bound. This is a recurring theme in deep learning: constraints that prevent pathological behaviour often improve both stability and final performance.

Remark 23.

DeepSeek adopted mHC in their latest models, with measurable training stability improvements at 200B+ scale. The overhead of Sinkhorn projection is negligible: for n=4 streams, each projection involves a 4×4 matrix, a cost dwarfed by the attention and feed-forward computations.

Evolution of skip connection architectures. (a) ResNet: additive skip with 𝒚=𝒙+F(𝒙). (b) DenseNet: concatenation preserves all features. (c) ReZero: learnable scalar α (init. 0) gates the residual. (d) Hyper-Connection (HC): multi-stream residual with unconstrained mixing matrix 𝑯res. (e) mHC: same as HC, but 𝑯res is constrained to the Birkhoff polytope n, bounding spectral norm to 1.
The Birkhoff polytope 2 in the 2×2 case. Every 2×2 doubly stochastic matrix has the form (a1a1aa) for a[0,1], forming a line segment from the identity matrix (a=1) to the swap permutation (a=0). The midpoint (a=1/2) represents uniform mixing of the two residual streams. In higher dimensions, n is a convex polytope with n! vertices (the permutation matrices).

Trick #5 - Choose Your Activation Wisely

Standard activations (sigmoid, tanh, ReLU, and their variants) were catalogued in Definition 2. Here we examine the subtleties that make one activation preferable to another, from the pathologies of ReLU to the self-normalising properties of SELU to the empirical dominance of GELU and SiLU in modern large language models.

Historical Note.

From the step function to learned activations: eight decades of evolution. The McCulloch–Pitts neuron (1943) used a binary step function: fire or not. The perceptron (Rosenblatt, 1958) inherited this discontinuity, which made gradient-based learning impossible. The sigmoid σ(x)=1/(1+ex) and hyperbolic tangent tanh(x) provided smooth, differentiable alternatives that enabled backpropagation (Rumelhart et al., 1986), but both suffered from saturating gradients: for large |x|, the derivative approaches zero, choking gradient flow in deep networks.

Nair and Hinton (2010) introduced the Rectified Linear Unit ReLU(x)=max(0,x), which is non-saturating for x>0 and computationally trivial. ReLU enabled the training of AlexNet (2012) and became the default activation for nearly a decade. But ReLU has its own pathology, dying neurons, which spawned a menagerie of alternatives: Leaky ReLU, ELU [19], SELU [20], GELU [21], SiLU/Swish [22], and Mish [23]. Today, the “best” activation is often dictated not by theory but by hardware support: GELU and SiLU dominate large-scale training because they are well-optimised on modern GPUs and TPUs.

The Dying ReLU Problem

ReLU's hard zero for x<0 creates a pathological failure mode: neurons can become permanently inactive.

Proposition 8 (Dying ReLU).

A ReLU neuron with weights 𝒘 and bias b computes ReLU(𝒘𝒙+b). If 𝒘𝒙+b<0 for every input 𝒙 in the training set, the neuron's output is identically zero, and its gradient ReLU/𝒘=0. The neuron receives no gradient signal and cannot recover; it is dead.

Proof.

For z=𝒘𝒙+b<0, we have ReLU(z)=0 and ReLU(z)=0. By the chain rule, the gradient of the loss with respect to 𝒘 passes through the factor ReLU(z), which is zero for all training examples. With zero gradient, the parameters 𝒘 and b receive no updates, so the neuron remains in the dead state permanently.

Under He initialisation with b=0, the probability of a neuron dying increases with network depth and learning rate. A large learning rate can push the bias term sufficiently negative that 𝒘𝒙+b<0 for all 𝒙, killing the neuron in a single update step.

Remark 24.

In practice, 10–20% of neurons can die in deep ReLU networks, especially in the early layers where gradient magnitudes are largest relative to the scale of the weights. This motivated alternatives such as Leaky ReLU (LeakyReLU(x)=max(αx,x) with α=0.01), which ensures a small but non-zero gradient for x<0.

SELU: Self-Normalising Networks

Klambauer et al. [20] designed an activation function that makes explicit normalisation layers unnecessary, by ensuring that activations automatically converge to zero mean and unit variance.

Definition 18 (Scaled Exponential Linear Unit).

The Scaled Exponential Linear Unit (SELU) is defined as (SELU)SELU(x)=λ{xif x>0,α(ex1)if x0, where λ1.0507 and α1.6733.

The seemingly arbitrary constants λ and α are far from arbitrary; they are the unique solution to a pair of integral equations that enforce the self-normalising property.

Theorem 1 (Self-Normalising Property).

Let X𝒩(μ,ν) and define μ=𝔼[SELU(X)] and ν=𝖵ar[SELU(X)]. Under LeCun normal initialisation (𝖵ar[weights]=1/nin), the mapping (μ,ν)(μ,ν) has a stable attracting fixed point at (μ,ν)=(0,1).

Proof sketch.

Let ϕ denote the standard normal density. The constants λ and α are chosen as the unique solution to the system (SELU Conditions)λ2[0x2ϕ(x)dx+α20(ex1)2ϕ(x)dx]=1,λ[0xϕ(x)dx+α0(ex1)ϕ(x)dx]=0. The first equation ensures 𝖵ar[SELU(X)]=1 when X𝒩(0,1); the second ensures 𝔼[SELU(X)]=0. A Banach fixed-point argument on the mapping g:(μ,ν)(μ,ν) shows that (0,1) is a stable attractor: perturbations in mean or variance are contracted back towards the fixed point at each layer.

Remark 25.

SELU achieves self-normalisation without explicit normalisation layers (BatchNorm, LayerNorm, etc.), but only under restrictive conditions: fully connected architectures, LeCun normal initialisation, and no skip connections that break the sequential layer-by-layer structure. For convolutional networks and Transformers, explicit normalisation remains necessary, which limits SELU's practical adoption despite its theoretical elegance.

GELU, SiLU, and the NAS Connection

The two activations that dominate modern large language models are GELU [21] and SiLU (also called Swish) [22]. Recall from (Sigmoid) and (Sigmoid): (GELU Recap)GELU(x)=xΦ(x),SiLU(x)=xσ(x), where Φ is the standard normal CDF and σ is the logistic sigmoid.

These two functions are strikingly similar. The connection is immediate once we note that σ(x)Φ(x/1.702): the logistic sigmoid is a rescaled approximation to the normal CDF. Substituting: (GELU SILU Relation)SiLU(x)=xσ(x)xΦ(x/1.702)GELU(x/1.702)1.702. In practice, the difference between GELU and SiLU is negligible for most architectures. GPT-2/3 and BERT use GELU; LLaMA and PaLM use SiLU. The choice is often determined by framework defaults rather than principled comparison.

How Swish was discovered.

Ramachandran et al. [22] used neural architecture search (NAS) to search over the space of activation functions parameterised as f(x)=xσ(βx) for learnable β. The search, conducted across multiple architectures and datasets, consistently converged to β1, yielding f(x)=xσ(x), the SiLU function.

Insight.

Neural architecture search rediscovered a function that mathematicians would recognise as the logistic-weighted identity. The function xσ(x) is a smooth, non-monotonic approximation to ReLU: it is approximately linear for x0, approximately zero for x0, and has a small negative region near x1.28 (minimum value 0.28). This slight non-monotonicity allows the network to suppress weakly negative signals without completely zeroing them out, a property that appears to improve optimisation.

Mish

Misra [23] proposed another smooth, non-monotonic activation that shares the beneficial properties of SiLU but uses a different mathematical formulation.

Definition 19 (Mish).

The Mish activation is defined as (MISH)Mish(x)=xtanh(softplus(x))=xtanh(ln(1+ex)).

Like SiLU, Mish is smooth, non-monotonic, and unbounded above. It has a slightly deeper negative trough than SiLU (minimum value 0.31 at x1.19) and approaches the identity more slowly for large x. Empirically, Mish performs comparably to SiLU on most benchmarks, with occasional small advantages on vision tasks (it was the default activation in YOLOv4).

StarReLU: Matching GELU Statistics Cheaply

Yu et al. [70] observed that much of GELU's benefit comes from its output statistics (mean and variance), not its precise functional form. They proposed an activation that matches GELU's statistics using only elementary operations.

Definition 20 (StarReLU).

The StarReLU activation is defined as (Starrelu)StarReLU(x)=sReLU(x)2+b, where s0.8944 and b0.4472 are chosen so that 𝔼[StarReLU(X)]=0 and 𝖵ar[StarReLU(X)]=1 when X𝒩(0,1), standardising StarReLU to zero mean and unit variance.

StarReLU uses only ReLU and squaring: no exponentials, no error functions, no sigmoid evaluations. On hardware where transcendental functions are expensive (e.g., some mobile accelerators), StarReLU offers a meaningful speedup with minimal accuracy loss. However, on modern GPUs where GELU is implemented as a fused kernel, the computational advantage is negligible, which limits StarReLU's adoption in large-scale training.

Comparison of activation functions on [3,3]. ReLU (blue): piecewise linear, zero for x<0. GELU (green): smooth approximation to ReLU weighted by the Gaussian CDF. SiLU (orange): xσ(x), nearly identical to GELU. SELU (purple): scaled ELU with self-normalising constants. Mish (amber): xtanh(softplus(x)). StarReLU (coral): sReLU(x)2+b, matching GELU's output statistics. Note the small negative region of GELU, SiLU, SELU, and Mish near x1, which allows weak suppression of mildly negative inputs.

Key Idea.

The best activation is often the one your hardware runs fastest. GELU and SiLU dominate large language models not because they are theoretically optimal (no such optimality result exists) but because they are well-supported in fused CUDA kernels on modern GPUs. When choosing an activation, start with GELU (for Transformer-based models) or SiLU (for LLaMA-family architectures). Switch only if profiling reveals a bottleneck: StarReLU for compute-constrained edge deployment, SELU for normalisation-free fully connected architectures, or Mish for specific vision tasks where it has demonstrated gains. The activation function is rarely the limiting factor in model quality; architecture, data, and training procedure matter far more.

Trick #6 - Encode Position Cleverly

Transformers process tokens in parallel, a strength for computation but a weakness for sequence understanding. Unlike recurrent networks, which process tokens one at a time and therefore inherently know the order, a Transformer's self-attention is permutation-equivariant: shuffling the input tokens merely shuffles the output in the same way. Without an explicit position signal, the model cannot distinguish “the cat sat on the mat” from “mat the on sat cat the.”

The sinusoidal positional encoding (Definition 14) and Rotary Position Embeddings (Definition 15), together with the elegant proof that RoPE attention scores depend only on relative position (Proposition 1), were derived in earlier chapters. Here we survey the broader landscape of position encoding strategies, focusing on the practical tricks that determine how far a model can generalise beyond its training context length.

Historical Note.

From afterthought to critical design choice. In the original Transformer paper [24], Vaswani et al. proposed sinusoidal positional encodings almost as an afterthought: the supplementary material showed that learned embeddings performed equally well on their benchmark tasks, and the choice was largely a matter of convenience. GPT-2 (2019) quietly switched to learned positional embeddings, capped at 1024 tokens. It was not until researchers began pushing context lengths beyond a few thousand tokens that the field realised position encoding profoundly affects length generalisation: the ability of a model to process sequences longer than those seen during training.

RoPE [25] (2021) introduced rotary embeddings and quickly became the standard for open-weight large language models. ALiBi [26] (2022) showed that position need not be encoded in the embeddings at all; a simple bias in the attention logits suffices. The NTK-aware scaling trick (2023), discovered by an anonymous Reddit user, and the YaRN method [27] (2023) then showed that RoPE's frequency schedule can be surgically modified to extend context length with minimal fine-tuning. Today, position encoding is recognised as one of the most consequential architectural decisions in language model design.

Learned Positional Embeddings

The simplest alternative to sinusoidal encodings is to learn position representations directly from data.

Definition 21 (Learned Positional Embedding).

Let Lmax be the maximum sequence length and d the model dimension. A learned positional embedding assigns to each position i{0,1,,Lmax1} a trainable vector (Learned PE)𝒑i=𝑬pos[i,:]d, where 𝑬posLmax×d is a learnable embedding matrix initialised at random (typically from 𝒩(0,0.022)). The input to the first Transformer layer is 𝒉i(0)=𝑬tok[tokeni]+𝒑i.

Learned embeddings are maximally flexible: the model can learn arbitrary position-dependent patterns. The fatal limitation is that 𝑬pos has exactly Lmax rows. At inference time, if the sequence length exceeds Lmax, there is no embedding for positions Lmax, and the model cannot generalise.

Remark 26.

GPT-2 used Lmax=1024; GPT-3 raised it to 2048. These choices were architectural ceilings that could not be lifted without retraining. This rigidity motivated the search for position encodings with built-in extrapolation capabilities.

ALiBi: Attention with Linear Biases

Press et al. [26] proposed an elegantly simple alternative: do not encode position in the embeddings at all. Instead, add a position-dependent bias directly to the attention logits.

Definition 22 (Attention with Linear Biases (ALiBi)).

Given queries 𝑸, keys 𝑲, values 𝑽n×d, and a head-specific slope m>0, the ALiBi attention for head h is (Alibi)attnALiBi(𝑸,𝑲,𝑽)=softmax(𝑸𝑲dmh𝑫)𝑽, where the distance matrix 𝑫n×n has entries Dij=|ij|, and the head slopes are set to (Alibi Slopes)mh=28h/H,h=1,2,,H, with H the total number of attention heads.

There are no learnable parameters associated with the position encoding in ALiBi: the slopes mh are fixed hyperparameters. Different heads attend at different scales: head 1 (the steepest slope) focuses almost exclusively on nearby tokens, while head H (the shallowest slope) has a nearly uniform attention pattern.

Proposition 9 (ALiBi Length Extrapolation).

Under ALiBi attention with slope m, the unnormalised attention weight from position i to position j satisfies (Alibi Decay)Sijexp(𝒒i𝒌jdm|ij|)=exp(𝒒i𝒌jd)em|ij|. Thus the attention weight decays exponentially with distance at rate m, regardless of the absolute positions involved.

Proof.

Write the softmax input as aij=𝒒i𝒌j/dm|ij|. By the definition of softmax, Sij=exp(aij)kexp(aik)=exp(𝒒i𝒌j/d)exp(m|ij|)kexp(𝒒i𝒌k/d)exp(m|ik|). The proportionality Sijexp(𝒒i𝒌j/d)em|ij| follows directly. Since the exponential decay factor em|ij| depends only on the distance |ij| and not on the absolute positions i or j, the attention pattern generalises naturally to positions unseen during training: a token at position 10,000 attends to a token at position 9,990 with the same bias as position 110 attends to position 100.

Remark 27.

ALiBi was used in the BLOOM model (176B parameters) and showed strong length extrapolation: trained at length 2048, it maintained perplexity when tested at lengths up to 8192. However, more recent models have largely converged on RoPE-based approaches, which offer better fine-grained position control.

NTK-Aware RoPE Scaling

Given that RoPE (Definition 15) has become the dominant position encoding, the most pressing practical question is: how do we extend the context length of a pretrained RoPE model without full retraining? The simplest approach, position interpolation [71], linearly rescales all positions by the factor Ltrain/Ltarget. This works but degrades quality on short-range patterns because it compresses the high-frequency rotations.

Definition 23 (NTK-Aware RoPE Scaling).

Given the original RoPE base frequency θbase=10000, define the NTK-aware scaled base as (NTK ROPE)θbase=θbase(αLtargetLtrain)d/(d2), where α is a scaling factor (typically α=1), d is the head dimension, and Ltarget>Ltrain is the desired context length. The modified frequency schedule is then θi=(θbase)2(i1)/d for i=1,,d/2.

The key intuition is rooted in the neural tangent kernel (NTK) perspective: the RoPE frequency spectrum spans from very low frequencies (large θi, capturing long-range structure) to very high frequencies (small θi, capturing fine-grained local patterns). Position interpolation uniformly compresses all frequencies, destroying the high-frequency information that the model has already learned to use for local token interactions. NTK-aware scaling instead adjusts the base frequency, which effectively stretches the low frequencies more than the high frequencies. The result: long-range positions receive genuinely new frequency representations, while short-range patterns remain largely intact.

Remark 28.

The NTK-aware scaling trick was discovered by an anonymous Reddit user (bloc97) in July 2023 [28] and published as a forum post rather than a peer-reviewed paper. Within weeks, it was adopted by the open-source community and integrated into major inference frameworks. This is a striking example of how the open-source ecosystem can produce and propagate impactful research outside traditional academic channels.

YaRN: Yet Another RoPE ExtensioN

Peng et al. [27] observed that neither pure interpolation nor NTK-aware scaling is optimal across the full frequency spectrum. Their solution, YaRN (Yet Another RoPE ExtensioN), partitions the frequency dimensions into three zones and treats each differently.

Definition 24 (YaRN: Yet Another RoPE ExtensioN).

Let s=Ltarget/Ltrain be the extension ratio. For each RoPE dimension i, define the wavelength-to-training-length ratio (YARN Ratio)ri=Ltrain2πθi, where θi is the original RoPE frequency for dimension i. Given boundary parameters α and β (typically α=1, β=32), define the ramp function (YARN RAMP)γ(ri)=riαβα,γ=clamp(γ,0,1). The three-zone treatment is:

  1. Zone 1 (low frequency, ri>β): interpolate by factor s, i.e., θi=θi/s.

  2. Zone 2 (mid frequency, αriβ): blend with the ramp function, θi=(1γ)θi+γ(θi/s).

  3. Zone 3 (high frequency, ri<α): keep original frequencies unchanged, θi=θi.

Additionally, YaRN applies an attention scaling factor (YARN ATTN Scale)t=1+0.1lns to the attention logits, compensating for the entropy increase caused by extending the context window: the query-key dot products are divided by dt instead of d.

The logic behind YaRN's three-zone partition is both simple and elegant. Low-frequency RoPE dimensions encode long-range positional information; since the model has never seen positions beyond Ltrain, these dimensions must be interpolated. High-frequency dimensions encode short-range patterns that the model has thoroughly learned; modifying them would destroy this learned structure. Mid-frequency dimensions fall somewhere in between and benefit from a smooth blend.

Remark 29.

YaRN achieves 128k context length with only 400 training steps of fine-tuning on a 64k-trained LLaMA model. This remarkable efficiency stems from the fact that YaRN changes only the frequency schedule, not the model weights. The brief fine-tuning allows the model to adapt to the modified frequencies without forgetting its pretrained knowledge.

Position Encoding Comparison

Table 4 summarises the key properties of the position encoding methods discussed in this section and earlier chapters.

MethodLearned?ExtrapolationRelative?Key Property
SinusoidalNoLimitedNoFixed; smooth decay with distance
LearnedYesNoneNoMaximum flexibility; fixed Lmax
RoPENoModerateYesRotational; decays with distance
ALiBiNoStrongYesExponential decay via attention bias
NTK-RoPENoGoodYesFrequency-aware base scaling
YaRNNoStrongYesThree-zone frequency modification
Comparison of position encoding methods. “Relative” means the attention score depends only on the distance |ij|, not the absolute positions i and j.
Effective wavelength of RoPE dimensions under different scaling strategies. Original RoPE (solid blue) spans wavelengths from short (low dimensions) to long (high dimensions). NTK-aware scaling (dashed green) uniformly shifts all frequencies by modifying the base. YaRN (dotted red) applies zone-specific treatment: high-frequency dimensions (Zone 3) are kept unchanged, mid-frequency dimensions (Zone 2) are smoothly blended, and low-frequency dimensions (Zone 1) are interpolated. Extension ratio s=4 (from 4k to 16k context).

Key Idea.

Position encoding is not just bookkeeping; it determines how far the model can see. The choice of position encoding sets a fundamental limit on context length generalisation. Learned embeddings create a hard ceiling at Lmax. Sinusoidal encodings theoretically generalise but degrade in practice. RoPE with intelligent frequency scaling (NTK-aware, YaRN) currently offers the best combination of quality and length extrapolation, which is why nearly all modern large language models use some variant of RoPE.

Trick #7 - Attend Efficiently

Self-attention is the computational heart of the Transformer, but it comes with a quadratic price tag. Standard attention (Definition 12) computes softmax(𝑸𝑲/d)𝑽, requiring Θ(n2d) operations and Θ(n2) memory to store the attention matrix. For moderate sequence lengths this is acceptable, but as models push towards million-token contexts, the quadratic cost becomes the dominant bottleneck.

Grouped-query attention (Definition 17), Flash Attention (Algorithm 3) with its IO-complexity analysis (Proposition 2), and multi-head latent attention (Definition 22) were presented in the Transformer chapter. Here we survey additional tricks for taming attention's appetite for compute and memory.

Historical Note.

The quadratic cost of attention is both its strength and its curse. The n2 attention matrix is precisely what allows every token to attend to every other token, a property that gives Transformers their remarkable modelling power. But the cost grows rapidly:

Sequence length nAttention entries n2Scale
1,000106Manageable
10,000108Expensive
100,0001010Very expensive
1,000,0001012Prohibitive
The quest for efficient attention has produced a rich ecosystem of approximations, sparse patterns, and systems-level optimisations, each trading off some combination of quality, speed, and generality.

Sparse Attention Patterns

The simplest idea for reducing attention cost is to compute only a subset of the n2 attention entries. Child et al. [72] introduced systematic sparse attention patterns in the Sparse Transformer.

Definition 25 (Sparse Attention).

Given a sparsity pattern 𝒮{1,,n}2, define the neighbourhood of position i as 𝒮(i)={j:(i,j)𝒮}. The sparse attention output at position i is (Sparse ATTN)attnsparse(𝑸,𝑲,𝑽)i=j𝒮(i)exp(𝒒i𝒌j/d)k𝒮(i)exp(𝒒i𝒌k/d)softmax restricted to 𝒮(i)𝒗j. Three canonical sparsity patterns are:

  1. Local window: 𝒮local(i)={j:|ij|w}, with |𝒮(i)|=2w+1, giving 𝒪(nw) total complexity.

  2. Strided: 𝒮stride(i)={j:(ij)mods=0}, with |𝒮(i)|=n/s, giving 𝒪(n2/s) total complexity.

  3. Combined: 𝒮=𝒮local𝒮stride, combining local detail with long-range connectivity.

Proposition 10 (Sparse Attention Complexity).

Combined local + strided sparse attention with window size w=n and stride s=n achieves 𝒪(nn) complexity, while maintaining the property that every token pair (i,j) is connected within at most 2 attention hops.

Proof.

Complexity.; Each token i attends to at most 2w+1+n/s positions. With w=s=n, this is 2n+1+n=3n+1=𝒪(n). Over all n tokens, the total number of attention entries is 𝒪(nn).

Connectivity.; Let i and j be arbitrary positions. We show that j can reach i in at most two hops. Let j=j+((ij)mods) be the nearest position to j that shares a strided connection with i (i.e., (ij)mods=0). Since 0(ij)mods<s=n, we have |jj|<n=w, so j𝒮local(j) (hop 1: jj). Furthermore, (ij)mods=0 by construction, so i𝒮stride(j) (hop 2: ji).

Sliding Window Attention

Sliding window attention takes the local window pattern and makes it the primary attention mechanism, relying on the depth of the network to propagate information across the full sequence.

Definition 26 (Sliding Window Attention).

Given a window size W, the sliding window attention at position i is (SWA)attnsw(𝑸,𝑲,𝑽)i=softmax(𝒒i𝑲[iW:i+W]d)𝑽[iW:i+W], where 𝑲[iW:i+W] and 𝑽[iW:i+W] denote the key and value vectors for positions in the window {j:|ij|W}. The per-layer complexity is 𝒪(nW), which is linear in n for fixed W.

A crucial insight is that the effective receptive field grows linearly with depth. After L layers of sliding window attention, information from a token at position j can influence a token at position i provided |ij|LW. For a model with L=32 layers and W=4096, the effective receptive field is 32×4096=131,072 tokens, sufficient for most practical applications.

Remark 30.

Mistral 7B [29] uses sliding window attention with W=4096, augmented by periodic global attention layers (every 4th layer) that attend to the full sequence. This hybrid approach achieves the efficiency of sliding windows while ensuring that long-range dependencies are captured. The Longformer [30] similarly combines local windows with task-specific global attention tokens.

Ring Attention

For sequences so long that even the key-value matrices do not fit on a single accelerator, Ring Attention [73] distributes the computation across multiple devices arranged in a ring topology.

Definition 27 (Ring Attention).

Consider a sequence of length n distributed across P devices. Each device p holds a contiguous block of n/P tokens, with the corresponding query, key, and value sub-matrices 𝑸p,𝑲p,𝑽p(n/P)×d. Ring Attention computes exact full attention by circulating the key-value blocks around a ring of devices:

  1. Partition: split the sequence into P blocks B1,,BP assigned to devices 1,,P.

  2. Iterate: for r=0,1,,P1: enumerate[(i)]

  3. Device p computes the partial attention of 𝑸p against 𝑲(p+r)modP and 𝑽(p+r)modP.

  4. Device p sends its current KV block to device (p+1)modP (ring shift).

  5. Accumulate softmax numerators and denominators using the online softmax trick: maintain running max, sum of exponentials, and weighted value sum. enumerate

  6. Finalize: after P rounds, each device has computed exact attention for its query block.

Proposition 11 (Ring Attention Communication Cost).

Ring Attention communicates a total of 𝒪(nd) bytes across all devices, achieving linear scaling with the number of devices.

Proof.

In each of the P1 communication rounds (the last round requires no send since each device already holds its own KV block at that point), each device sends a KV block of size 2(n/P)d values (the factor 2 accounts for both 𝑲 and 𝑽). The total bytes communicated across all devices in one round is P2(n/P)d=2nd. Over P1 rounds, the total is 2nd(P1). However, since the ring shift is pipelined (each device sends while computing), the latency is P1 rounds, but the bandwidth per device is (P1)2(n/P)d=2nd(11/P)=𝒪(nd), independent of P.

Remark 31.

Ring Attention is the key enabler for training on extremely long contexts. Combined with Flash Attention for the local computation on each device, it achieves both memory efficiency (via the online softmax trick, which avoids materialising the full attention matrix) and communication efficiency (via the ring topology, which overlaps communication with computation).

Linear Attention

An entirely different approach to reducing attention cost is to approximate the softmax kernel with a decomposable feature map, enabling the computation to be rearranged from 𝒪(n2d) to 𝒪(nd2).

Definition 28 (Linear Attention).

Replace the softmax attention softmax(𝑸𝑲)𝑽 with (Linear ATTN)attnlinear(𝑸,𝑲,𝑽)=ϕ(𝑸)(ϕ(𝑲)𝑽), where ϕ:dd is a non-negative feature map applied row-wise, and the parenthesisation indicates the order of matrix multiplication. A common choice is ϕ(𝒙)=elu(𝒙)+1, where elu is the exponential linear unit [31].

The key algebraic insight is the associativity trick. In standard attention, we must first compute 𝑨=𝑸𝑲n×n (cost 𝒪(n2d)) and then 𝑨𝑽n×d (cost 𝒪(n2d)). In linear attention, we instead first compute 𝑺=ϕ(𝑲)𝑽d×d (cost 𝒪(nd2)) and then ϕ(𝑸)𝑺n×d (cost 𝒪(nd2)). The total is 𝒪(nd2), which wins whenever n>d, a common regime in long-context applications.

Remark 32.

Linear attention trades attention quality for computational speed. In practice, the approximation to the softmax kernel is loose, and linear attention models consistently underperform standard softmax attention for language modelling tasks requiring precise token-to-token dependencies. However, linear attention has found success in recurrent-style architectures (RetNet, RWKV, Mamba) where the 𝑺 matrix serves as a compressed state that is updated incrementally, enabling efficient autoregressive inference.

Flash Attention Extensions

The core Flash Attention algorithm was presented in Algorithm 3, with its IO complexity analysis in Proposition 2. Here we survey the subsequent extensions that have made Flash Attention the de facto standard for attention computation.

Flash Attention 2.

Dao [74] introduced several improvements over the original:

  1. Parallelism over sequence length: the original Flash Attention parallelises over batch size and number of heads. Flash-2 additionally parallelises over the sequence length dimension, improving GPU occupancy for long sequences.

  2. Reduced non-matmul FLOPs: by rearranging the online softmax computation, Flash-2 reduces the overhead of non-matrix-multiply operations, which are bottlenecked by GPU register bandwidth.

  3. Result: approximately 2× speedup over the original Flash Attention on A100 GPUs.

Flash Attention 3.

Shah et al. [75] leverage hardware features specific to NVIDIA Hopper GPUs (H100):

  1. TMA (Tensor Memory Accelerator): asynchronous data movement between global memory and shared memory.

  2. WGMMA (Warpgroup Matrix Multiply-Accumulate): higher-throughput matrix multiply instructions.

  3. Warp specialisation: dedicating different warp groups to different tasks (data loading vs. computation) to maximise pipeline utilisation.

  4. Result: 1.5–2× speedup over Flash-2 on H100 GPUs, approaching the theoretical peak throughput.

PagedAttention.

Kwon et al. [76] address a different bottleneck: the KV cache (Definition 16) memory management during inference.

  1. Problem: standard KV cache pre-allocates contiguous memory for the maximum sequence length, leading to significant memory fragmentation and waste when serving multiple requests of varying lengths.

  2. Solution: PagedAttention manages the KV cache in fixed-size pages (analogous to OS virtual memory), allocating pages on demand and using a page table for indirection.

  3. Result: near-zero memory waste, enabling 2–4× higher serving throughput via better batching.

Remark 33.

Flash Attention is an implementation trick, not an approximation: it computes exact attention with the same numerical output as the naive algorithm (up to floating point non-associativity). This is what distinguishes it from sparse or linear attention methods, which sacrifice accuracy for speed. Flash Attention achieves its gains purely through better memory access patterns, a vivid demonstration that algorithms must be designed for the hardware they run on.

Attention pattern comparison. Dense: every token attends to every token (𝒪(n2)). Sparse: combined local window (bandwidth 1) and strided (stride 4) pattern (𝒪(nn)). Sliding window: fixed local window of size W (𝒪(nW)). Ring: full attention distributed across 4 devices; each colour indicates the device that owns the query rows. The result is exact dense attention computed in a distributed manner.

Insight.

The best attention trick depends on the bottleneck. If the bottleneck is memory bandwidth (the attention matrix does not fit in SRAM), use Flash Attention. If the bottleneck is FLOPs (the quadratic computation is too expensive), use sparse attention patterns. If the bottleneck is device memory (the sequence does not fit on a single accelerator), use Ring Attention. In practice, these tricks compose: a modern training run might use Flash Attention locally, sparse patterns for extremely long sequences, and Ring Attention to distribute across a cluster.

Trick #8 - Regularize Creatively

Deep networks have enormous capacity, far more parameters than training examples in most practical settings. Classical learning theory would predict catastrophic overfitting. Yet deep networks generalise remarkably well, and a key reason is the regularisation tricks that prevent them from memorising the training data. This section surveys the most important regularisation techniques, unified by a common principle: inject controlled noise during training, and remove it during inference.

Historical Note.

Hinton's insight: if a committee of experts always agrees, they might be overfitting. Geoffrey Hinton motivated dropout with an analogy from evolutionary biology: sexual reproduction creates genetic diversity by randomly combining parental genes, preventing any single gene from becoming a “free rider” that only works in combination with specific other genes. Analogously, dropout forces each neuron to be independently useful, preventing co-adaptation. Hinton later remarked that this idea came to him after a conversation with a bank teller: banks rotate tellers between branches specifically to prevent fraud through collusion. If employees cannot rely on having the same colleagues, they cannot develop exploitative partnerships. The same principle applies to neurons in a neural network.

Dropout

Definition 29 (Dropout).

Let 𝒉d be a hidden activation vector and p(0,1) the dropout rate. During training, inverted dropout produces (Dropout)hi=mihi1p,miBernoulli(1p),i=1,,d, where the mask mi is sampled independently for each neuron and each training example. During inference, no masking or scaling is applied: hi=hi.

The scaling factor 1/(1p) in inverted dropout ensures that the expected value is preserved: 𝔼[hi]=hi. This eliminates the need to modify the network at test time, a practical convenience that has made inverted dropout the universal implementation.

Proposition 12 (Dropout as Implicit Ensemble).

A network with L layers, each containing n neurons, trained with dropout rate p, implicitly trains an ensemble of up to 2nL sub-networks. The inference-time prediction (using all neurons with scaled weights) approximates the geometric mean of the predictions of these sub-networks.

Proof sketch.

Each dropout mask 𝒎=(m1,,mnL){0,1}nL selects a sub-network f𝒎 by zeroing out a subset of neurons. Training with dropout optimises the expected loss over masks: minθ𝔼𝒎[(f𝒎(𝒙;θ),y)]. For the cross-entropy loss =logp(y|𝒙), this is equivalent to minimising the KL divergence to a mixture model. At inference, using all neurons with weights scaled by (1p) computes a single forward pass whose output approximates p(y|𝒙)𝒎p𝒎(y|𝒙)1/2nL=exp(12nL𝒎logp𝒎(y|𝒙)), the geometric mean of the sub-network predictions. The approximation relies on the first-order Taylor expansion of the network output around the mean activation, which is exact for linear networks and approximate for nonlinear ones.

Proposition 13 (Dropout as Approximate Bayesian Inference).

Gal and Ghahramani [32] showed that training a neural network with dropout and L2 regularisation is mathematically equivalent to approximate variational inference in a deep Gaussian process. The dropout rate p corresponds to the prior precision, and Monte Carlo dropout at test time (running the network multiple times with different dropout masks) provides a principled estimate of predictive uncertainty.

Proof sketch.

Consider a single-layer network f(𝒙)=σ(𝑾𝒙) with dropout applied to the weight matrix: 𝑾~=𝑾diag(𝒎), miBernoulli(1p). The variational distribution is q(𝑾~)=i[(1p)δ(w~iwi)+pδ(w~i)]. Gal and Ghahramani show that the ELBO (evidence lower bound) of this variational distribution, applied to a Gaussian process prior with kernel κ(𝒙,𝒙)=σ(𝒙)σ(𝒙), equals (up to a constant) the dropout training objective 𝔼𝒎[(f𝒎(𝒙),y)]+λ𝑾F2, where λ is determined by p and the prior precision.

DropPath (Stochastic Depth)

Dropout zeros out individual neurons. DropPath, also known as stochastic depth [77], operates at a coarser granularity: it drops entire layers (more precisely, entire residual branches).

Definition 30 (Stochastic Depth / DropPath).

In a residual network with L blocks, the output of layer is (Droppath)𝒙+1=𝒙+bF(𝒙), where bBernoulli(p) is a binary random variable with survival probability p that follows a linear decay schedule: (Droppath Schedule)p=1L(1pL), with pL(0,1) the survival probability of the last layer (typically pL=0.8). Early layers (small ) survive with high probability; later layers are dropped more frequently.

At inference, no stochastic dropping is performed. Instead, the residual branch is scaled by the survival probability: (Droppath Inference)𝒙+1=𝒙+pF(𝒙).

The linear decay schedule reflects the empirical observation that later layers in deep networks tend to learn more fine-grained, task-specific features that are more prone to overfitting, while early layers learn general features that should always be active.

Remark 34.

DropPath is standard in Vision Transformers. DeiT, Swin Transformer, and ConvNeXt all use DropPath with survival rates between 0.7 and 0.9. It is generally more effective than standard dropout for deep residual networks because it regularises the depth of the effective network rather than individual neurons, providing a qualitatively different form of noise injection.

Label Smoothing

Definition 31 (Label Smoothing).

Given K classes, replace the hard target 𝒚=𝒆k (a one-hot vector for class k) with the smooth target (Label Smooth)𝒚smooth=(1ε)𝒆k+εK𝟏, where ε(0,1) is the smoothing parameter (typically ε=0.1) and 𝟏=(1,,1) [33].

With hard targets, the cross-entropy loss drives the logits towards + for the correct class and for all others; the model becomes maximally confident and often overconfident, assigning near-zero probability to all but the correct class. Label smoothing prevents this by ensuring the target distribution always has non-zero probability for every class.

Proposition 14 (Label Smoothing and Calibration).

With label smoothing parameter ε and K classes, the maximum logit at the optimum of the smoothed cross-entropy loss is bounded: (Label Smooth Logit)zczj=ln(K(1ε)ε+1).

Proof.

At the optimum of =kyksmoothlogpk, the softmax outputs equal the targets: pk=yksmooth for all k. For the correct class c, pc=1ε+ε/K. For incorrect classes, pj=ε/K. Using pc=ezc/kezk and pj=ezj/kezk, we get pcpj=ezczj=1ε+ε/Kε/K=K(1ε)+εε=K(1ε)ε+1. Taking logarithms: zczj=ln(K(1ε)/ε+1). Since zc is the maximum logit and all zj are equal (by symmetry of the target over incorrect classes), this is the maximum logit gap. The bound maxkzkln((1ε)(K1)/ε) follows from noting that (K1) incorrect classes share the remaining probability mass.

Mixup

Definition 32 (Mixup).

Given two training examples (𝒙i,𝒚i) and (𝒙j,𝒚j), Mixup [34] constructs a virtual training example by linear interpolation: (Mixup)𝒙~=λ𝒙i+(1λ)𝒙j,𝒚~=λ𝒚i+(1λ)𝒚j, where λBeta(α,α) with α>0 (typically α[0.2,0.4]).

Remark 35 (Vicinal Risk Minimisation).

Standard empirical risk minimisation (ERM) optimises the loss over point masses at training examples: R^=(1/N)i(f(𝒙i),𝒚i). Mixup instead minimises risk over the vicinity of training examples, defined by linear interpolation in both input and label space. This vicinal risk minimisation (VRM) framework encourages the model to behave linearly between training examples: the function value at the midpoint of two inputs should be the midpoint of their labels. This implicit linear prior is a powerful inductive bias that reduces oscillation and improves generalisation.

CutMix

Definition 33 (CutMix).

Given two images 𝒙i,𝒙jH×W×C and their labels 𝒚i,𝒚j, CutMix [35] constructs a training example by spatial composition: (Cutmix)𝒙~=𝑴𝒙i+(𝟏𝑴)𝒙j,𝒚~=λ𝒚i+(1λ)𝒚j, where 𝑴{0,1}H×W is a binary mask corresponding to a randomly sampled rectangular region, and λ=1area(𝑴)/(HW) is the fraction of the image from 𝒙i.

CutMix offers two advantages over standard Mixup. First, it preserves local spatial structure: within each region, the pixels come from a single coherent image, so the model sees realistic local patterns rather than ghost-like superimpositions. Second, it forces the model to classify from partial information: a training example might show 70% of a dog and 30% of a cat, requiring the model to recognise both from incomplete evidence. This encourages attention to distributed features rather than reliance on a single discriminative region.

R-Drop

Definition 34 (R-Drop).

Given an input 𝒙 and target y, pass 𝒙 through the model twice with different dropout masks, producing output distributions p1=f(𝒙;𝒎1) and p2=f(𝒙;𝒎2). The R-Drop loss [36] is (Rdrop)R-Drop=CE(p1,y)+CE(p2,y)+α[KL(p1p2)+KL(p2p1)], where α>0 controls the strength of the consistency regularisation, and the symmetric KL divergence penalises the two forward passes for producing different outputs.

Remark 36.

R-Drop combines the ensemble benefit of dropout with a consistency objective. The two forward passes with different masks produce different predictions; the KL term forces these predictions to agree. This is conceptually similar to self-distillation: each forward pass serves as both student and teacher to the other. The result is a model that is more robust to the specific dropout mask used, leading to better generalisation.

Three regularisation techniques. (a) Dropout: neurons (crossed out) are randomly zeroed during training, along with their connections. (b) Mixup: two images are linearly blended with mixing coefficient λBeta(α,α); the label is similarly interpolated. (c) CutMix: a rectangular region from one image replaces a corresponding region in another; the label reflects the area ratio.

Key Idea.

Regularisation tricks all share one principle: inject controlled noise during training, remove it during inference. Dropout injects noise by zeroing activations. DropPath injects noise by skipping layers. Label smoothing injects noise into the targets. Mixup and CutMix inject noise by blending examples. R-Drop injects noise through inconsistent dropout masks and then penalises the inconsistency. In each case, the noise prevents the model from relying too heavily on any single feature, co-adaptation, or memorised pattern, forcing it to learn robust representations that transfer to unseen data.

Trick #9 - Schedule the Learning Rate

The learning rate η in SGD (Definition 4) and its variants is not merely a hyperparameter to be tuned once and fixed. It is a dynamic control signal that shapes the entire training trajectory. Too high, and the optimiser overshoots and diverges. Too low, and it gets trapped in poor local minima or takes unacceptably long to converge. The art of learning rate scheduling is to navigate between these extremes throughout the training process.

Historical Note.

From fixed learning rates to sophisticated schedules. Yann LeCun wrote in 1998: “The learning rate is the single most important hyperparameter, and one should always make sure that it has been tuned.” Early practitioners used a simple prescription: start with a “large” learning rate (e.g., 0.1) and divide by 10 every time the validation loss plateaus (step decay). This worked reasonably well for small networks but required constant manual intervention.

The modern era of learning rate scheduling began with two parallel developments. Loshchilov and Hutter [37] introduced cosine annealing with warm restarts, providing a smooth, principled schedule. Smith [38] showed that cyclical learning rates, deliberately increasing the LR during training, could actually improve convergence. Today, every competitive large-scale training run uses a carefully designed schedule, typically combining warmup, a main training phase, and a cooldown.

Warmup

Definition 35 (Linear Warmup).

During the first Twarmup training steps, the learning rate increases linearly from near zero to its maximum value: (Warmup)ηt=ηmaxtTwarmup,t=1,2,,Twarmup. After the warmup phase completes, the learning rate transitions to the main schedule (cosine, linear decay, etc.).

Why is warmup necessary? At initialisation, the network's representations are essentially random. Gradients computed on these random representations are noisy: they point in roughly the right direction on average, but with high variance. A large learning rate applied to noisy gradients produces large, erratic updates that can push the parameters into regions of the loss landscape from which recovery is difficult or impossible.

Proposition 15 (Warmup and Gradient Noise).

Define the gradient noise scale (GNS) as 𝒢t=t/σ(t), where t is the gradient norm and σ(t) is the standard deviation of the gradient estimate. The GNS is typically smallest at initialisation (high noise relative to signal). Linear warmup maintains an approximately constant effective step size by keeping the product ηt𝒢t bounded during the initial phase when 𝒢t is small and growing.

Proof sketch.

At initialisation, the gradients are approximately isotropic with magnitude 0σ(0), so 𝒢01. As training progresses and the network begins to fit the data, the signal-to-noise ratio improves: 𝒢t grows. If η were immediately set to ηmax, the effective step size ηmax/𝒢0ηmax would be large. With linear warmup, ηt=ηmaxt/Twarmup starts small and grows in proportion to t, approximately matching the growth rate of 𝒢t and keeping ηt/𝒢t bounded.

Remark 37.

Every modern large language model training run uses warmup, typically spanning 1–5% of total training steps. The exact warmup duration is not critical: 500 to 5000 steps usually suffices. What matters is that the initial learning rate is small enough to prevent divergence. Goyal et al. [39] demonstrated that warmup is essential for large-batch training: without it, increasing the batch size (and proportionally the learning rate) leads to training instability.

Cosine Annealing

Definition 36 (Cosine Annealing).

The cosine annealing schedule [37] decays the learning rate following a half-cosine curve: (Cosine)ηt=ηmin+12(ηmaxηmin)(1+cosπtT),t=0,1,,T, where ηmin is the minimum learning rate (often 0 or 0.1ηmax) and T is the total number of training steps.

The cosine schedule has several appealing properties. It starts at ηmax when t=0 and smoothly decays to ηmin when t=T, with no abrupt transitions. Crucially, the schedule spends more time at low learning rates: the derivative dηt/dt=π2T(ηmaxηmin)sin(πt/T) is smallest near the endpoints, meaning the learning rate changes slowly at the beginning and end. This is desirable because the final phase of training benefits from small, precise updates.

Cosine with warm restarts (SGDR).

Loshchilov and Hutter also proposed periodically restarting the cosine schedule: (SGDR)ηt=ηmin+12(ηmaxηmin)(1+cosπTcurTi), where Tcur resets to 0 at each restart, and the period can grow geometrically: Ti=T0Tmulti for the i-th restart. Each restart allows the optimiser to escape local minima by temporarily increasing the learning rate, then fine-tune into a (potentially better) basin.

Remark 38.

Cosine annealing (without restarts) is the de facto default schedule for large-scale pretraining of both vision and language models. Chinchilla (2022), LLaMA (2023), and Gemma (2024) all use cosine schedules. The simplicity and robustness of the cosine curve (no step sizes, no milestone epochs) make it an excellent default choice when a practitioner has no strong prior about the optimal schedule.

Cyclical Learning Rates

Smith [38] made a counterintuitive observation: periodically increasing the learning rate during training can improve both convergence speed and final accuracy.

Definition 37 (Cyclical Learning Rate).

The learning rate oscillates between ηmin and ηmax in a triangular wave with half-period (step size) S: (Cyclical LR)ηt=ηmin+(ηmaxηmin)max(0,1|t/S2t/(2S)1|). The learning rate linearly increases for S steps, then linearly decreases for S steps, and repeats.

A key practical contribution from Smith's work is the LR range test, a simple diagnostic for finding the viable range of learning rates for any model and dataset.

Definition 38 (LR Range Test).

  1. Start with a very small learning rate (e.g., 107).

  2. Increase the learning rate exponentially after each mini-batch: ηt+1=ηtγ where γ>1 (e.g., γ=1.05).

  3. Record the training loss at each learning rate.

  4. Choose ηmax as the learning rate where the loss begins to increase (or diverge).

  5. Choose ηmin=ηmax/10.

Remark 39.

The LR range test is useful for any schedule, not just cyclical. It identifies the viable learning rate range in a fraction of a training epoch, providing an informed starting point that eliminates much of the guesswork in hyperparameter tuning.

One-Cycle Policy

Smith and Topin [78] refined cyclical learning rates into the one-cycle policy, which uses a single cycle of increasing and decreasing learning rate over the entire training run.

Definition 39 (One-Cycle Policy).

The one-cycle schedule has three phases:

  1. Phase 1 (30–50% of training): increase the learning rate linearly from ηmin to ηmax.

  2. Phase 2 (50–70% of training): decrease the learning rate linearly from ηmax to ηmin.

  3. Phase 3 (final 5% of training, optional): anneal the learning rate from ηmin to a very small value ηmin/100 for final fine-tuning.

Concurrently, the momentum parameter (in SGD with momentum) is varied inversely: high momentum when LR is low, low momentum when LR is high.

Insight.

Super-convergence. Smith and Topin demonstrated a remarkable phenomenon: the one-cycle policy can achieve the same final accuracy as a standard schedule in as few as 1/10 of the epochs. This “super-convergence” occurs because the increasing learning rate in Phase 1 serves as a form of regularisation (the large LR prevents the model from settling into sharp minima) while the decreasing phase allows fine-grained convergence to a flat minimum with good generalisation.

WSD: Warmup-Stable-Decay

The most recent addition to the learning rate schedule repertoire is the WSD (Warmup-Stable-Decay) schedule, which was instrumental in training the MiniCPM models [79].

Definition 40 (Warmup-Stable-Decay (WSD) Schedule).

The WSD schedule consists of three phases:

  1. Warmup (tTw): ηt=ηmaxt/Tw.

  2. Stable (Tw<tTs): ηt=ηmax (constant).

  3. Decay (t>Ts): ηt=ηmaxcos(π(tTs)2(TTs)), or alternatively, linear or exponential decay.

The key insight behind WSD is that the stable phase at constant ηmax serves as a plateau during which the model steadily improves. At any point during the stable phase, one can branch off a copy of the training run and apply a short decay phase to produce a usable checkpoint. This makes the schedule “anytime optimal”: you do not need to commit to a total training budget in advance. With cosine annealing, the learning rate is entangled with the total number of steps T, making it impossible to extend training without restarting the schedule.

Remark 40.

The WSD schedule was used to train MiniCPM-2B, a 2.4B parameter model that matches the performance of models 5–10× larger. The authors attribute part of this success to the ability to select the optimal point to begin the decay phase by monitoring validation loss during the stable phase. This “training-as-exploration” paradigm, where the stable phase explores the loss landscape and the decay phase exploits the best trajectory, represents a conceptually clean separation of concerns.

Comparison of learning rate schedules. Step decay (blue): piecewise constant, drops at predetermined milestones. Cosine (green): smooth half-cosine from ηmax to 0. Cyclical (purple): oscillates between ηmin and ηmax. One-cycle (orange): single triangle with final anneal. WSD (red): warmup to ηmax, hold constant, then cosine decay. The WSD schedule is “anytime optimal”: the decay phase can begin at any point during the stable phase.

Key Idea.

The learning rate is not a fixed hyperparameter; it is a dynamic control signal that must be matched to the training dynamics. At initialisation, when gradients are noisy and the loss landscape is poorly conditioned, the learning rate should be small (warmup). During the main training phase, it should be large enough to explore broadly. Towards the end, it should decay to allow convergence to a precise minimum. The specific schedule (cosine, cyclical, WSD) matters less than the principle: adapt the learning rate to the training dynamics, not the other way around.

Trick #10 - Train in Low Precision

Every number in a neural network (every weight, activation, gradient, and optimizer state) is represented as a floating-point number. For decades, the default was 32-bit floating point (FP32), a format designed for scientific computing with 7 decimal digits of precision. Modern deep learning has shown that this precision is vastly more than needed: networks can be trained with 16-bit or even 8-bit numbers with little or no accuracy loss, while enjoying dramatic speedups and memory savings.

Historical Note.

The assumption that neural networks need 32-bit precision was one of deep learning's most expensive misconceptions. In 2017, NVIDIA's V100 GPU introduced Tensor Cores with native FP16 support, offering 8× the throughput of FP32 matrix multiplications. Micikevicius et al. [40] (2018) demonstrated that mixed-precision training, using FP16 for most operations while keeping a master copy of weights in FP32, achieved 2× speedup with no accuracy loss across a range of tasks. The A100 GPU (2020) added BF16 (bfloat16) support, a format that trades precision for range, and BF16 quickly became the default for large language model training. The H100 GPU (2022) introduced FP8 Tensor Cores, and FP8 training is now an active area of research, promising yet another 2× throughput improvement.

The progression from FP32 to FP16 to BF16 to FP8 represents one of the most impactful “free lunches” in deep learning: the same model, the same algorithm, the same accuracy, just faster and cheaper.

Floating Point Formats

Definition 41 (IEEE Floating Point Formats).

A floating-point number is represented as (FP Format)x=(1)s×2ebias×(1+m/2p), where s{0,1} is the sign bit, e is the exponent (an unsigned integer), bias is a format-dependent offset, m is the mantissa (significand), and p is the number of mantissa bits. The key formats used in deep learning are:

FormatSignExponentMantissaRangePrecision
FP321823±3.4×10387 decimal digits
FP161510±65,5043.3 decimal digits
BF16187±3.4×10382.4 decimal digits
FP8 E4M3143±4481.4 decimal digits
FP8 E5M2152±57,3441.0 decimal digit

The critical trade-off is between range (determined by the number of exponent bits) and precision (determined by the number of mantissa bits). FP16 has more mantissa bits than BF16 (10 vs. 7), giving it better precision, but FP16's 5-bit exponent limits its range to ±65,504. BF16 has the same 8-bit exponent as FP32, giving it the same dynamic range (±3.4×1038), at the cost of reduced precision.

For training, BF16's range advantage is decisive. Gradient values in deep networks can span many orders of magnitude, and a format that overflows at 65,504 (FP16) frequently encounters numerical issues during training of large models. BF16 never overflows in practice, making it far more robust.

Caution.

FP16 training of models with more than 1B parameters often diverges due to overflow and underflow. The maximum representable FP16 value is 65,504; any gradient or activation exceeding this value overflows to infinity, corrupting the entire training run. Conversely, gradients smaller than 2246×108 underflow to zero, causing many parameters to stop learning. For large-scale training, use BF16 or FP16 with loss scaling (see below).

Mixed Precision Training

Definition 42 (Mixed Precision Training).

Mixed precision training [40] maintains a master copy of the model parameters in FP32 and performs forward and backward passes in a lower precision format (FP16 or BF16). The training loop proceeds as follows:

  1. Cast: copy the FP32 weights 𝜽 to reduced precision 𝜽16.

  2. Forward: compute the loss =(f(𝒙;𝜽16)) in reduced precision.

  3. Loss in FP32: cast the scalar loss to FP32 for numerical stability.

  4. Backward: compute gradients 𝒈16 in reduced precision.

  5. Update: cast gradients to FP32 and update the master weights: 𝜽𝜽η𝒈32.

Why keep master weights in FP32? The issue is precision of accumulation. When the learning rate is small (e.g., η=104) and the gradient is also small, the update ηg may be smaller than the FP16/BF16 precision at the scale of the weight. Concretely, if a weight w=100 and the update is Δw=105, FP16 cannot represent 100+0.00001100 because the mantissa only has 10 bits of precision. In FP32, the 23-bit mantissa resolves this fine difference.

Definition 43 (Mixed Precision Training Loop with Loss Scaling).

  1. Input: model parameters 𝜽 (FP32), loss scale S.

  2. 𝜽16cast(𝜽,FP16).

  3. forward(𝜽16,𝒙) [FP16 compute]

  4. scaledS [scale up to prevent gradient underflow]

  5. 𝒈16backward(scaled) [FP16 gradients]

  6. 𝒈32cast(𝒈16,FP32)/S [unscale in FP32]

  7. 𝜽𝜽η𝒈32 [FP32 update]

Proposition 16 (Memory Savings of Mixed Precision).

Mixed precision training with FP16/BF16 activations reduces activation memory by approximately 50% compared to FP32, and enables 2× throughput on tensor cores that natively support reduced-precision matrix multiplications.

Proof.

Each FP16/BF16 value requires 2 bytes vs. 4 bytes for FP32, yielding a 2× reduction in memory for activations and temporary buffers. The master weights in FP32 add 4N bytes (where N is the parameter count), and the FP16 copy adds 2N bytes, for a total parameter memory of 6N bytes. However, for large models, activation memory dominates parameter memory (especially with long sequences), so the net saving approaches 50%.

The throughput gain comes from GPU tensor cores: NVIDIA A100 tensor cores achieve 312 TFLOPS in FP16/BF16 vs. 156 TFLOPS in FP32 (TF32), a 2× improvement. H100 tensor cores further improve this to 989 TFLOPS in FP16 vs. 495 TFLOPS in TF32.

Loss Scaling

Definition 44 (Dynamic Loss Scaling).

FP16 gradients smaller than 2246×108 underflow to zero, causing the corresponding parameters to stop receiving gradient updates. Loss scaling addresses this by multiplying the loss by a large factor S before the backward pass, which shifts all gradients into the representable range, and then dividing by S after casting to FP32: (LOSS Scaling)𝒈32=1Scast(𝜽16(S),FP32). Dynamic loss scaling adapts S during training:

  1. Initialise S=224 (a large value).

  2. If any gradient is inf or NaN (overflow detected): skip the update and halve S.

  3. If N consecutive steps (e.g., N=2000) pass without overflow: double S.

Dynamic loss scaling is automatic: the scale S self-adjusts to keep gradients in the representable range of FP16 without requiring any manual tuning. Note that with BF16 training, loss scaling is typically unnecessary because BF16's large dynamic range prevents both overflow and most underflow.

Gradient Clipping

Large gradient norms, caused by outlier examples, loss spikes, or numerical instability, can destabilise training. Gradient clipping constrains the gradient magnitude before the parameter update.

Definition 45 (Gradient Clipping by Norm).

Given a gradient vector 𝒈N and a clipping threshold c>0, the clipped gradient is (GRAD CLIP)𝒈=𝒈min(1,c𝒈).

Proposition 17 (Clipping Preserves Gradient Direction).

Gradient clipping by norm preserves the gradient direction: 𝒈/𝒈=𝒈/𝒈. Only the magnitude is affected: 𝒈=min(𝒈,c).

Proof.

There are two cases:

  1. If 𝒈c: then min(1,c/𝒈)=1, so 𝒈=𝒈. Direction and magnitude are unchanged.

  2. If 𝒈>c: then 𝒈=𝒈c/𝒈. The direction is 𝒈/𝒈=(𝒈c/𝒈)/(c)=𝒈/𝒈, which is identical to the original direction. The magnitude is 𝒈=c𝒈/𝒈=c.

In both cases, 𝒈/𝒈=𝒈/𝒈, and 𝒈=min(𝒈,c).

Remark 41.

Most large language model training runs use gradient clipping with c=1.0. This is a conservative choice that rarely clips during normal training (typical gradient norms are well below 1.0 for well-initialised models with proper learning rate schedules) but provides a safety net against the occasional gradient spike that could otherwise cause a loss divergence. Gradient clipping is particularly important when combined with mixed precision training, where reduced-precision gradients are more susceptible to numerical outliers.

Gradient Accumulation

Modern training often requires large effective batch sizes for stable convergence, but GPU memory may only accommodate a small batch. Gradient accumulation bridges this gap by spreading a single optimiser step across multiple forward-backward passes.

Definition 46 (Gradient Accumulation).

To simulate an effective batch size Beff=KB using micro-batches of size B, accumulate gradients over K micro-batches before performing a single parameter update: (GRAD Accum)𝒈accum=1Kk=1K(𝜽;𝒙k), where 𝒙k is the k-th micro-batch. The parameter update is then 𝜽𝜽η𝒈accum.

Proposition 18 (Equivalence to Large-Batch Training).

Gradient accumulation over K independent micro-batches of size B produces the same expected gradient as a single batch of size KB: (GRAD Accum Equiv)𝔼[𝒈accum]=𝔼[(𝜽;𝒙)]=𝔼[𝒈large-batch]. Moreover, if the micro-batches are drawn independently, the variances are identical: 𝖵ar(𝒈accum)=𝖵ar(𝒈large-batch).

Proof.

By linearity of expectation: 𝔼[𝒈accum]=1Kk=1K𝔼[(𝜽;𝒙k)]=1KK𝔼[(𝜽;𝒙)]=𝔼[(𝜽;𝒙)]. This is identical to the expected gradient of a single batch of any size, since the expectation is taken over the data distribution.

For the variance, the accumulated gradient over K i.i.d. micro-batches of size B is the mean of KB i.i.d. per-example gradients: 𝒈accum=1KBi=1KBi. A single large batch of size KB computes 𝒈large=1KBi=1KBi. These are the same sum, so 𝖵ar(𝒈accum)=𝖵ar(𝒈large)=σ2/(KB), where σ2 is the per-example gradient variance.

Floating-point bit layouts for formats used in deep learning. FP32 (32 bits): the traditional default, with high precision and range. FP16 (16 bits): higher precision than BF16 but limited range (±65,504). BF16 (16 bits): same range as FP32, reduced precision, the preferred format for LLM training. FP8 E4M3 (8 bits): emerging format for next-generation training on Hopper GPUs. The key trade-off: more exponent bits increase range, more mantissa bits increase precision.

Key Idea.

Modern LLM training runs in BF16 with FP32 master weights, the best of both worlds. BF16 provides 2× throughput and 2× memory savings for forward and backward passes, while the FP32 master weights ensure that tiny gradient updates are not lost to reduced-precision rounding. Combined with gradient clipping (to prevent outlier gradients from destabilising training) and gradient accumulation (to simulate large batch sizes on limited hardware), this low-precision recipe enables training of models with hundreds of billions of parameters on clusters of commodity GPUs. The lesson is clear: precision is a resource to be managed, not an absolute requirement. Use just enough precision where it matters (weight updates) and economise everywhere else (activations, gradients).

Trick #11 - Distill Knowledge

A large model trained for weeks on thousands of GPUs captures an extraordinary amount of knowledge, not merely the mapping from inputs to correct labels, but the relative confidences across all possible outputs. When a vision model assigns probabilities [0.7,0.2,0.1] to the classes [cat, lynx, dog], the non-zero probability on “lynx” encodes a structural similarity between cats and lynxes that the hard label [1,0,0] entirely discards. Knowledge distillation is the art of transferring this richer signal from a large teacher to a small student.

Historical Note.

Hinton's “dark knowledge” (2015). The idea of model compression via soft targets dates to Bucilua et al. (2006) [41], but the modern formulation is due to Hinton, Vinyals, and Dean (2015) [42], who coined the evocative term dark knowledge: “The knowledge is not just in the hard labels; it is in the relative probabilities of incorrect classes.” A teacher's output [0.7,0.2,0.1] tells the student that class 2 is more similar to class 1 than class 3 is. This “dark knowledge” is lost when training on hard labels [1,0,0]. By raising the softmax temperature, even tiny probabilities become visible, revealing the full geometry of the teacher's learned representation.

The distillation objective

The core idea is simple: train the student to match both the true labels and the teacher's soft predictions.

Definition 47 (Knowledge Distillation).

Let 𝒛sK and 𝒛tK denote the logits of a student network and a teacher network, respectively, for a K-class classification problem. The knowledge distillation loss is (KD LOSS)KD=(1α)CE(σ(𝒛s),𝒚)+αT2DKL(σ(𝒛t/T)σ(𝒛s/T)), where σ() is the softmax function, 𝒚 is the one-hot ground truth, T>0 is the temperature parameter, α[0,1] is the interpolation weight, and DKL(pq)=kpklog(pk/qk) is the Kullback–Leibler divergence. The first term trains the student on hard labels; the second aligns it with the teacher's softened predictions.

The temperature T controls the “softness” of the probability distribution. At T=1, we recover the standard softmax; as T, the distribution approaches uniform, revealing the full ranking over classes. The factor T2 in (KD LOSS) is not arbitrary; it compensates for the gradient scaling introduced by the temperature.

Proposition 19 (Temperature and Gradient Scaling).

As T, the softened targets σ(𝒛/T) approach the uniform distribution 1/K. The gradient of the KL term with respect to the student logits scales as DKL/zsk1/T for large T, which is compensated by the T2 prefactor, yielding an effective learning signal of order O(T).

Proof.

For large T, a first-order expansion gives σk(𝒛/T)=ezk/Tjezj/T1K(1+zkKT1KjzjT)=1K(1+zkzKT), where z=1Kjzj. Substituting into the KL divergence, DKL(σ(𝒛t/T)σ(𝒛s/T))12KT2k=1K(ztkzsk)2. Taking the gradient with respect to zsk: DKLzskzskztkKT2. Multiplying by T2, the effective gradient becomes (zskztk)/K, which is independent of T. Thus the T2 factor ensures a stable learning signal regardless of temperature.

Remark 42.

In practice, T[2,20] works well. Small T preserves the teacher's sharp predictions (useful when the teacher is highly confident); large T reveals fine-grained inter-class similarities (useful when classes are semantically related, e.g., fine-grained visual recognition).

Self-distillation and Born-Again Networks

A surprising finding: distillation improves performance even when the student has the same architecture as the teacher.

Definition 48 (Self-Distillation).

Self-distillation trains a student with the same architecture as the teacher. Starting from a trained model f𝜽0, each generation trains a new model by minimising the distillation loss: (SELF Distill)𝜽n+1=arg min𝜽KD(f𝜽,f𝜽n). Furlanello et al. (2018) [43] showed that Born-Again Networks, students identical to their teachers, consistently outperform the teacher, often by 0.51.5% accuracy on ImageNet.

Remark 43.

Why does self-distillation help? The teacher's soft labels act as a form of label smoothing (Trick #8 - Regularize Creatively) and implicit data augmentation: each training example carries K soft targets instead of a single hard label, effectively multiplying the information per sample. The teacher also provides a form of curriculum: early in training, the student receives well-calibrated targets that are easier to learn from than noisy hard labels.

Online distillation

Classical distillation requires a pre-trained teacher. Online distillation removes this requirement by training teacher and student simultaneously.

Definition 49 (Deep Mutual Learning).

In deep mutual learning [44], two (or more) networks f1,f2 train simultaneously, each distilling from the other. The losses are (Mutual1)1=CE(𝒑1,𝒚)+DKL(𝒑2𝒑1),2=CE(𝒑2,𝒚)+DKL(𝒑1𝒑2), where 𝒑i=σ(𝒛i) is the softmax output of network i. No pre-trained teacher is needed; the networks learn collaboratively, each providing complementary dark knowledge to the other.

Remark 44.

Remarkably, deep mutual learning improves both networks relative to training each independently, even when both networks have the same architecture and capacity. The KL terms encourage the networks to agree, which acts as a consensus regulariser that reduces overfitting and explores a broader set of good solutions.

Distillation at scale

Insight.

Distillation as the deployment pipeline. Distillation is the primary mechanism by which frontier model knowledge flows into small, deployable models. GPT-4 knowledge is distilled into Phi-series models; LLaMA-70B is distilled into LLaMA-8B variants; PaLM-540B is distilled into Gemma-2B. In the modern LLM ecosystem, distillation is not an afterthought; it is the deployment strategy [41].

Key Idea.

Why distillation works. The teacher provides a richer learning signal than labels alone: inter-class similarities (dark knowledge), confidence calibration (soft targets reveal uncertainty), and implicit data augmentation (each example carries K targets instead of one). The student learns not just what the teacher predicts but how certain the teacher is, and the uncertainty itself carries structural information about the task.

For large language models, distillation takes a different form. The student is typically trained on the teacher's generated text rather than its logit distributions, because logit-level access to frontier models is often unavailable. This is sometimes called black-box distillation: the student learns from the teacher's outputs without access to its internal representations.

Remark 45.

Distillation introduces a trade-off: the cost of running the teacher on the training set (or generating training data) is amortized over all future deployments of the smaller student. For a model that will serve millions of inference requests, even expensive teacher computation is worthwhile.

Trick #12 - Quantize Aggressively

Modern neural networks are trained in 32-bit or 16-bit floating point, but inference, and increasingly training, can be performed with far fewer bits. Quantization reduces the numerical precision of weights and/or activations, yielding smaller models, faster computation, and lower energy consumption. The challenge is to do so without destroying accuracy.

Historical Note.

From 32-bit “standard” to 1-bit extreme. For decades, 32-bit floating point (FP32) was the unquestioned standard for neural network training. The journey to lower precision has been remarkably swift:

  • 2018: INT8 inference becomes practical for CNNs, with less than 0.1% accuracy loss [45].

  • 2022: GPTQ [46] enables 4-bit LLM inference without fine-tuning, making 175B-parameter models runnable on consumer hardware.

  • 2023: AWQ [47] and QLoRA [48] make quantization accessible for both inference and fine-tuning.

  • 2024: FP8 training on NVIDIA Hopper GPUs achieves near-FP16 training quality at 2× throughput.

Post-training quantization

The simplest approach is to quantize a pre-trained model without further training. The key design choice is the mapping from continuous to discrete values.

Definition 50 (Uniform Quantization).

Given a real-valued tensor x and a target bit-width b, the uniform quantization function is (Quant)Q(x)=clip(xs+z,0,2b1), where denotes rounding to the nearest integer, s is the scale factor, and z is the zero-point. The dequantization recovers an approximation: x^=s(Q(x)z). Two common schemes:

  1. Asymmetric: s=(xmaxxmin)/(2b1), z=xmin/s.

  2. Symmetric: z=0, s=max(|x|)/(2b11).

Quantization can be applied per-tensor (one s,z for the entire weight matrix) or per-channel (different sc,zc for each output channel c), with per-channel providing finer granularity at negligible overhead.

The quantization error ϵ=xx^ introduces noise that accumulates through layers. The art of post-training quantization lies in minimising the impact of this accumulated error.

GPTQ: Optimal Brain Quantization

Naïve rounding quantizes each weight independently, ignoring correlations. GPTQ uses second-order information to quantize weights optimally.

Definition 51 (GPTQ).

Given a weight matrix 𝑾dout×din and a calibration input matrix 𝑿din×N, GPTQ [46] minimises the layer-wise reconstruction error: (GPTQ)min𝑾^𝑾𝑿𝑾^𝑿F2. Weights are quantized column-by-column. For column j:

  1. Compute the quantized weight: w^j=Q(wj).

  2. Compute the quantization error: δj=wjw^j.

  3. Compensate by updating remaining columns: (GPTQ Update)𝑾:,j+1:𝑾:,j+1:+δj[𝑯1]j,j+1:[𝑯1]jj, where 𝑯=2𝑿𝑿 is the Hessian of the Optimal Brain Surgeon (OBS) objective.

The inverse Hessian 𝑯1 is computed once via Cholesky decomposition, yielding overall complexity O(din2drow) per row group.

Remark 46.

GPTQ can quantize a 175B-parameter model to 4-bit precision in approximately 4 hours on a single GPU, because it processes one layer at a time (requiring only that layer's weights and calibration activations in memory). The resulting 4-bit model fits in 87.5 GB, runnable on a pair of 48,GB GPUs.

AWQ: Activation-Aware Weight Quantization

GPTQ modifies weights after quantization. AWQ takes a complementary approach: it protects important weights before quantization.

Definition 52 (Activation-Aware Weight Quantization).

AWQ [47] observes that not all weights are equally important: weights connected to high-magnitude activations cause disproportionate error when quantized. The solution is per-channel scaling before quantization: (AWQ)𝑾^=Q(𝑾diag(𝒔)),sj=(max|𝑿j|)α(max|𝑾:,j|)1α, where 𝑿j denotes the j-th channel of the calibration activations and α[0,1] is optimised by grid search. The scaling sj enlarges channels with large activations (making them more robust to rounding) and shrinks channels with small activations (where quantization error matters less).

Remark 47.

AWQ preserves approximately 1% more accuracy than GPTQ at the same bit-width on language modelling benchmarks, while being faster to apply (no iterative column-by-column updates). In practice, AWQ and GPTQ are complementary and can be combined.

QLoRA: Quantize and fine-tune

Quantization is not only for inference. QLoRA enables fine-tuning of quantized models by keeping the base model frozen in low precision and training only small adapter modules.

Definition 53 (QLoRA).

QLoRA [48] combines aggressive quantization with parameter-efficient fine-tuning:

  1. Quantize: convert the base model to 4-bit NormalFloat (NF4), a data type optimised for normally distributed weights: NF4 levels=Φ1(i+0.516),i=0,,15, where Φ1 is the inverse normal CDF. This places quantization levels where weights are most dense.

  2. Adapt: add LoRA adapters (low-rank matrices 𝑨d×r, 𝑩r×d with rd) in FP16.

  3. Train: optimise only the LoRA parameters; the base model stays frozen in 4-bit.

  4. Double quantization: quantize the quantization constants themselves (scales s) to 8-bit, saving an additional 0.37 bits per parameter.

Memory: 4-bit base + 16-bit LoRA enables fine-tuning a 65B-parameter model on a single 48 GB GPU.

Uniform quantization of a normally distributed weight tensor. Vertical lines show quantization bin boundaries for INT8 (green dashed, 256 bins) and INT4 (red solid, 16 bins). INT4 has far fewer bins, leading to larger rounding errors, especially in the tails where outlier weights reside.

Remark 48.

The relationship between bit-width and accuracy is not linear. Empirically, going from FP16 to INT8 incurs <0.1% accuracy loss for most models. Going from INT8 to INT4 incurs 0.52% loss without careful calibration (GPTQ/AWQ), but only 0.10.5% with it. Going below INT4 (e.g., INT2 or binary) typically requires quantization-aware training and incurs significant degradation on complex tasks.

Caution.

Outliers are the enemy of quantization. Quantization errors are not uniform across weights. Outlier weights, values far from the mean, cause disproportionate degradation because the quantization grid must span the full range, reducing resolution in the dense central region. A single outlier channel with magnitude 10× the mean can halve the effective precision of the entire tensor. Always calibrate on representative data, and consider per-channel or per-group quantization to isolate outlier channels.

Key Idea.

The quantization toolkit. Post-training quantization (PTQ) methods like GPTQ and AWQ reduce model size by 48× with minimal accuracy loss, making LLMs deployable on consumer hardware. QLoRA extends this to fine-tuning, enabling personalisation of massive models on a single GPU. The key principle: not all weights are equal; protect the important ones (high-activation channels, outlier values) and compress the rest.

Trick #13 - Prune and Route

Two complementary ideas address the same question from opposite directions. Pruning asks: “Can we make a trained network smaller without losing accuracy?” Mixture of Experts (MoE) asks: “Can we make a network conditionally larger, using different subsets of parameters for different inputs?” Together, they represent the modern approach to parameter efficiency: use many parameters for capacity, but activate only a few for any given input.

Historical Note.

From brain damage to conditional computation. Pruning dates to LeCun et al.'s “Optimal Brain Damage” (1990), which removed weights based on second-order sensitivity. Han et al. (2015) [49] revived pruning for deep networks, achieving 9× compression on AlexNet. Meanwhile, the Mixture of Experts concept was introduced by Jacobs et al. (1991) for shallow networks and scaled to deep learning by Shazeer et al. (2017) [50] with the Sparsely-Gated MoE layer. The convergence of these ideas in modern LLMs (Mixtral [51], DeepSeek-V3 [52], Switch Transformers [53]) has made conditional computation the dominant paradigm for scaling beyond a trillion parameters.

Magnitude pruning

The simplest pruning criterion: remove weights with the smallest magnitudes, on the assumption that small weights contribute least to the output.

Definition 54 (Magnitude Pruning).

Given trained weights 𝑾, create a binary mask (Prune MASK)𝑴=𝟙[|𝑾|>τ], where τ is a threshold (typically chosen to achieve a target sparsity level s, so that τ is the s-th quantile of |𝑾|). The pruned model uses weights 𝑾=𝑴𝑾. Two granularities:

  1. Unstructured pruning: individual weights are zeroed, yielding sparse matrices.

  2. Structured pruning: entire neurons, channels, or attention heads are removed, yielding smaller dense matrices.

Remark 49.

Unstructured pruning can reach 90%+ sparsity with <1% accuracy loss on many tasks. However, exploiting unstructured sparsity requires hardware support for sparse matrix operations (e.g., NVIDIA's sparse tensor cores support 2:4 structured sparsity at 2× throughput). Structured pruning yields immediate speedups on standard hardware but typically tolerates less compression.

The Lottery Ticket Hypothesis

Pruning raises a deeper question: does a dense network need all those parameters, or does it contain a small subnetwork that could have learned just as well from the start?

Theorem 2 (Lottery Ticket Hypothesis).

(Frankle & Carbin, 2019 [54].) A randomly initialised dense network contains a subnetwork (the “winning ticket”) that, when trained in isolation with the same initialisation, achieves comparable accuracy to the full network in at most the same number of training iterations.

Formally, let f(𝒙;𝜽0) be a dense network with random initialisation 𝜽0d. There exists a mask 𝒎{0,1}d with 𝒎0d such that training f(𝒙;𝒎𝜽0) for T steps achieves test accuracy that of training f(𝒙;𝜽0) for T steps.

Algorithm 1 (Iterative Magnitude Pruning (IMP)).

The standard algorithm for finding lottery tickets:

  1. Randomly initialise the network: 𝜽0.

  2. Train to convergence: 𝜽0𝜽T.

  3. Prune p% of weights with smallest |𝜽T|: 𝒎=𝟙[|𝜽T|>quantilep(|𝜽T|)].

  4. Reset remaining weights to their original values: 𝜽=𝒎𝜽0.

  5. Repeat from step (b) with 𝜽 until the desired sparsity is reached.

Each round prunes p% of the surviving weights, so after k rounds the network retains (1p/100)k of its original parameters.

Remark 50.

Finding lottery tickets is computationally expensive: IMP requires full training for each pruning round. For a target sparsity of 90% with p=20% per round, this requires log(0.1)/log(0.8)=11 rounds of full training. Research on efficient ticket-finding (e.g., early-bird tickets, one-shot pruning) aims to reduce this cost.

Mixture of Experts

Rather than making a network smaller, MoE makes it conditionally larger: the total parameter count grows, but each input activates only a small subset of “expert” sub-networks.

Definition 55 (Mixture of Experts Layer).

A Mixture of Experts layer with N experts computes (MOE)𝒚=iTopK(𝒈(𝒙),k)gi(𝒙)Ei(𝒙), where:

  • 𝒈(𝒙)=softmax(𝑾g𝒙)N is the gating (or router) network,

  • Ei:dd is the i-th expert (typically a feedforward network),

  • TopK(𝒈,k) returns the indices of the k largest entries of 𝒈,

  • gi(𝒙) is re-normalised over the selected experts.

Total parameters: N|E|+|g|. Active parameters per token: k|E|+|g| with kN.

A critical challenge in MoE training is expert collapse: the router learns to send most tokens to a few experts, leaving others untrained. The standard remedy is an auxiliary load-balancing loss.

Definition 56 (Load Balancing Loss).

The auxiliary load-balancing loss encourages uniform expert utilisation: (LOAD Balance)aux=αNi=1Nfipi, where fi is the fraction of tokens routed to expert i in the current batch, pi is the average routing probability for expert i (averaged over tokens), and α is a small coefficient (typically α=0.01). This loss is minimised when fi=pi=1/N for all i (uniform routing).

Remark 51.

Switch Transformer [53]: uses k=1 (a single expert per token), the simplest possible routing. This minimises communication overhead in distributed settings and simplifies the load-balancing problem. Despite its simplicity, Switch Transformers achieve 47× speedups over dense models at the same compute budget.

Remark 52.

Mixtral [51]: uses k=2 experts selected from N=8 per MoE layer. Total parameters: 46.7B. Active parameters per token: 12.9B. This 3.6× parameter efficiency enables Mixtral-8x7B to match or exceed LLaMA-2-70B on most benchmarks while using only 13B active parameters.

Remark 53.

DeepSeek-MoE [52]: introduces shared experts alongside routed experts. Some experts are always active (encoding shared knowledge common to all tokens), while others are conditionally selected. This hybrid design reduces the burden on the router and stabilises training.

Proposition 20 (MoE Capacity-Compute Trade-off).

For an MoE layer with N experts of size |E| and top-k routing, the ratio of total parameters to active parameters is (MOE Ratio)ρ=N|E|+|g|k|E|+|g|Nk(when |E||g|). This means a model can have N/k times more parameters than a dense model of equal computational cost. For Mixtral (N=8, k=2), ρ4; for Switch (N=128, k=1), ρ128. The larger ρ, the greater the capacity per FLOP, but also the greater the memory footprint and communication overhead in distributed settings.

Mixture of Experts routing. Input tokens pass through a learned router that selects the top-K experts (here K=2). Inactive experts (grey) consume no compute. The output for each token is the weighted combination of its selected experts' outputs.

Trick #14 - Cache and Decode Faster

KV caching (Definition 16) and parallel attention+FFN blocks (Definition 21) were covered in the Transformer chapter. Here we turn to techniques that address the fundamental autoregressive bottleneck: generating one token at a time is inherently sequential.

Historical Note.

The autoregressive bottleneck. A language model generating a 100-token response must perform 100 serial forward passes, each waiting for the previous token. On modern hardware, each pass is memory-bandwidth bound (not compute-bound) during decoding, because the batch size is typically one token. The GPU's thousands of cores sit largely idle, waiting for data to arrive from memory. The quest: generate multiple tokens per step without changing the output distribution.

Speculative decoding

The key insight: use a small, fast model to draft several tokens, then verify them all at once with the large model. Because verification of K tokens costs roughly the same as generating one (a single forward pass over K positions), we get a K× speedup when most drafts are accepted.

Definition 57 (Speculative Decoding).

Let Mdraft be a small, fast draft model and Mtarget be the large target model. Speculative decoding [55] proceeds as follows:

  1. Draft: Mdraft generates K candidate tokens x1,,xK autoregressively.

  2. Verify: Mtarget computes logits for all K positions in a single forward pass (exploiting KV caching and parallel computation).

  3. Accept/Reject: for each position i=1,,K, accept xi with probability (SPEC Accept)min(1,ptarget(xi|x<i)pdraft(xi|x<i)).

  4. If xi is rejected, resample from the adjusted distribution (SPEC Resample)padj(x)=max(0,ptarget(x|x<i)pdraft(x|x<i))xmax(0,ptarget(x|x<i)pdraft(x|x<i)) and discard all subsequent draft tokens.

The crucial property of speculative decoding is that it produces exactly the same output distribution as the target model.

Proposition 21 (Speculative Decoding Correctness).

The output distribution of speculative decoding is identical to that of the target model Mtarget.

Proof.

This is a Metropolis–Hastings-style rejection sampling scheme. For any token x at position i, the marginal probability under speculative decoding is: pspec(x)=pdraft(x)min(1,ptarget(x)pdraft(x))+padj(x)xpdraft(x)max(0,1ptarget(x)pdraft(x)). Case 1: ptarget(x)pdraft(x). The acceptance probability is 1, contributing pdraft(x). The resampling contributes the remaining ptarget(x)pdraft(x) (from the adjusted distribution). Total: ptarget(x).

Case 2: ptarget(x)<pdraft(x). The acceptance probability is ptarget(x)/pdraft(x), contributing ptarget(x). The resampling assigns zero probability to x (since ptarget(x)pdraft(x)<0). Total: ptarget(x).

In both cases, pspec(x)=ptarget(x).

Proposition 22 (Expected Speedup).

If the per-token acceptance rate is α (i.e., each drafted token is accepted with probability α, independently), the expected number of accepted tokens per verification step is (SPEC Expected)𝔼[n]=1αK+11α, where K is the draft length.

Proof.

Let n be the number of accepted tokens (including the one generated at the rejection point). We have P(ni)=αi for iK, and the last position always generates a valid token (either accepted or resampled). Thus: 𝔼[n]=i=0KP(ni)=i=0Kαi=1αK+11α. The effective speedup over standard decoding is approximately Speedup𝔼[n]1+K(cdraft/ctarget), where cdraft and ctarget are the per-token costs of the draft and target models, respectively.

Remark 54.

With α0.8 and K=5: 𝔼[n]=(10.86)/(10.8)=(10.262)/0.23.69 accepted tokens per verification step. If the draft model costs 5% of the target model, the speedup is 3.69/(1+5×0.05)=3.69/1.252.95×.

Medusa decoding

Speculative decoding requires a separate draft model. Medusa eliminates this requirement by adding prediction heads directly to the target model.

Definition 58 (Medusa Decoding).

Medusa [56] adds K extra prediction heads to the model, each predicting the k-th future token: (Medusa)pk(xt+k|xt)=softmax(𝑾k𝒉t),k=1,,K, where 𝒉t is the hidden state at position t and 𝑾kV×d is the k-th head's projection. At each step:

  1. Generate K+1 candidate tokens: one from the original head (position t+1) and K from the Medusa heads (positions t+2,,t+K+1).

  2. Construct a candidate tree from the top-m predictions of each head.

  3. Verify all candidates with a single forward pass using tree attention: attention masks are structured so that each candidate attends only to its ancestors in the tree.

  4. Accept the longest prefix that matches the target model's predictions.

No separate draft model is needed; the target model does both drafting and verification.

Weight tying

A simple but effective trick that reduces parameters and improves performance simultaneously.

Definition 59 (Weight Tying).

Set the output projection matrix equal to the transpose of the input embedding matrix [57]: (TIED Embed)𝑾output=𝑾embed. Parameter savings: dmodel×V fewer parameters, where V is the vocabulary size. For V=50,000 and dmodel=4096, this saves approximately 200M parameters (400 MB in FP16).

Remark 55.

Weight tying is essentially free: it saves memory and often improves performance by providing implicit regularisation. The intuition is that the input embedding learns to map tokens into a semantic space, and the output projection should map back to the same space, so sharing weights enforces this consistency. Nearly all modern language models use weight tying.

Speculative decoding flow. The draft model generates 5 candidate tokens autoregressively. The target model verifies all 5 in a single forward pass. Tokens 1–3 are accepted (green); token 4 is rejected (red); the resampled token (amber) is drawn from the adjusted distribution. Net result: 4 tokens generated with one target model forward pass.

Key Idea.

Lossless speedup. Speculative decoding is the only inference trick that provides a strict speedup with zero quality loss: the output distribution is mathematically identical to that of the target model. Every other speed optimisation (quantization, pruning, distillation) trades quality for speed; speculative decoding trades draft model compute for target model parallelism.

Trick #15 - Combine Tricks Synergistically

No trick works in isolation. The power of the techniques covered in Trick #1 - Initialize WiselyTrick #14 - Cache and Decode Faster lies not in any single trick but in their synergistic combination. A modern large language model is a carefully composed symphony of 10+ tricks working in concert, each addressing a specific failure mode while remaining compatible with the others.

Key Idea.

The meta-trick. The modern LLM is not a single trick but a carefully composed symphony of 10+ tricks working together. The art of deep learning engineering is knowing which tricks to combine, in what order, and how they interact. A poor combination (e.g., BatchNorm + Pre-norm + ReZero) is redundant; a good combination (e.g., RMSNorm + SwiGLU + RoPE + GQA + Flash Attention) is greater than the sum of its parts.

Model recipe analysis

Table 5 shows which tricks are used by several prominent LLMs. The convergence on a common “recipe” is striking: nearly all models use pre-norm RMSNorm, SwiGLU activations, RoPE positional encoding, and some form of efficient attention.

TrickLLaMA-2Qwen-2.5DeepSeek-V3MistralGPT-4
InitHeHeHeHeHe
GatingSwiGLUSwiGLUSwiGLUSwiGLU(unknown)
NormRMSNormRMSNormRMSNormRMSNormLayerNorm
(pre)(pre)(pre)(pre)(pre)
SkipResidualResidualmHCResidualResidual
ActivationSiLUSiLUSiLUSiLU(unknown)
PositionRoPERoPERoPERoPE(unknown)
AttentionGQAGQAMLAGQA(unknown)
Regularise--DropPath-(unknown)
LRCosineCosineWSDCosineCosine
PrecisionBF16BF16BF16+FP8BF16(unknown)
MoENoNoYesNoYes
GPT-4 architecture is not publicly disclosed; entries are community estimates.
Mixtral uses MoE; base Mistral does not.
Trick recipes for prominent LLMs. Each row indicates which variant of each trick the model uses. The convergence on a common recipe (shaded cells) is remarkable.

Interaction effects

Understanding why certain tricks compose well is as important as knowing which ones to use.

The LLaMA recipe: RMSNorm + SwiGLU + RoPE.

These three tricks compose synergistically because each operates on a different aspect of the architecture. RMSNorm is computationally cheap (no mean subtraction, no bias) and stabilises training without introducing extra parameters. SwiGLU adds expressiveness to the FFN block via learnable gating. RoPE handles position without added parameters and naturally supports length extrapolation. None interferes with the others: RMSNorm normalises activations before SwiGLU processes them, and RoPE acts only on attention queries and keys.

Pre-norm + ReZero: redundant?

Pre-norm (Trick #3 - Normalise Everything) already ensures well-behaved gradients at initialisation by normalising inputs to each sub-layer. ReZero's learnable scalar α (initialised at zero) addresses the same problem from a different angle. Combining both is redundant: if α=0 at init, the normalisation has nothing to normalise. In practice, one should choose either pre-norm (the standard) or ReZero (simpler but less common), not both.

MoE + quantization challenges.

Different experts may have different weight distributions, making a single quantization scale suboptimal. Per-expert quantization is necessary but increases the number of quantization parameters. Moreover, expert-level load imbalance means that heavily used experts accumulate more gradient noise, potentially requiring expert-specific precision settings.

Gated Attention + Flash Attention.

The element-wise gate 𝒈𝒐 in gated attention (Trick #2 - Make It Gated) is applied after the attention computation, so it adds minimal overhead to Flash Attention's IO-optimal algorithm. The two compose cleanly.

Open research directions

  1. Automatic trick discovery. Can neural architecture search (NAS) discover new tricks? Most NAS work searches over macro-architecture (layer counts, widths); searching over micro-architecture (normalisation placement, gating variants, skip-connection topology) is largely unexplored.

  2. Theoretical understanding. Why do these tricks compose well? Information-theoretic analyses of individual tricks exist (e.g., residual connections preserve mutual information with the input), but a unified theory of trick composition is lacking.

  3. Scaling laws for tricks. Do tricks help more or less at scale? Preliminary evidence suggests that some tricks (e.g., careful initialisation) matter less at scale (large models are more robust to initialisation), while others (e.g., MoE, mixed precision) matter more (they enable training at scales that would otherwise be infeasible).

  4. Hardware-aware trick design. As hardware evolves (e.g., AMD MI300, Google TPUs, Cerebras wafer-scale), the optimal trick recipe changes. Tricks optimised for NVIDIA A100s may be suboptimal on TPUs (which have different memory hierarchies and matrix unit sizes).

  5. Biological analogues. Many tricks have biological counterparts: gating in neurons (ion channel modulation), normalisation in neural populations (divisive normalisation), pruning during development (synaptic pruning in adolescence). Can biological insights suggest new tricks?

Insight.

The next breakthrough. The next breakthrough may not be a new trick but a deeper understanding of why existing tricks work together. A principled theory of trick composition would enable automatic recipe design for new architectures, new hardware, and new tasks, replacing the current approach of manual experimentation guided by intuition and precedent.

Historical Timeline

The techniques covered in this chapter emerged over four decades of research. fig:tricks:full-timeline traces their evolution, from the foundational ideas of the 1980s to the efficiency innovations of the 2020s.

A serpentine timeline of neural network tricks from 1986 to 2025. Row 1 (1986–2015): foundational ideas that made deep training possible. Row 2 (2015–2021): the Transformer era and the explosion of modern tricks. Row 3 (the refinement era): efficiency refinements for trillion-parameter models; each node is placed at its year of introduction, so a few tricks shown here, RMSNorm (2019) and SwiGLU (2020), predate this era but became standard components only within it.

Narrative: four eras of tricks

1986–2010: The dark ages.

Training deep networks was black magic. Backpropagation existed (Rumelhart et al., 1986), but networks deeper than 2–3 layers routinely failed to train. Initialisation was ad hoc (often uniform random), normalisation was non-existent, and the gradient dynamics of deep networks were poorly understood. The few practitioners who achieved results relied on extensive manual tuning and domain-specific architectures.

2010–2015: The foundations.

Three foundational tricks made deep training possible. Xavier initialisation (2010) showed that variance-preserving init enables gradient flow through many layers. Dropout (2012) provided the first effective regulariser for deep networks. Batch normalisation and residual connections (both 2015) made it possible to train networks with 100+ layers reliably. These tricks transformed deep learning from an art into a science.

2015–2020: The explosion.

The Transformer architecture (2017) [24] combined several tricks (residual connections, layer normalisation, scaled dot-product attention) into a unified framework that scaled to billions of parameters. This era saw rapid innovation: GELU activations, GLU variants, RoPE, mixed-precision training, and the Lottery Ticket Hypothesis. By 2020, the basic recipe for billion-parameter language models was established.

2020–2025: The refinement.

The challenge shifted from “can we train large models?” to “can we train and deploy them efficiently?” Flash Attention made attention IO-optimal. Grouped-query attention reduced KV cache memory. SwiGLU replaced standard FFNs. Quantization (GPTQ, AWQ, QLoRA) made LLMs runnable on consumer hardware. Speculative decoding achieved lossless speedup. RMSNorm replaced LayerNorm. Each refinement was small individually; together, they enabled the deployment of models that would have been impractical in 2020.

Historical Note.

A coherent theory of deep network design. Looking back, each trick solved a specific failure mode: Xavier init solved vanishing activations; residual connections solved vanishing gradients; normalisation solved internal covariate shift; gating solved expressiveness bottlenecks; efficient attention solved the quadratic complexity wall. Together, they form a coherent, if empirically discovered, theory of deep network design: preserve signal flow, stabilise statistics, gate information, and minimise computational waste.

Exercises

The following exercises cover all 15 tricks presented in this chapter, ranging from straightforward derivations to open-ended design problems.

Exercise 1 (Xavier Initialisation Derivation).

Consider a linear layer 𝒛=𝑾𝒙 with 𝒙nin, where Wijiid(0,σ2) and xi are i.i.d. with mean 0 and variance 𝖵ar[xi].

  1. Show that 𝖵ar[zj]=ninσ2𝖵ar[xi].

  2. Derive the condition σ2=1/nin for forward-pass variance preservation (𝖵ar[zj]=𝖵ar[xi]).

  3. Repeat the analysis for the backward pass (gradient propagation through 𝑾) to obtain σ2=1/nout.

  4. Show that the harmonic mean σ2=2/(nin+nout) balances both forward and backward passes.

Exercise 2 (He Initialisation for ReLU).

Let X𝒩(0,σ2). We wish to compute 𝔼[ReLU(X)2].

  1. Compute 𝔼[max(0,X)2]=0x21σ2πex2/(2σ2)dx and show that the result is σ2/2.

  2. Using the result from (a) and the analysis of Exercise 1, derive the He initialisation variance σ2=2/nin.

Exercise 3 (GLU Gradient Flow).

Compare gradient magnitude through a standard FFN 𝒉=σ(𝑾𝒙) and a GLU 𝒉=(𝑾1𝒙)σ(𝑾2𝒙).

  1. Compute 𝒉/𝒙 for the standard FFN. Express it in terms of 𝑾 and σ.

  2. Compute 𝒉/𝒙 for the GLU. Use the product rule for the Hadamard product to obtain two terms.

  3. Explain why the GLU gradient has a direct linear path (through 𝑾1) that survives even when the sigmoid σ saturates. Contrast this with the standard FFN, where saturation kills the gradient entirely.

Exercise 4 (Gated Attention Expressiveness).

  1. Show that the standard attention output for query i lies in conv(𝒗1,,𝒗n), the convex hull of the value vectors (since attention weights sum to 1 and are non-negative).

  2. Show that the gated attention output 𝒈i𝒐i can lie outside this convex hull when 𝒈i has entries <1 or entries with different signs.

  3. Give a concrete 2D example: let 𝒗1=(1,0), 𝒗2=(0,1), attention weights α=(0.5,0.5), and gate 𝒈=(0.3,0.8). Compute the gated output and verify it is not in conv(𝒗1,𝒗2).

Exercise 5 (GroupNorm as Interpolation).

Let GroupNorm with G groups operate on a feature map with C channels. Show that GroupNorm reduces to:

  1. LayerNorm when G=1 (all channels in a single group).

  2. InstanceNorm when G=C (each channel is its own group).

In each case, explicitly write the set of elements over which the mean and variance are computed.

Exercise 6 (DeepNorm Scaling Derivation).

In a transformer with N sub-layers using DeepNorm: 𝒙+1=LN(α𝒙+F(𝒙)), where F is initialised at scale β (i.e., 𝖵ar[F(𝒙)]=β2𝖵ar[𝒙]).

  1. Show that after N layers with the above recurrence, the expected output variance (before LN) is O(α2N+Nβ2α2(N1)).

  2. Choose α and β as functions of N so that this variance is O(1).

  3. Verify that α=(2N)1/4 and β=(8N)1/4 satisfies this condition.

Exercise 7 (Pre-Norm vs Post-Norm Gradient).

Compare gradient flow for L residual layers.

  1. Post-norm: 𝒙+1=LN(𝒙+F(𝒙)). Show that 𝒙L/𝒙 involves L applications of the LayerNorm Jacobian LN/𝒙, which can amplify or attenuate gradients.

  2. Pre-norm: 𝒙+1=𝒙+F(LN(𝒙)). Show that 𝒙L/𝒙=𝑰+(cross terms), so the gradient has a direct path through the identity, ensuring it never vanishes regardless of depth.

Exercise 8 (DenseNet Parameter Count).

A DenseNet block with L layers and growth rate k (each layer produces k feature maps).

  1. Compute the input dimension to the -th layer, given that it receives feature maps from all previous layers: d=k0+(1)k, where k0 is the initial channel count.

  2. Count the total parameters for the block, assuming each layer is a 3×3 convolution: =1L9k(k0+(1)k).

  3. Compare with a ResNet of the same depth with constant width k0+Lk. Which uses fewer parameters, and by how much?

Exercise 9 (mHC Doubly Stochastic Properties).

  1. Show that the 2×2 doubly stochastic matrices form a line segment: B2={(a1a1aa):a[0,1]}.

  2. Show that the product of two 2×2 doubly stochastic matrices is doubly stochastic.

  3. Show that B3 (the set of 3×3 doubly stochastic matrices) has exactly 6 vertices, namely the 3!=6 permutation matrices (Birkhoff's theorem).

  4. Show that the spectral norm of any doubly stochastic matrix is at most 1. Hint: the all-ones vector is an eigenvector with eigenvalue 1, and all eigenvalues have modulus 1.

Exercise 10 (Dying ReLU Probability).

Under He initialisation with 𝒘𝒩(0,(2/nin)𝑰) and b=0:

  1. Compute the probability that ReLU(𝒘𝒙+b)=0 for a random input 𝒙𝒩(0,𝑰). Hint: what is the distribution of 𝒘𝒙?

  2. After one gradient step with learning rate η on a single example (𝒙,y), compute the probability that the neuron remains dead. Discuss how this depends on η and the loss function.

Exercise 11 (SELU Fixed Point).

Let f(x)=SELU(x)=λx𝟙[x>0]+λα(ex1)𝟙[x0], with λ=1.0507 and α=1.6733.

  1. Compute 𝔼[f(X)] for X𝒩(0,1). Split the integral at x=0.

  2. Compute 𝔼[f(X)2] for X𝒩(0,1).

  3. Verify numerically that 𝔼[f(X)]0 and 𝖵ar[f(X)]1, confirming that (0,1) is a fixed point of the mean-variance map.

Exercise 12 (ALiBi vs RoPE Decay).

For a head with ALiBi slope m=21=0.5 and head dimension d=64:

  1. Compute the ALiBi attention weight modification: S(i,j)exp(m|ij|). What fraction of the unmodified weight remains at distance |ij|=10?

  2. For RoPE, show that the attention decay with distance depends on the alignment of query and key vectors, not just the distance. Write out the inner product 𝑹i𝒒,𝑹j𝒌 and identify the distance-dependent and content-dependent factors.

  3. At distance |ij|=4096, compare the ALiBi relative weight exp(0.5×4096) with a typical RoPE decay. Which mechanism provides a harder position cutoff?

Exercise 13 (NTK Scaling Derivation).

RoPE uses frequencies θi=θbase2i/d with θbase=10000. To extend from context length Ltrain to Ltarget=sLtrain:

  1. Show that naïve position interpolation (dividing positions by s) reduces all frequencies by a factor of s, including high-frequency components that were well within the training range.

  2. Explain why high-frequency components (small θi, large i) need less interpolation than low-frequency ones: they already have many cycles within Ltrain.

  3. Derive the NTK-aware scaling formula: θbase=θbasesd/(d2). Show that this interpolates the lowest-frequency component by factor s while leaving the highest-frequency component nearly unchanged.

Exercise 14 (YaRN Frequency Zones).

For d=128, Ltrain=4096, Ltarget=32768 (scale s=8):

  1. Compute the wavelength ri=Ltrain/(2πθi) for i=0,16,32,48,63.

  2. With ramp parameters αmin=1 and βmax=32, classify each frequency dimension into low/medium/high frequency zones.

  3. Compute the interpolation factor γi for each dimension: γi=0 (no change) for high frequency, γi=1 (full interpolation) for low frequency, and linear ramp for medium frequency.

Exercise 15 (Sparse Attention Complexity).

Consider combined local (window w) + strided (stride s) attention on sequence length n.

  1. Count the number of positions each token attends to: w+n/s.

  2. Show that the total complexity (over all n tokens) is O(n(w+n/s)).

  3. Choose w=s=n and show this gives O(n3/2) total complexity, subquadratic in n.

Exercise 16 (Ring Attention Communication).

For P devices, sequence length N, model dimension d, and h attention heads with dimension dk:

  1. Compute the size of KV blocks transmitted per round: each device sends K,V(N/P)×h×dk, so the message size is 2(N/P)hdk.

  2. Compute the total communication volume for P1 rounds.

  3. Compare with all-to-all communication (where every device sends its KV to every other device). Under what conditions is ring attention preferable?

Exercise 17 (Dropout as Ensemble).

Consider a 2-layer network with 2 neurons per layer and dropout rate p=0.5.

  1. Enumerate all possible sub-networks obtained by dropping neurons. How many are there? (Count the number of binary masks over 4 neurons: 24=16.)

  2. For a specific input 𝒙, compute the ensemble average 𝔼masks[fmask(𝒙)] for a simple linear network f(𝒙)=𝑾2𝑾1𝒙.

  3. Show that inference with all neurons active and weights scaled by (1p)=0.5 approximates the ensemble average.

Exercise 18 (Label Smoothing Calibration).

With smoothing parameter ε=0.1 and K=10 classes:

  1. Compute the target distribution: the correct class receives probability 1ε+ε/K; each incorrect class receives ε/K.

  2. At the optimal cross-entropy solution, the logit difference between the correct class and any incorrect class is bounded. Show that the maximum logit gap is ln(10(1ε)/ε+1)=ln(91)4.51.

  3. Compare with hard labels (ε=0), where the optimal logit for the correct class is +. Explain why bounded logits improve calibration.

Exercise 19 (Mixup as Vicinal Risk).

  1. Define the vicinal distribution for Mixup: given two training pairs (𝒙i,𝒚i) and (𝒙j,𝒚j), the virtual example is (𝒙~,𝒚~)=(λ𝒙i+(1λ)𝒙j,λ𝒚i+(1λ)𝒚j) with λBeta(α,α).

  2. Show that 𝔼[𝒚~]=(𝒚i+𝒚j)/2 when α=1 (i.e., λUniform(0,1)).

  3. Show that as α, λ0.5 with probability 1 (the Beta distribution concentrates at its mean), making Mixup a simple average of two examples.

Exercise 20 (Cosine vs Step Decay).

Compare the total “learning signal” (integral of LR over time) for cosine annealing and step decay (divide by 10 at 50% and 75% of training). Let ηmax be the peak learning rate and T the total training steps.

  1. Compute 0Tηcosine(t)dt, where ηcosine(t)=ηmax2(1+cos(πt/T)).

  2. Compute 0Tηstep(t)dt, where ηstep(t)=ηmax for t<T/2, ηmax/10 for T/2t<3T/4, and ηmax/100 for t3T/4.

  3. Which schedule provides more total gradient signal? Compute the ratio.

Exercise 21 (WSD Schedule Properties).

The Warmup-Stable-Decay (WSD) schedule maintains a constant learning rate ηmax during the “stable” phase, then decays.

  1. Show that WSD is “anytime optimal”: at any point during the stable phase, branching into a cosine decay reaching ηmin produces a valid schedule. Why is this useful for long training runs where the total duration is uncertain?

  2. Compare the total learning signal 0Tη(t)dt for WSD (with stable phase [0.1T,0.9T]) vs. cosine with the same ηmax.

  3. When would WSD be preferred over cosine? Hint: consider continual pretraining scenarios where new data arrives during training.

Exercise 22 (BF16 vs FP16 Range).

  1. Compute the maximum representable value for FP16 (1 sign, 5 exponent, 10 mantissa bits) and BF16 (1 sign, 8 exponent, 7 mantissa bits).

  2. Compute the minimum positive normal value for each format.

  3. For a gradient of magnitude 106, determine whether it underflows (falls below the minimum normal) in FP16 and BF16.

  4. Explain why BF16 is preferred for training despite having lower precision (7 vs. 10 mantissa bits): the larger exponent range (±38 decades vs. ±4.5 decades) prevents overflow and underflow during training.

Exercise 23 (Loss Scaling Factor).

  1. What is the smallest positive normal FP16 number? Show that it is 2146.1×105.

  2. If typical gradients have magnitude 105 (below the FP16 normal range), compute the minimum loss scale factor S needed to prevent underflow: S105214.

  3. If the loss scale is S=216=65536, compute the maximum gradient magnitude before overflow: gmax=65504/S. Is this a concern in practice?

Exercise 24 (Distillation Temperature).

Given teacher logits 𝒛t=(3,1,0.5):

  1. Compute softmax(𝒛t/T) for T=1,2,5,10,100. Observe how the distribution flattens as T increases.

  2. Verify that as T, the distribution approaches 1/3 (uniform over 3 classes).

  3. For the KL divergence term in the distillation loss, compute DKL/zsk at 𝒛s=𝒛t for each temperature T. Show that this gradient is zero (as expected, since the student matches the teacher).

Exercise 25 (GPTQ Error Analysis).

For a 2×2 weight matrix 𝑾=(1.30.70.21.8) and INT4 symmetric quantization with s=max(|Wij|)/(231):

  1. Compute the scale factor s=1.8/7.

  2. Quantize each weight: Q(w)=clip(w/s,7,7). Compute the quantized values and the element-wise quantization error δij=wijw^ij.

  3. Assume the Hessian 𝑯1=𝑰 (identity) for simplicity. Apply the GPTQ correction: after quantizing column 1, update column 2 as 𝑾:,2𝑾:,2+δ:,1. Show that this reduces the reconstruction error 𝑾𝑾^F.

Exercise 26 (Lottery Ticket Sparsity).

Starting with a network of N=106 parameters, IMP prunes 20% of surviving parameters each round.

  1. After k rounds, how many parameters remain? Express as N(10.2)k=1060.8k.

  2. How many rounds k are needed to reach 10% of the original parameters? Solve 0.8k=0.1.

  3. If each round requires full retraining (cost C per round), what is the total compute cost to find the 10%-sparse ticket? Compare with the cost of training the full network once.

Exercise 27 (MoE Load Balancing).

With N=8 experts and a batch of T=1000 tokens:

  1. Show that the auxiliary loss aux=Ni=1Nfipi is minimised when fi=pi=1/N for all i. Hint: use the AM-GM inequality or Lagrange multipliers, subject to fi=1 and pi=1.

  2. Compute aux when one expert receives 50% of tokens (i.e., f1=0.5, f2==f8=0.5/7) and pi=fi.

  3. Compute the gradient aux/pi and explain how it pushes the router towards uniform routing.

Exercise 28 (Speculative Decoding Speedup).

With acceptance rate α=0.85, draft length K=5, and cost ratio cdraft/ctarget=0.05:

  1. Compute 𝔼[n]=(1αK+1)/(1α). Show that 𝔼[n]4.62.

  2. Compute the cost per verification step: ctarget+Kcdraft=ctarget(1+K0.05)=1.25ctarget.

  3. Compute the effective speedup: Speedup=𝔼[n]ctarget/(ctarget+Kcdraft)=𝔼[n]/1.25.

  4. Plot the speedup as a function of α for K{3,5,8}. At what acceptance rate does speculative decoding become slower than standard decoding?

Exercise 29 (Trick Interactions).

  1. Explain why Fixup initialisation + BatchNorm is redundant: both address the problem of maintaining activation scale through deep residual networks. If BatchNorm is present, what purpose does Fixup's careful scaling serve?

  2. Explain why DropPath + ReZero could interact poorly at initialisation. With ReZero's α=0 initially, each residual branch contributes nothing; DropPath then randomly zeros out a branch that already contributes nothing. What happens to the gradient signal?

  3. Design a combination of 5 tricks for a new 1B-parameter vision model (ViT-style). For each trick, state: (i) the specific variant, (ii) why it is appropriate for this scale and modality, and (iii) how it interacts with the other chosen tricks.

Exercise 30 (Design a Novel Trick).

  1. Propose a new gating mechanism for the FFN layer that differs from GLU, SwiGLU, and GEGLU. Suggestion: consider multiplicative interactions involving more than two branches, or adaptive gating conditioned on the layer index or a running statistics estimate.

  2. Write the mathematical formulation of your proposed mechanism: 𝒉=g(𝒙;𝑾1,𝑾2,).

  3. Analyse the gradient flow through your mechanism. Specifically, compute 𝒉/𝒙 and identify whether a direct linear path exists (as in GLU).

  4. Discuss potential advantages and disadvantages compared to SwiGLU. Consider: parameter count, computational cost, gradient flow properties, and ease of implementation.

0.60.5pt

The exercises above span the full range of tricks covered in this chapter. Exercises 1–9 test foundational understanding of individual tricks; Exercises 10–16 develop quantitative analysis skills; Exercises 17–23 connect tricks to practical engineering decisions; Exercises 24–28 require numerical computation and verification; and Exercises 29–30 develop design intuition by asking you to analyse interactions and propose new ideas. Solutions to selected exercises (marked with ) are available in Appendix B.

References

  1. Efficient BackProp

    Yann LeCun, Leon Bottou, Genevieve B. Orr, Klaus-Robert Muller

    Neural Networks: Tricks of the Trade, pp. 9-50 · 1998

    BibTeX
    @incollection{lecun1998efficient,
      title={Efficient {BackProp}},
      author={LeCun, Yann and Bottou, L\'{e}on and Orr, Genevieve B. and M\"{u}ller, Klaus-Robert},
      booktitle={Neural Networks: Tricks of the Trade},
      publisher={Springer},
      pages={9--50},
      year={1998}
    }

    Book chapter

  2. Understanding the Difficulty of Training Deep Feedforward Neural Networks

    Xavier Glorot, Yoshua Bengio

    International Conference on Artificial Intelligence and Statistics (AISTATS), pp. 249-256 · 2010

    BibTeX
    @inproceedings{glorot2010understanding,
      title={Understanding the Difficulty of Training Deep Feedforward Neural Networks},
      author={Glorot, Xavier and Bengio, Yoshua},
      booktitle={International Conference on Artificial Intelligence and Statistics (AISTATS)},
      pages={249--256},
      year={2010}
    }

    Conference paper

  3. Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification

    Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun

    IEEE International Conference on Computer Vision (ICCV), pp. 1026-1034 · 2015

    BibTeX
    @inproceedings{he2015delving,
      title={Delving Deep into Rectifiers: Surpassing Human-Level Performance on {ImageNet} Classification},
      author={He, Kaiming and Zhang, Xiangyu and Ren, Shaoqing and Sun, Jian},
      booktitle={IEEE International Conference on Computer Vision (ICCV)},
      pages={1026--1034},
      year={2015}
    }

    Conference paper

  4. Tensor Programs V: Tuning Large Neural Networks via Zero-Shot Hyperparameter Transfer

    Greg Yang, Edward J. Hu, Igor Babuschkin, Szymon Sidor, Xiaodong Liu, David Farhi, Nick Ryder, Jakub Pachocki, et al.

    arXiv:2203.03466 · 2022

    BibTeX
    @misc{yang2022tensor,
      title={Tensor Programs {V}: Tuning Large Neural Networks via Zero-Shot Hyperparameter Transfer},
      author={Yang, Greg and Hu, Edward J. and Babuschkin, Igor and Sidor, Szymon and Liu, Xiaodong and Farhi, David and Ryder, Nick and Pachocki, Jakub and Chen, Weizhu and Gao, Jianfeng},
      year={2022},
      eprint={2203.03466},
      archiveprefix={arXiv},
      primaryclass={cs.LG}
    }

    Reference

  5. Exact Solutions to the Nonlinear Dynamics of Learning in Deep Linear Neural Networks

    Andrew M. Saxe, James L. McClelland, Surya Ganguli

    International Conference on Learning Representations (ICLR) · 2014

    BibTeX
    @inproceedings{saxe2013exact,
      title={Exact Solutions to the Nonlinear Dynamics of Learning in Deep Linear Neural Networks},
      author={Saxe, Andrew M. and McClelland, James L. and Ganguli, Surya},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2014}
    }

    Conference paper

  6. All You Need is a Good Init

    Dmytro Mishkin, Jiri Matas

    International Conference on Learning Representations (ICLR) · 2016

    BibTeX
    @inproceedings{mishkin2016lsuv,
      title={All You Need is a Good Init},
      author={Mishkin, Dmytro and Matas, Jiri},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2016}
    }

    Conference paper

  7. Fixup Initialization: Residual Learning Without Normalization

    Hongyi Zhang, Yann N. Dauphin, Tengyu Ma

    International Conference on Learning Representations (ICLR) · 2019

    BibTeX
    @inproceedings{zhang2019fixup,
      title={Fixup Initialization: Residual Learning Without Normalization},
      author={Zhang, Hongyi and Dauphin, Yann N. and Ma, Tengyu},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2019}
    }

    Conference paper

  8. Long Short-Term Memory

    Sepp Hochreiter, Jurgen Schmidhuber

    Neural Computation, vol. 9, no. 8, pp. 1735-1780 · 1997

    BibTeX
    @article{hochreiter1997long,
      title={Long Short-Term Memory},
      author={Hochreiter, Sepp and Schmidhuber, J{\"u}rgen},
      journal={Neural Computation},
      volume={9},
      number={8},
      pages={1735--1780},
      year={1997}
    }

    Journal article

  9. Learning Phrase Representations using RNN Encoder--Decoder for Statistical Machine Translation

    Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Dzmitry Bahdanau, Fethi Bougares, Holger Schwenk, Yoshua Bengio

    Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP), pp. 1724-1734 · 2014

    BibTeX
    @inproceedings{cho2014learning,
      title={Learning Phrase Representations using {RNN} Encoder--Decoder for Statistical Machine Translation},
      author={Cho, Kyunghyun and van Merrienboer, Bart and Gulcehre, Caglar and Bahdanau, Dzmitry and Bougares, Fethi and Schwenk, Holger and Bengio, Yoshua},
      booktitle={Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP)},
      pages={1724--1734},
      year={2014}
    }

    Conference paper

  10. Highway Networks

    Rupesh Kumar Srivastava, Klaus Greff, Jurgen Schmidhuber

    arXiv:1505.00387 · 2015

    BibTeX
    @misc{srivastava2015highway,
      title={Highway Networks},
      author={Srivastava, Rupesh Kumar and Greff, Klaus and Schmidhuber, J\"{u}rgen},
      year={2015},
      eprint={1505.00387},
      archiveprefix={arXiv},
      primaryclass={cs.LG}
    }

    Reference

  11. Language Modeling with Gated Convolutional Networks

    Yann N. Dauphin, Angela Fan, Michael Auli, David Grangier

    International Conference on Machine Learning (ICML), pp. 933-941 · 2017

    BibTeX
    @inproceedings{dauphin2017language,
      title={Language Modeling with Gated Convolutional Networks},
      author={Dauphin, Yann N. and Fan, Angela and Auli, Michael and Grangier, David},
      booktitle={International Conference on Machine Learning (ICML)},
      pages={933--941},
      year={2017}
    }

    Conference paper

  12. GLU Variants Improve Transformer

    Noam Shazeer

    arXiv preprint arXiv:2002.05202 · 2020

    BibTeX
    @article{shazeer2020glu,
      title={{GLU} Variants Improve Transformer},
      author={Shazeer, Noam},
      journal={arXiv preprint arXiv:2002.05202},
      year={2020}
    }

    Journal article

  13. Gated Attention for Large Language Models

    Zihan Qiu, Zekun Wang, Bo Zheng, Zeyu Huang, Kaiyue Wen, Songlin Yang, Rui Men, Le Yu, et al.

    Advances in Neural Information Processing Systems, vol. 38 · 2025

    BibTeX
    @inproceedings{qiu2025gated,
      title={Gated Attention for Large Language Models},
      author={Qiu, Zihan and Wang, Zekun and Zheng, Bo and Huang, Zeyu and Wen, Kaiyue and Yang, Songlin and Men, Rui and Yu, Le and Huang, Fei and Huang, Suozhi and Liu, Dayiheng and Zhou, Jingren and Lin, Junyang},
      booktitle={Advances in Neural Information Processing Systems},
      volume={38},
      year={2025}
    }

    Conference paper

  14. Highway and Residual Networks Learn Unrolled Iterative Estimation

    Klaus Greff, Rupesh Kumar Srivastava, Jurgen Schmidhuber

    International Conference on Learning Representations (ICLR) · 2017

    BibTeX
    @inproceedings{greff2017highway,
      title={Highway and Residual Networks Learn Unrolled Iterative Estimation},
      author={Greff, Klaus and Srivastava, Rupesh Kumar and Schmidhuber, J\"{u}rgen},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2017}
    }

    Conference paper

  15. Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift

    Sergey Ioffe, Christian Szegedy

    International Conference on Machine Learning (ICML), pp. 448-456 · 2015

    BibTeX
    @inproceedings{ioffe2015batch,
      title={Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift},
      author={Ioffe, Sergey and Szegedy, Christian},
      booktitle={International Conference on Machine Learning (ICML)},
      pages={448--456},
      year={2015}
    }

    Conference paper

  16. How Does Batch Normalization Help Optimization?

    Shibani Santurkar, Dimitris Tsipras, Andrew Ilyas, Aleksander Madry

    Advances in Neural Information Processing Systems (NeurIPS) · 2018

    BibTeX
    @inproceedings{santurkar2018does,
      title={How Does Batch Normalization Help Optimization?},
      author={Santurkar, Shibani and Tsipras, Dimitris and Ilyas, Andrew and Madry, Aleksander},
      booktitle={Advances in Neural Information Processing Systems (NeurIPS)},
      year={2018}
    }

    Conference paper

  17. DeepNet: Scaling Transformers to 1,000 Layers

    Hongyu Wang, Shuming Ma, Li Dong, Shaohan Huang, Dongdong Zhang, Furu Wei

    arXiv:2203.00555 · 2022

    BibTeX
    @misc{wang2022deepnet,
      title={{DeepNet}: Scaling Transformers to 1,000 Layers},
      author={Wang, Hongyu and Ma, Shuming and Dong, Li and Huang, Shaohan and Zhang, Dongdong and Wei, Furu},
      year={2022},
      eprint={2203.00555},
      archiveprefix={arXiv},
      primaryclass={cs.LG}
    }

    Reference

  18. Deep Residual Learning for Image Recognition

    Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun

    IEEE Conference on Computer Vision and Pattern Recognition (CVPR), pp. 770-778 · 2016

    BibTeX
    @inproceedings{he2016deep,
      title={Deep Residual Learning for Image Recognition},
      author={He, Kaiming and Zhang, Xiangyu and Ren, Shaoqing and Sun, Jian},
      booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
      pages={770--778},
      year={2016}
    }

    Conference paper

  19. Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs)

    Djork-Arne Clevert, Thomas Unterthiner, Sepp Hochreiter

    International Conference on Learning Representations (ICLR) · 2016

    BibTeX
    @inproceedings{clevert2015fast,
      title={Fast and Accurate Deep Network Learning by Exponential Linear Units ({ELUs})},
      author={Clevert, Djork-Arn\'{e} and Unterthiner, Thomas and Hochreiter, Sepp},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2016}
    }

    Conference paper

  20. Self-Normalizing Neural Networks

    Gunter Klambauer, Thomas Unterthiner, Andreas Mayr, Sepp Hochreiter

    Advances in Neural Information Processing Systems (NeurIPS) · 2017

    BibTeX
    @inproceedings{klambauer2017self,
      title={Self-Normalizing Neural Networks},
      author={Klambauer, G\"{u}nter and Unterthiner, Thomas and Mayr, Andreas and Hochreiter, Sepp},
      booktitle={Advances in Neural Information Processing Systems (NeurIPS)},
      year={2017}
    }

    Conference paper

  21. Gaussian Error Linear Units (GELUs)

    Dan Hendrycks, Kevin Gimpel

    arXiv:1606.08415 · 2016

    BibTeX
    @misc{hendrycks2016gaussian,
      title={Gaussian Error Linear Units ({GELUs})},
      author={Hendrycks, Dan and Gimpel, Kevin},
      year={2016},
      eprint={1606.08415},
      archiveprefix={arXiv},
      primaryclass={cs.LG}
    }

    Reference

  22. Searching for Activation Functions

    Prajit Ramachandran, Barret Zoph, Quoc V. Le

    arXiv:1710.05941 · 2017

    BibTeX
    @misc{ramachandran2017searching,
      title={Searching for Activation Functions},
      author={Ramachandran, Prajit and Zoph, Barret and Le, Quoc V.},
      year={2017},
      eprint={1710.05941},
      archiveprefix={arXiv},
      primaryclass={cs.NE}
    }

    Reference

  23. Mish: A Self Regularized Non-Monotonic Activation Function

    Diganta Misra

    arXiv:1908.08681 · 2019

    BibTeX
    @misc{misra2019mish,
      title={Mish: A Self Regularized Non-Monotonic Activation Function},
      author={Misra, Diganta},
      year={2019},
      eprint={1908.08681},
      archiveprefix={arXiv},
      primaryclass={cs.LG}
    }

    Reference

  24. Attention is all you need

    Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, Illia Polosukhin

    Advances in neural information processing systems, pp. 5998-6008 · 2017

    BibTeX
    @inproceedings{vaswani2017attention,
    title={Attention is all you need},
    author={Vaswani, Ashish and Shazeer, Noam and Parmar, Niki and Uszkoreit, Jakob and Jones, Llion and Gomez, Aidan N and Kaiser, {\L}ukasz and Polosukhin, Illia},
    booktitle={Advances in neural information processing systems},
    pages={5998--6008},
    year={2017}
    }

    Conference paper

  25. RoFormer: Enhanced Transformer with Rotary Position Embedding

    Jianlin Su, Murtadha Ahmed, Yu Lu, Shengfeng Pan, Wen Bo, Yunfeng Liu

    Neurocomputing, vol. 568, pp. 127063 · 2024

    BibTeX
    @article{su2024roformer,
      title={{RoFormer}: Enhanced Transformer with Rotary Position Embedding},
      author={Su, Jianlin and Ahmed, Murtadha and Lu, Yu and Pan, Shengfeng and Bo, Wen and Liu, Yunfeng},
      journal={Neurocomputing},
      volume={568},
      pages={127063},
      year={2024},
      publisher={Elsevier}
    }

    Journal article

  26. Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation

    Ofir Press, Noah A. Smith, Mike Lewis

    International Conference on Learning Representations (ICLR) · 2022

    BibTeX
    @inproceedings{press2022alibi,
      title={Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation},
      author={Press, Ofir and Smith, Noah A. and Lewis, Mike},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2022}
    }

    Conference paper

  27. YaRN: Efficient Context Window Extension of Large Language Models

    Bowen Peng, Jeffrey Quesnelle, Honglu Fan, Enrico Shippole

    arXiv:2309.00071 · 2023

    BibTeX
    @misc{peng2023yarn,
      title={{YaRN}: Efficient Context Window Extension of Large Language Models},
      author={Peng, Bowen and Quesnelle, Jeffrey and Fan, Honglu and Shippole, Enrico},
      year={2023},
      eprint={2309.00071},
      archiveprefix={arXiv},
      primaryclass={cs.CL}
    }

    Reference

  28. NTK-Aware Scaled RoPE Allows LLaMA Models to Have Extended Context

    bloc97

    Reddit post and community discovery · 2023

    BibTeX
    @misc{ntk2023rope,
      title={{NTK}-Aware Scaled {RoPE} Allows {LLaMA} Models to Have Extended Context},
      author={bloc97},
      year={2023},
      howpublished={Reddit post and community discovery},
      note={Community-discovered method for extending RoPE context length via Neural Tangent Kernel-aware interpolation}
    }

    Reference

  29. Mistral 7B

    Albert Q. Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh Chaplot, Diego de las Casas, Florian Bressand, Gianna Lengyel, et al.

    arXiv preprint arXiv:2310.06825 · 2023

    BibTeX
    @article{jiang2023mistral,
      title={{Mistral 7B}},
      author={Jiang, Albert Q. and Sablayrolles, Alexandre and Mensch, Arthur and Bamford, Chris and Chaplot, Devendra Singh and de las Casas, Diego and Bressand, Florian and Lengyel, Gianna and Lample, Guillaume and Saulnier, Lucile and others},
      journal={arXiv preprint arXiv:2310.06825},
      year={2023}
    }

    Journal article

  30. Longformer: The Long-Document Transformer

    Iz Beltagy, Matthew E. Peters, Arman Cohan

    arXiv preprint arXiv:2004.05150 · 2020

    BibTeX
    @article{beltagy2020longformer,
      title={Longformer: The Long-Document Transformer},
      author={Beltagy, Iz and Peters, Matthew E. and Cohan, Arman},
      journal={arXiv preprint arXiv:2004.05150},
      year={2020}
    }

    Journal article

  31. Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention

    Angelos Katharopoulos, Apoorv Vyas, Nikolaos Pappas, Francois Fleuret

    International Conference on Machine Learning (ICML), pp. 5156-5165 · 2020

    BibTeX
    @inproceedings{katharopoulos2020transformers,
      title={Transformers are {RNNs}: Fast Autoregressive Transformers with Linear Attention},
      author={Katharopoulos, Angelos and Vyas, Apoorv and Pappas, Nikolaos and Fleuret, Fran\c{c}ois},
      booktitle={International Conference on Machine Learning (ICML)},
      pages={5156--5165},
      year={2020}
    }

    Conference paper

  32. Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning

    Yarin Gal, Zoubin Ghahramani

    Proceedings of the International Conference on Machine Learning (ICML), pp. 1050-1059 · 2016

    BibTeX
    @inproceedings{gal2016dropout,
      title={Dropout as a {B}ayesian Approximation: Representing Model Uncertainty in Deep Learning},
      author={Gal, Yarin and Ghahramani, Zoubin},
      booktitle={Proceedings of the International Conference on Machine Learning (ICML)},
      pages={1050--1059},
      year={2016}
    }

    Conference paper

  33. Rethinking the Inception Architecture for Computer Vision

    Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jon Shlens, Zbigniew Wojna

    IEEE Conference on Computer Vision and Pattern Recognition (CVPR), pp. 2818-2826 · 2016

    BibTeX
    @inproceedings{szegedy2016rethinking,
      title={Rethinking the Inception Architecture for Computer Vision},
      author={Szegedy, Christian and Vanhoucke, Vincent and Ioffe, Sergey and Shlens, Jon and Wojna, Zbigniew},
      booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
      pages={2818--2826},
      year={2016}
    }

    Conference paper

  34. mixup: Beyond Empirical Risk Minimization

    Hongyi Zhang, Moustapha Cisse, Yann N. Dauphin, David Lopez-Paz

    International Conference on Learning Representations (ICLR) · 2018

    BibTeX
    @inproceedings{zhang2018mixup,
      title={mixup: Beyond Empirical Risk Minimization},
      author={Zhang, Hongyi and Cisse, Moustapha and Dauphin, Yann N. and Lopez-Paz, David},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2018}
    }

    Conference paper

  35. CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features

    Sangdoo Yun, Dongyoon Han, Seong Joon Oh, Sanghyuk Chun, Junsuk Choe, Youngjoon Yoo

    IEEE International Conference on Computer Vision (ICCV), pp. 6023-6032 · 2019

    BibTeX
    @inproceedings{yun2019cutmix,
      title={{CutMix}: Regularization Strategy to Train Strong Classifiers with Localizable Features},
      author={Yun, Sangdoo and Han, Dongyoon and Oh, Seong Joon and Chun, Sanghyuk and Choe, Junsuk and Yoo, Youngjoon},
      booktitle={IEEE International Conference on Computer Vision (ICCV)},
      pages={6023--6032},
      year={2019}
    }

    Conference paper

  36. R-Drop: Regularized Dropout for Neural Networks

    Xiaobo Liang, Lijun Wu, Juntao Li, Yue Wang, Qi Meng, Tao Qin, Wei Chen, Min Zhang, et al.

    Advances in Neural Information Processing Systems (NeurIPS) · 2021

    BibTeX
    @inproceedings{liang2021rdrop,
      title={{R-Drop}: Regularized Dropout for Neural Networks},
      author={Liang, Xiaobo and Wu, Lijun and Li, Juntao and Wang, Yue and Meng, Qi and Qin, Tao and Chen, Wei and Zhang, Min and Liu, Tie-Yan},
      booktitle={Advances in Neural Information Processing Systems (NeurIPS)},
      year={2021}
    }

    Conference paper

  37. SGDR: Stochastic Gradient Descent with Warm Restarts

    Ilya Loshchilov, Frank Hutter

    International Conference on Learning Representations (ICLR) · 2017

    BibTeX
    @inproceedings{loshchilov2017sgdr,
      title={{SGDR}: Stochastic Gradient Descent with Warm Restarts},
      author={Loshchilov, Ilya and Hutter, Frank},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2017}
    }

    Conference paper

  38. Cyclical Learning Rates for Training Neural Networks

    Leslie N. Smith

    IEEE Winter Conference on Applications of Computer Vision (WACV), pp. 464-472 · 2017

    BibTeX
    @inproceedings{smith2017cyclical,
      title={Cyclical Learning Rates for Training Neural Networks},
      author={Smith, Leslie N.},
      booktitle={IEEE Winter Conference on Applications of Computer Vision (WACV)},
      pages={464--472},
      year={2017}
    }

    Conference paper

  39. Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour

    Priya Goyal, Piotr Dollar, Ross Girshick, Pieter Noordhuis, Lukasz Wesolowski, Aapo Kyrola, Andrew Tulloch, Yangqing Jia, et al.

    arXiv:1706.02677 · 2017

    BibTeX
    @misc{goyal2017accurate,
      title={Accurate, Large Minibatch {SGD}: Training {ImageNet} in 1 Hour},
      author={Goyal, Priya and Doll\'{a}r, Piotr and Girshick, Ross and Noordhuis, Pieter and Wesolowski, Lukasz and Kyrola, Aapo and Tulloch, Andrew and Jia, Yangqing and He, Kaiming},
      year={2017},
      eprint={1706.02677},
      archiveprefix={arXiv},
      primaryclass={cs.CV}
    }

    Reference

  40. Mixed Precision Training

    Paulius Micikevicius, Sharan Narang, Jonah Alben, Gregory Diamos, Erich Elsen, David Garcia, Boris Ginsburg, Michael Houston, et al.

    International Conference on Learning Representations (ICLR) · 2018

    BibTeX
    @inproceedings{micikevicius2018mixed,
      title={Mixed Precision Training},
      author={Micikevicius, Paulius and Narang, Sharan and Alben, Jonah and Diamos, Gregory and Elsen, Erich and Garcia, David and Ginsburg, Boris and Houston, Michael and Kuchaiev, Oleksii and Venkatesh, Ganesh and Wu, Hao},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2018}
    }

    Conference paper

  41. Knowledge Distillation: A Survey

    Jianping Gou, Baosheng Yu, Stephen J. Maybank, Dacheng Tao

    International Journal of Computer Vision, vol. 129, no. 6, pp. 1789-1819 · 2021

    BibTeX
    @article{gou2021knowledge,
      title={Knowledge Distillation: A Survey},
      author={Gou, Jianping and Yu, Baosheng and Maybank, Stephen J. and Tao, Dacheng},
      journal={International Journal of Computer Vision},
      volume={129},
      number={6},
      pages={1789--1819},
      year={2021}
    }

    Journal article

  42. Distilling the Knowledge in a Neural Network

    Geoffrey Hinton, Oriol Vinyals, Jeff Dean

    NIPS Deep Learning and Representation Learning Workshop · 2015

    BibTeX
    @inproceedings{hinton2015distilling,
      title={Distilling the Knowledge in a Neural Network},
      author={Hinton, Geoffrey and Vinyals, Oriol and Dean, Jeff},
      booktitle={NIPS Deep Learning and Representation Learning Workshop},
      year={2015}
    }

    Conference paper

  43. Born Again Neural Networks

    Tommaso Furlanello, Zachary C. Lipton, Michael Tschannen, Laurent Itti, Anima Anandkumar

    International Conference on Machine Learning (ICML), pp. 1607-1616 · 2018

    BibTeX
    @inproceedings{furlanello2018born,
      title={Born Again Neural Networks},
      author={Furlanello, Tommaso and Lipton, Zachary C. and Tschannen, Michael and Itti, Laurent and Anandkumar, Anima},
      booktitle={International Conference on Machine Learning (ICML)},
      pages={1607--1616},
      year={2018}
    }

    Conference paper

  44. Be Your Own Teacher: Improve the Performance of Convolutional Neural Networks via Self Distillation

    Linfeng Zhang, Jiebo Song, Anni Gao, Jingwei Chen, Chenglong Bao, Kaisheng Ma

    IEEE International Conference on Computer Vision (ICCV), pp. 3713-3722 · 2019

    BibTeX
    @inproceedings{zhang2019your,
      title={Be Your Own Teacher: Improve the Performance of Convolutional Neural Networks via Self Distillation},
      author={Zhang, Linfeng and Song, Jiebo and Gao, Anni and Chen, Jingwei and Bao, Chenglong and Ma, Kaisheng},
      booktitle={IEEE International Conference on Computer Vision (ICCV)},
      pages={3713--3722},
      year={2019}
    }

    Conference paper

  45. A White Paper on Neural Network Quantization

    Markus Nagel, Rana Ali Amjad, Mart van Baalen, Christos Louizos, Tijmen Blankevoort

    arXiv:2106.08295 · 2021

    BibTeX
    @misc{nagel2021white,
      title={A White Paper on Neural Network Quantization},
      author={Nagel, Markus and Amjad, Rana Ali and van Baalen, Mart and Louizos, Christos and Blankevoort, Tijmen},
      year={2021},
      eprint={2106.08295},
      archiveprefix={arXiv},
      primaryclass={cs.LG}
    }

    Reference

  46. GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers

    Elias Frantar, Saleh Ashkboos, Torsten Hoefler, Dan Alistarh

    International Conference on Learning Representations (ICLR) · 2023

    BibTeX
    @inproceedings{frantar2022gptq,
      title={{GPTQ}: Accurate Post-Training Quantization for Generative Pre-trained Transformers},
      author={Frantar, Elias and Ashkboos, Saleh and Hoefler, Torsten and Alistarh, Dan},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2023}
    }

    Conference paper

  47. AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration

    Ji Lin, Jiaming Tang, Haotian Tang, Shang Yang, Wei-Ming Chen, Wei-Chen Wang, Guangxuan Xiao, Xingyu Dang, et al.

    Conference on Machine Learning and Systems (MLSys) · 2024

    BibTeX
    @inproceedings{lin2023awq,
      title={{AWQ}: Activation-aware Weight Quantization for {LLM} Compression and Acceleration},
      author={Lin, Ji and Tang, Jiaming and Tang, Haotian and Yang, Shang and Chen, Wei-Ming and Wang, Wei-Chen and Xiao, Guangxuan and Dang, Xingyu and Gan, Chuang and Han, Song},
      booktitle={Conference on Machine Learning and Systems (MLSys)},
      year={2024}
    }

    Conference paper

  48. QLoRA: Efficient Finetuning of Quantized Language Models

    Tim Dettmers, Artidoro Pagnoni, Ari Holtzman, Luke Zettlemoyer

    Advances in Neural Information Processing Systems, vol. 36 · 2023

    BibTeX
    @article{dettmers2023qlora,
      title={{QLoRA}: Efficient Finetuning of Quantized Language Models},
      author={Dettmers, Tim and Pagnoni, Artidoro and Holtzman, Ari and Zettlemoyer, Luke},
      journal={Advances in Neural Information Processing Systems},
      volume={36},
      year={2023}
    }

    Journal article

  49. Learning Both Weights and Connections for Efficient Neural Networks

    Song Han, Jeff Pool, John Tran, William J. Dally

    Advances in Neural Information Processing Systems (NeurIPS), pp. 1135-1143 · 2015

    BibTeX
    @inproceedings{han2015learning,
      title={Learning Both Weights and Connections for Efficient Neural Networks},
      author={Han, Song and Pool, Jeff and Tran, John and Dally, William J.},
      booktitle={Advances in Neural Information Processing Systems (NeurIPS)},
      pages={1135--1143},
      year={2015}
    }

    Conference paper

  50. Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer

    Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton, Jeff Dean

    International Conference on Learning Representations · 2017

    BibTeX
    @inproceedings{shazeer2017outrageously,
      title={Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer},
      author={Shazeer, Noam and Mirhoseini, Azalia and Maziarz, Krzysztof and Davis, Andy and Le, Quoc and Hinton, Geoffrey and Dean, Jeff},
      booktitle={International Conference on Learning Representations},
      year={2017}
    }

    Conference paper

  51. Mixtral of Experts

    Albert Q. Jiang, Alexandre Sablayrolles, Antoine Roux, Arthur Mensch, Blanche Savary, Chris Bamford, Devendra Singh Chaplot, Diego de las Casas, et al.

    arXiv:2401.04088 · 2024

    BibTeX
    @misc{jiang2024mixtral,
      title={Mixtral of Experts},
      author={Jiang, Albert Q. and Sablayrolles, Alexandre and Roux, Antoine and Mensch, Arthur and Savary, Blanche and Bamford, Chris and Chaplot, Devendra Singh and de las Casas, Diego and Hanna, Emma Bou and Bressand, Florian and others},
      year={2024},
      eprint={2401.04088},
      archiveprefix={arXiv},
      primaryclass={cs.LG}
    }

    Reference

  52. DeepSeek-V3 Technical Report

    DeepSeek-AI, Aixin Liu, Bei Feng, Bing Xue, Bingxuan Wang, Bochao Wu, Chengda Lu, Chenggang Zhao, et al.

    arXiv preprint arXiv:2412.19437 · 2024

    BibTeX
    @article{deepseekv3,
      title={{DeepSeek-V3} Technical Report},
      author={DeepSeek-AI and Liu, Aixin and Feng, Bei and Xue, Bing and Wang, Bingxuan and Wu, Bochao and Lu, Chengda and Zhao, Chenggang and Deng, Chengqi and Zhang, Chenyu and others},
      journal={arXiv preprint arXiv:2412.19437},
      year={2024}
    }

    Journal article

  53. Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity

    William Fedus, Barret Zoph, Noam Shazeer

    Journal of Machine Learning Research, vol. 23, no. 120, pp. 1-39 · 2022

    BibTeX
    @article{fedus2022switch,
      title={Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity},
      author={Fedus, William and Zoph, Barret and Shazeer, Noam},
      journal={Journal of Machine Learning Research},
      volume={23},
      number={120},
      pages={1--39},
      year={2022}
    }

    Journal article

  54. The Lottery Ticket Hypothesis: Finding Sparse, Trainable Neural Networks

    Jonathan Frankle, Michael Carbin

    International Conference on Learning Representations (ICLR) · 2019

    BibTeX
    @inproceedings{frankle2019lottery,
      title={The Lottery Ticket Hypothesis: Finding Sparse, Trainable Neural Networks},
      author={Frankle, Jonathan and Carbin, Michael},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2019}
    }

    Conference paper

  55. Fast Inference from Transformers via Speculative Decoding

    Yaniv Leviathan, Matan Kalman, Yossi Matias

    International Conference on Machine Learning (ICML), pp. 19274-19286 · 2023

    BibTeX
    @inproceedings{leviathan2023fast,
      title={Fast Inference from Transformers via Speculative Decoding},
      author={Leviathan, Yaniv and Kalman, Matan and Matias, Yossi},
      booktitle={International Conference on Machine Learning (ICML)},
      pages={19274--19286},
      year={2023}
    }

    Conference paper

  56. Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads

    Tianle Cai, Yuhong Li, Zhengyang Geng, Hongwu Peng, Jason D. Lee, Deming Chen, Tri Dao

    International Conference on Machine Learning (ICML) · 2024

    BibTeX
    @inproceedings{cai2024medusa,
      title={Medusa: Simple {LLM} Inference Acceleration Framework with Multiple Decoding Heads},
      author={Cai, Tianle and Li, Yuhong and Geng, Zhengyang and Peng, Hongwu and Lee, Jason D. and Chen, Deming and Dao, Tri},
      booktitle={International Conference on Machine Learning (ICML)},
      year={2024}
    }

    Conference paper

  57. Using the Output Embedding to Improve Language Models

    Ofir Press, Lior Wolf

    Conference of the European Chapter of the Association for Computational Linguistics (EACL), pp. 157-163 · 2017

    BibTeX
    @inproceedings{press2017using,
      title={Using the Output Embedding to Improve Language Models},
      author={Press, Ofir and Wolf, Lior},
      booktitle={Conference of the European Chapter of the Association for Computational Linguistics (EACL)},
      pages={157--163},
      year={2017}
    }

    Conference paper

  58. Efficient Streaming Language Models with Attention Sinks

    Guangxuan Xiao, Yuandong Tian, Beidi Chen, Song Han, Mike Lewis

    International Conference on Learning Representations · 2024

    BibTeX
    @inproceedings{xiao2024efficient,
      title={Efficient Streaming Language Models with Attention Sinks},
      author={Xiao, Guangxuan and Tian, Yuandong and Chen, Beidi and Han, Song and Lewis, Mike},
      booktitle={International Conference on Learning Representations},
      year={2024}
    }

    Conference paper

  59. Group Normalization

    Yuxin Wu, Kaiming He

    European Conference on Computer Vision (ECCV), pp. 3-19 · 2018

    BibTeX
    @inproceedings{wu2018group,
      title={Group Normalization},
      author={Wu, Yuxin and He, Kaiming},
      booktitle={European Conference on Computer Vision (ECCV)},
      pages={3--19},
      year={2018}
    }

    Conference paper

  60. Instance Normalization: The Missing Ingredient for Fast Stylization

    Dmitry Ulyanov, Andrea Vedaldi, Victor Lempitsky

    arXiv:1607.08022 · 2016

    BibTeX
    @misc{ulyanov2016instance,
      title={Instance Normalization: The Missing Ingredient for Fast Stylization},
      author={Ulyanov, Dmitry and Vedaldi, Andrea and Lempitsky, Victor},
      year={2016},
      eprint={1607.08022},
      archiveprefix={arXiv},
      primaryclass={cs.CV}
    }

    Reference

  61. Root Mean Square Layer Normalization

    Biao Zhang, Rico Sennrich

    Advances in Neural Information Processing Systems, vol. 32 · 2019

    BibTeX
    @inproceedings{zhang2019rmsnorm,
      title={Root Mean Square Layer Normalization},
      author={Zhang, Biao and Sennrich, Rico},
      booktitle={Advances in Neural Information Processing Systems},
      volume={32},
      year={2019}
    }

    Conference paper

  62. Query-Key Normalization for Transformers

    Alex Henry, Prudhvi Raj Dachapally, Shubham Pawar, Yun Chen

    Findings of the Association for Computational Linguistics: EMNLP, pp. 4246-4253 · 2020

    BibTeX
    @inproceedings{henry2020querykey,
      title={Query-Key Normalization for Transformers},
      author={Henry, Alex and Dachapally, Prudhvi Raj and Pawar, Shubham and Chen, Yun},
      booktitle={Findings of the Association for Computational Linguistics: EMNLP},
      pages={4246--4253},
      year={2020}
    }

    Conference paper

  63. On Layer Normalization in the Transformer Architecture

    Ruibin Xiong, Yunchang Yang, Di He, Kai Zheng, Shuxin Zheng, Chen Xing, Huishuai Zhang, Yanyan Lan, et al.

    International Conference on Machine Learning (ICML), pp. 10524-10533 · 2020

    BibTeX
    @inproceedings{xiong2020layer,
      title={On Layer Normalization in the Transformer Architecture},
      author={Xiong, Ruibin and Yang, Yunchang and He, Di and Zheng, Kai and Zheng, Shuxin and Xing, Chen and Zhang, Huishuai and Lan, Yanyan and Wang, Liwei and Liu, Tie-Yan},
      booktitle={International Conference on Machine Learning (ICML)},
      pages={10524--10533},
      year={2020}
    }

    Conference paper

  64. Residual Networks Behave Like Ensembles of Relatively Shallow Networks

    Andreas Veit, Michael Wilber, Serge Belongie

    Advances in Neural Information Processing Systems (NeurIPS) · 2016

    BibTeX
    @inproceedings{veit2016residual,
      title={Residual Networks Behave Like Ensembles of Relatively Shallow Networks},
      author={Veit, Andreas and Wilber, Michael and Belongie, Serge},
      booktitle={Advances in Neural Information Processing Systems (NeurIPS)},
      year={2016}
    }

    Conference paper

  65. Identity Mappings in Deep Residual Networks

    Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun

    European Conference on Computer Vision (ECCV), pp. 630-645 · 2016

    BibTeX
    @inproceedings{he2016identity,
      title={Identity Mappings in Deep Residual Networks},
      author={He, Kaiming and Zhang, Xiangyu and Ren, Shaoqing and Sun, Jian},
      booktitle={European Conference on Computer Vision (ECCV)},
      pages={630--645},
      year={2016}
    }

    Conference paper

  66. Densely Connected Convolutional Networks

    Gao Huang, Zhuang Liu, Laurens van der Maaten, Kilian Q. Weinberger

    IEEE Conference on Computer Vision and Pattern Recognition (CVPR), pp. 2261-2269 · 2017

    BibTeX
    @inproceedings{huang2017densely,
      title={Densely Connected Convolutional Networks},
      author={Huang, Gao and Liu, Zhuang and van der Maaten, Laurens and Weinberger, Kilian Q.},
      booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
      pages={2261--2269},
      year={2017}
    }

    Conference paper

  67. ReZero is All You Need: Fast Convergence at Large Depth

    Thomas Bachlechner, Bodhisattwa Prasad Majumder, Huanru Henry Mao, Garrison W. Cottrell, Julian McAuley

    Conference on Uncertainty in Artificial Intelligence (UAI), pp. 1352-1362 · 2021

    BibTeX
    @inproceedings{bachlechner2020rezero,
      title={{ReZero} is All You Need: Fast Convergence at Large Depth},
      author={Bachlechner, Thomas and Majumder, Bodhisattwa Prasad and Mao, Huanru Henry and Cottrell, Garrison W. and McAuley, Julian},
      booktitle={Conference on Uncertainty in Artificial Intelligence (UAI)},
      pages={1352--1362},
      year={2021}
    }

    Conference paper

  68. Hyper-Connections

    Defa Zhu, Hongzhi Huang, Zihao Huang, Yutao Zeng, Yunyao Mao, Banggu Wu, Qiyang Min, Xun Zhou

    arXiv:2409.19606 · 2024

    BibTeX
    @misc{zhu2024hyperconnections,
      title={Hyper-Connections},
      author={Zhu, Defa and Huang, Hongzhi and Huang, Zihao and Zeng, Yutao and Mao, Yunyao and Wu, Banggu and Min, Qiyang and Zhou, Xun},
      year={2024},
      eprint={2409.19606},
      archiveprefix={arXiv},
      primaryclass={cs.LG}
    }

    Reference

  69. mHC: Manifold-Constrained Hyper-Connections

    Zhenda Xie, Yixuan Wei, Huanqi Cao, Chenggang Zhao, Chengqi Deng, Jiashi Li, Damai Dai, Huazuo Gao, et al.

    arXiv:2512.24880 · 2025

    BibTeX
    @misc{xie2025mhc,
      title={{mHC}: Manifold-Constrained Hyper-Connections},
      author={Xie, Zhenda and Wei, Yixuan and Cao, Huanqi and Zhao, Chenggang and Deng, Chengqi and Li, Jiashi and Dai, Damai and Gao, Huazuo and Chang, Jiang and Yu, Kuai and Zhao, Liang and Zhou, Shangyan and Xu, Zhean and Zhang, Zhengyan and Zeng, Wangding and Hu, Shengding and Wang, Yuqing and Yuan, Jingyang and Wang, Lean and Liang, Wenfeng},
      year={2025},
      eprint={2512.24880},
      archiveprefix={arXiv},
      primaryclass={cs.LG}
    }

    Reference

  70. MetaFormer Baselines for Vision

    Weihao Yu, Chenyang Si, Pan Zhou, Mi Luo, Yichen Zhou, Jiashi Feng, Shuicheng Yan, Xinchao Wang

    IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 46, no. 2, pp. 896-912 · 2024

    BibTeX
    @article{yu2022metaformer,
      title={{MetaFormer} Baselines for Vision},
      author={Yu, Weihao and Si, Chenyang and Zhou, Pan and Luo, Mi and Zhou, Yichen and Feng, Jiashi and Yan, Shuicheng and Wang, Xinchao},
      journal={IEEE Transactions on Pattern Analysis and Machine Intelligence},
      volume={46},
      number={2},
      pages={896--912},
      year={2024}
    }

    Journal article

  71. Extending Context Window of Large Language Models via Positional Interpolation

    Shouyuan Chen, Sherman Wong, Liangjian Chen, Yuandong Tian

    arXiv preprint arXiv:2306.15595 · 2023

    BibTeX
    @article{chen2023extending,
      title={Extending Context Window of Large Language Models via Positional Interpolation},
      author={Chen, Shouyuan and Wong, Sherman and Chen, Liangjian and Tian, Yuandong},
      journal={arXiv preprint arXiv:2306.15595},
      year={2023}
    }

    Journal article

  72. Generating Long Sequences with Sparse Transformers

    Rewon Child, Scott Gray, Alec Radford, Ilya Sutskever

    arXiv preprint arXiv:1904.10509 · 2019

    BibTeX
    @article{child2019generating,
      title={Generating Long Sequences with Sparse Transformers},
      author={Child, Rewon and Gray, Scott and Radford, Alec and Sutskever, Ilya},
      journal={arXiv preprint arXiv:1904.10509},
      year={2019}
    }

    Journal article

  73. Ring Attention with Blockwise Transformers for Near-Infinite Context

    Hao Liu, Matei Zaharia, Pieter Abbeel

    International Conference on Learning Representations · 2024

    BibTeX
    @inproceedings{liu2023ring,
      title={Ring Attention with Blockwise Transformers for Near-Infinite Context},
      author={Liu, Hao and Zaharia, Matei and Abbeel, Pieter},
      booktitle={International Conference on Learning Representations},
      note={arXiv:2310.01889, October 2023},
      year={2024}
    }

    Conference paper

  74. FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning

    Tri Dao

    International Conference on Learning Representations (ICLR) · 2024

    BibTeX
    @inproceedings{dao2023flashattention2,
      title={{FlashAttention-2}: Faster Attention with Better Parallelism and Work Partitioning},
      author={Dao, Tri},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2024}
    }

    Conference paper

  75. FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision

    Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao

    arXiv:2407.08691 · 2024

    BibTeX
    @misc{shah2024flashattention3,
      title={{FlashAttention-3}: Fast and Accurate Attention with Asynchrony and Low-precision},
      author={Shah, Jay and Bikshandi, Ganesh and Zhang, Ying and Thakkar, Vijay and Ramani, Pradeep and Dao, Tri},
      year={2024},
      eprint={2407.08691},
      archiveprefix={arXiv},
      primaryclass={cs.LG}
    }

    Reference

  76. Efficient Memory Management for Large Language Model Serving with PagedAttention

    Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, Lianmin Zheng, Cody Hao Yu, Joseph E. Gonzalez, Hao Zhang, et al.

    ACM Symposium on Operating Systems Principles (SOSP), pp. 611-626 · 2023

    BibTeX
    @inproceedings{kwon2023efficient,
      title={Efficient Memory Management for Large Language Model Serving with {PagedAttention}},
      author={Kwon, Woosuk and Li, Zhuohan and Zhuang, Siyuan and Sheng, Ying and Zheng, Lianmin and Yu, Cody Hao and Gonzalez, Joseph E. and Zhang, Hao and Stoica, Ion},
      booktitle={ACM Symposium on Operating Systems Principles (SOSP)},
      pages={611--626},
      year={2023}
    }

    Conference paper

  77. Deep Networks with Stochastic Depth

    Gao Huang, Yu Sun, Zhuang Liu, Daniel Sedra, Kilian Q. Weinberger

    European Conference on Computer Vision (ECCV), pp. 646-661 · 2016

    BibTeX
    @inproceedings{huang2016deep,
      title={Deep Networks with Stochastic Depth},
      author={Huang, Gao and Sun, Yu and Liu, Zhuang and Sedra, Daniel and Weinberger, Kilian Q.},
      booktitle={European Conference on Computer Vision (ECCV)},
      pages={646--661},
      year={2016}
    }

    Conference paper

  78. Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates

    Leslie N. Smith, Nicholay Topin

    arXiv:1708.07120 · 2018

    BibTeX
    @misc{smith2018superconvergence,
      title={Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates},
      author={Smith, Leslie N. and Topin, Nicholay},
      year={2018},
      eprint={1708.07120},
      archiveprefix={arXiv},
      primaryclass={cs.LG}
    }

    Reference

  79. MiniCPM: Unveiling the Potential of Small Language Models with Scalable Training Strategies

    Shengding Hu, Yuge Tu, Xu Han, Chaoqun He, Ganqu Cui, Xiang Long, Zhi Zheng, Yewei Fang, et al.

    arXiv:2404.06395 · 2024

    BibTeX
    @misc{hu2024minicpm,
      title={{MiniCPM}: Unveiling the Potential of Small Language Models with Scalable Training Strategies},
      author={Hu, Shengding and Tu, Yuge and Han, Xu and He, Chaoqun and Cui, Ganqu and Long, Xiang and Zheng, Zhi and Fang, Yewei and Huang, Yuxiang and Zhao, Weilin and others},
      year={2024},
      eprint={2404.06395},
      archiveprefix={arXiv},
      primaryclass={cs.CL}
    }

    Reference