FXJ Wiki

Back

A Brief Introduction to Deep Learning
32 min read
English Deep Learning / Neural Networks / Transformer

A Brief Introduction to Deep Learning

From a single neuron, gradient descent, and 2-2-1 backpropagation to embeddings, 3-token self-attention, RoPE, FFN parameter counts, and KV Cache.
views | comments

This post walks through the core computational chain of deep learning: the first half starts from a single neuron and derives gradient descent, backpropagation, a worked 2-2-1 network example, and cross-entropy loss; the second half moves to text sequences and derives word embeddings, self-attention (with a worked 3-token example), RoPE rotary position embeddings, FFN parameter counts, and KV Cache optimizations in modern LLMs. Why stacking many layers improves expressivity is covered in the companion post Why Neural Networks Need Depth.

Neurons & MatricesActivations break linearcollapseGradient Descent &Backprop2-2-1 worked example ·Cross-EntropyTokenization & EmbeddingsHigh-dim near-orthogonalitySelf-Attention & RoPE3-Token example · RelativerotationDecoder BlockLayerNorm · FFNparameter budgetKV Cache & Modern LLMsRMSNorm · SwiGLU ·GQA · MLA

Prerequisites: matrix multiplication and the chain rule for composite functions.

Neurons and Multilayer Networks#

From Handcrafted Rules to Parameterized Functions#

In MNIST handwritten digit recognition, each input is a 28×28=78428 \times 28 = 784 grayscale image with pixel values normalized to [0,1][0, 1], and the output is a score for each digit from 00 to 99. Because handwriting varies widely, enumerating explicit conditional rules is impractical.

A neural network instead fixes a family of functions with many tunable parameters and adjusts those parameters on training data to match the target labels.

A Single Neuron#

With two inputs x1,x2x_1, x_2, a single neuron performs two steps:

z=w1x1+w2x2+b,a=σ(z).z = w_1 x_1 + w_2 x_2 + b, \qquad a = \sigma(z).

Here w1,w2w_1, w_2 are weights controlling each input’s direction and magnitude, bb is a bias shifting the activation threshold, and σ\sigma is a nonlinear activation function.

A classic activation function is Sigmoid:

σ(z)=11+e−z.\sigma(z) = \frac{1}{1 + e^{-z}}.

It maps real numbers into (0,1)(0, 1), and its derivative satisfies:

σ′(z)=e−z(1+e−z)2=11+e−z⋅e−z1+e−z=σ(z)(1−σ(z)).\sigma'(z) = \frac{e^{-z}}{(1+e^{-z})^2} = \frac{1}{1+e^{-z}} \cdot \frac{e^{-z}}{1+e^{-z}} = \sigma(z)\bigl(1-\sigma(z)\bigr).

Because t(1−t)t(1-t) attains its maximum 14\tfrac{1}{4} at t=12t=\tfrac{1}{2}, we have 0<σ′(z)≤140 < \sigma'(z) \le \tfrac{1}{4} for every zz. This upper bound directly affects gradient propagation in deep networks.

Why Nonlinear Activations Are Necessary#

Without hidden-layer activations, stacking two linear layers collapses into a single affine map:

W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2).W_2(W_1 x + b_1) + b_2 = (W_2 W_1)x + (W_2 b_1 + b_2).

Setting W′=W2W1W' = W_2 W_1 and b′=W2b1+b2b' = W_2 b_1 + b_2 yields W′x+b′W'x + b'. Regardless of depth, removing nonlinear activations reduces the network to a single linear model that cannot represent nonlinear decision boundaries.

Matrix Form of a Layer#

For 33 inputs (x1,x2,x3)(x_1, x_2, x_3) feeding into 22 neurons:

(z1z2)=(w11w12w13w21w22w23)(x1x2x3)+(b1b2).\begin{pmatrix} z_1 \\ z_2 \end{pmatrix} = \begin{pmatrix} w_{11} & w_{12} & w_{13} \\ w_{21} & w_{22} & w_{23} \end{pmatrix} \begin{pmatrix} x_1 \\ x_2 \\ x_3 \end{pmatrix} + \begin{pmatrix} b_1 \\ b_2 \end{pmatrix}.

In the fully connected sections we let wjk(l)w_{jk}^{(l)} denote the weight in layer ll connecting neuron kk in layer l−1l-1 to neuron jj in layer ll. Row jj of W(l)W^{(l)} holds all incoming weights of neuron jj, and column kk holds all outgoing weights of neuron kk from the previous layer. Forward propagation through layer ll is:

z(l)=W(l)a(l−1)+b(l),a(l)=σ(z(l)).z^{(l)} = W^{(l)} a^{(l-1)} + b^{(l)}, \qquad a^{(l)} = \sigma\bigl(z^{(l)}\bigr).

Consider a 784→16→16→10784 \to 16 \to 16 \to 10 MLP for MNIST:

Diagram of 784 inputs, two hidden layers, and 10 output units

ConnectionWeight Matrix ShapeWeightsBiases
Input → Hidden 116×78416\times 78412,54416
Hidden 1 → Hidden 216×1616\times 1625616
Hidden 2 → Output10×1610\times 1616010
Total—12,96042

The network has 13,002 parameters in total. Training does not enforce that early layers extract edges or later layers compose strokes; it only adjusts those 13,002 parameters to minimize the loss. Learned weights are often hard to interpret directly, and pure random noise can still receive high-confidence predictions because the objective never constrains out-of-distribution inputs.

Draw a digit from 0 to 9 on the 7×7 grid to see how a smaller trained network makes a prediction. Click a node in the first hidden layer to inspect the pixel weights that neuron learned.

Digit:
Prediction: 8 (98.6%) · 3-layer MLP 49→12→10→1049\to 12\to 10\to 10 (840 params)
Draw (drag) x∈{0,1}7×7x \in \{0,1\}^{7\times 7}
Neuron h1(1)h^{(1)}_{1}
z=0.81z = 0.81
b=0.28b = 0.28
a=0.81a = 0.81
Forward pass x→a(1)→a(2)→softmaxx \to a^{(1)} \to a^{(2)} \to \mathrm{softmax}
0 0% 1 0% 2 0% 3 0% 4 0% 5 0% 6 1% 7 0% 8 99% 9 0% 49 12 ReLU 10 ReLU 0–9

Cost Functions and Gradient Descent#

Deriving the Negative Gradient Step#

Collect all network parameters into a vector θ\theta. For a single sample, start with squared error between output a(L)a^{(L)} and one-hot label yy (the 12\frac{1}{2} cancels the exponent 22 upon differentiation):

C0=12∑j=110(aj(L)−yj)2,C(θ)=1N∑n=1NCn(θ).C_0 = \frac{1}{2}\sum_{j=1}^{10} \bigl(a_j^{(L)} - y_j\bigr)^2, \qquad C(\theta) = \frac{1}{N}\sum_{n=1}^{N} C_n(\theta).

Consider a small displacement Δθ\Delta\theta of fixed length ∥Δθ∥=ε\|\Delta\theta\| = \varepsilon. By first-order Taylor expansion:

C(θ+Δθ)−C(θ)≈∇C(θ)⋅Δθ=∥∇C(θ)∥ ∥Δθ∥ cos⁡α,C(\theta + \Delta\theta) - C(\theta) \approx \nabla C(\theta) \cdot \Delta\theta = \|\nabla C(\theta)\|\,\|\Delta\theta\|\,\cos\alpha,

where α\alpha is the angle between Δθ\Delta\theta and ∇C(θ)\nabla C(\theta). To make C(θ+Δθ)−C(θ)C(\theta+\Delta\theta)-C(\theta) as negative as possible, choose cos⁡α=−1\cos\alpha = -1, meaning Δθ\Delta\theta points opposite to ∇C(θ)\nabla C(\theta):

θnew=θold−η ∇C(θ).\boxed{\theta_{\text{new}} = \theta_{\text{old}} - \eta\,\nabla C(\theta).}

Effect of the Learning Rate η\eta#

Take the 1D quadratic C(w)=(w−3)2C(w) = (w - 3)^2 with derivative C′(w)=2(w−3)C'(w) = 2(w-3) and minimum at w=3w=3. Starting from w0=0w_0 = 0 and iterating wt+1=wt−2η(wt−3)w_{t+1} = w_t - 2\eta(w_t - 3):

Learning rate η\etaFirst four steps w0→w1→w2→w3→w4w_0 \to w_1 \to w_2 \to w_3 \to w_4Behavior
η=0.1\eta = 0.10→0.6→1.08→1.464→1.7710 \to 0.6 \to 1.08 \to 1.464 \to 1.771Monotonic convergence to 33
η=0.5\eta = 0.50→3→3→3→30 \to 3 \to 3 \to 3 \to 3Exact minimum in one step
η=1.0\eta = 1.00→6→0→6→00 \to 6 \to 0 \to 6 \to 0Constant-amplitude oscillation
η=1.2\eta = 1.20→7.2→−2.88→11.23→−8.520 \to 7.2 \to -2.88 \to 11.23 \to -8.52Growing amplitude, divergence

Because the linear approximation holds only locally, an oversized step overshoots the minimum and causes oscillation or divergence. Switch between the 1D parabola and 2D narrow valley below to observe each regime:

Step 0 · η=0.22\eta = 0.22 · SGD C=6.6829C = 6.6829
Model y^=−0.80x+2.70\hat{y} = -0.80x +2.70
x y
Loss C(w,b)C(w, b)(click to move)
w b

Backpropagation#

From Finite Differences to Chain-Rule Recursion#

Estimating each partial derivative via finite differences ∂C∂wi≈C(wi+ϵ)−C(wi)ϵ\frac{\partial C}{\partial w_i} \approx \frac{C(w_i + \epsilon) - C(w_i)}{\epsilon} costs O(PF)O(PF) for PP parameters and forward cost FF, which is infeasible at scale. Backpropagation [1] applies the chain rule from output to input, reusing shared intermediate derivatives to compute all gradients in O(F)O(F) time.

For a two-layer network with one neuron per layer:

x→ w1, b1 z1→ σ a1→ w2, b2 z2→ σ a2⟶C=12(a2−y)2.x \xrightarrow{\ w_1,\ b_1\ } z_1 \xrightarrow{\ \sigma\ } a_1 \xrightarrow{\ w_2,\ b_2\ } z_2 \xrightarrow{\ \sigma\ } a_2 \longrightarrow C = \frac{1}{2}(a_2 - y)^2.

Define the layer-ll error signal δl≡∂C∂zl\delta_l \equiv \frac{\partial C}{\partial z_l}. Differentiating with respect to w2w_2 gives δ2=(a2−y)σ′(z2)\delta_2 = (a_2 - y)\sigma'(z_2) and ∂C∂w2=δ2a1\frac{\partial C}{\partial w_2} = \delta_2 a_1; differentiating with respect to w1w_1 reuses δ2\delta_2 to give δ1=δ2w2σ′(z1)\delta_1 = \delta_2 w_2 \sigma'(z_1) and ∂C∂w1=δ1x\frac{\partial C}{\partial w_1} = \delta_1 x.

In a general multilayer network, neuron ak(l)a_k^{(l)} feeds into every unit z1(l+1),z2(l+1),…z_1^{(l+1)}, z_2^{(l+1)}, \dots of the next layer, so the multivariable chain rule sums all outgoing branches:

∂C∂ak(l)=∑jwjk(l+1)δj(l+1).\frac{\partial C}{\partial a_k^{(l)}} = \sum_{j} w_{jk}^{(l+1)} \delta_j^{(l+1)}.

Backpropagation distributing output error back to earlier weights

Forward propagation sums over row indices (W(l+1)a(l)W^{(l+1)} a^{(l)}), while backpropagation sums over column kk, which is precisely the transpose (W(l+1))⊤δ(l+1)(W^{(l+1)})^\top \delta^{(l+1)}. This yields the four core backpropagation equations (⊙\odot denotes elementwise multiplication):

δ(L)=∂C∂a(L)⊙σ′(z(L))δ(l)=(W(l+1))⊤δ(l+1)⊙σ′(z(l))∂C∂b(l)=δ(l)∂C∂W(l)=δ(l)(a(l−1))⊤\boxed{ \begin{aligned} \delta^{(L)} &= \frac{\partial C}{\partial a^{(L)}} \odot \sigma'\bigl(z^{(L)}\bigr) \\ \delta^{(l)} &= \bigl(W^{(l+1)}\bigr)^\top \delta^{(l+1)} \odot \sigma'\bigl(z^{(l)}\bigr) \\ \frac{\partial C}{\partial b^{(l)}} &= \delta^{(l)} \\ \frac{\partial C}{\partial W^{(l)}} &= \delta^{(l)} \bigl(a^{(l-1)}\bigr)^\top \end{aligned} }

Worked 2-2-1 Network Example#

Take a 2→2→12 \to 2 \to 1 network (ReLU hidden layer, linear output, loss C=12(y^−y)2C = \frac{1}{2}(\hat{y}-y)^2) with input x=(1,2)⊤x = (1, 2)^\top, target y=2y = 2, and initial parameters:

W(1)=(0.50.51.0−0.25),b(1)=(00),W(2)=(1.0−1.0),b(2)=0.W^{(1)} = \begin{pmatrix} 0.5 & 0.5 \\ 1.0 & -0.25 \end{pmatrix}, \quad b^{(1)} = \begin{pmatrix} 0 \\ 0 \end{pmatrix}, \qquad W^{(2)} = \begin{pmatrix} 1.0 & -1.0 \end{pmatrix}, \quad b^{(2)} = 0.
  1. Forward pass: z(1)=(1.50.5)  ⟹  a(1)=(1.50.5),y^=1.0×1.5−1.0×0.5=1.0,C=12(1.0−2)2=0.5.z^{(1)} = \begin{pmatrix} 1.5 \\ 0.5 \end{pmatrix} \implies a^{(1)} = \begin{pmatrix} 1.5 \\ 0.5 \end{pmatrix}, \qquad \hat{y} = 1.0\times 1.5 - 1.0\times 0.5 = 1.0, \qquad C = \frac{1}{2}(1.0-2)^2 = 0.5.
  2. Backward pass: δ(2)=y^−y=−1.0,∂C∂W(2)=(−1.5−0.5),∂C∂b(2)=−1.0.\delta^{(2)} = \hat{y} - y = -1.0, \qquad \frac{\partial C}{\partial W^{(2)}} = \begin{pmatrix} -1.5 & -0.5 \end{pmatrix}, \qquad \frac{\partial C}{\partial b^{(2)}} = -1.0. δ(1)=(1.0−1.0)(−1.0)⊙(11)=(−1.01.0),∂C∂W(1)=(−1.0−2.01.02.0),∂C∂b(1)=(−1.01.0).\delta^{(1)} = \begin{pmatrix} 1.0 \\ -1.0 \end{pmatrix}(-1.0) \odot \begin{pmatrix} 1 \\ 1 \end{pmatrix} = \begin{pmatrix} -1.0 \\ 1.0 \end{pmatrix}, \qquad \frac{\partial C}{\partial W^{(1)}} = \begin{pmatrix} -1.0 & -2.0 \\ 1.0 & 2.0 \end{pmatrix}, \qquad \frac{\partial C}{\partial b^{(1)}} = \begin{pmatrix} -1.0 \\ 1.0 \end{pmatrix}.
  3. One update step (η=0.05\eta = 0.05): Updating gives Wnew(2)=(1.075,−0.975), bnew(2)=0.05W^{(2)}_{\text{new}} = (1.075, -0.975),\ b^{(2)}_{\text{new}} = 0.05, Wnew(1)=(0.550.600.95−0.35), bnew(1)=(0.05−0.05)W^{(1)}_{\text{new}} = \begin{pmatrix} 0.55 & 0.60 \\ 0.95 & -0.35 \end{pmatrix},\ b^{(1)}_{\text{new}} = \begin{pmatrix} 0.05 \\ -0.05 \end{pmatrix}. Re-evaluating forward gives a(1)′=(1.80,0.20)⊤a^{(1)'} = (1.80, 0.20)^\top, y^′=1.79\hat{y}' = 1.79, and C′=0.02205C' = 0.02205 — a 95.6%95.6\% drop in a single step.
y^=1.000\hat{y} = 1.000 / 2.000 · C=0.50000C = 0.50000
0.50 0.50 1.00 -0.25 1.00 -1.00 x₁ 1.00 x₂ 2.00 h₁ a₁=1.50 b₁=0.00 h₂ a₂=0.50 b₂=0.00 ŷ 1.00 b₃=0.00 Loss C 0.5000 y = 2.0
z1=1.50,  z2=0.50  ⟹  y^=1.00⋅1.50+(−1.00)⋅0.50+0.00=1.000z_1 = 1.50,\; z_2 = 0.50 \implies \hat{y} = 1.00\cdot 1.50 + (-1.00)\cdot 0.50 +0.00 = 1.000

Three Changes in Practice#

  1. Softmax + Cross-Entropy for classification: With Sigmoid and squared error, the output gradient δ=(a−y)a(1−a)\delta = (a-y)a(1-a) vanishes when a prediction is confidently wrong (e.g., y=1,z=−10y=1, z=-10) because σ′(z)→0\sigma'(z) \to 0. Using Softmax pi=ezi∑jezjp_i = \frac{e^{z_i}}{\sum_j e^{z_j}} with cross-entropy L=−log⁡pcL = -\log p_c cancels the saturating derivative: ∂L∂zi=pi−yi.\boxed{\frac{\partial L}{\partial z_i} = p_i - y_i.}
Jump:
z=−6.0z = -6.0 · σ(z)=0.0025\sigma(z) = 0.0025 · CE 0.99750.9975 vs MSE 0.002460.00246 (405.4×405.4\times)
Loss L(z) (y=1)L(z)\ (y=1)
-10-50510 0135
Gradient ∣∂L∂z∣\left|\frac{\partial L}{\partial z}\right|
-10-50510 00.250.51
Cross-Entropy (solid) Sigmoid + MSE (dashed)
  1. ReLU instead of Sigmoid in hidden layers: Since σ′(z)≤14\sigma'(z) \le \frac{1}{4}, ten Sigmoid layers shrink gradients by roughly (1/4)10≈10−6(1/4)^{10} \approx 10^{-6}. ReLU(z)=max⁡(0,z)\mathrm{ReLU}(z)=\max(0,z) has derivative 11 on the positive half-line, mitigating vanishing gradients (modern Transformers also use smooth variants such as GELU [2]).
  2. Mini-batches and reverse-mode autodiff: Training evaluates gradients over mini-batches in parallel and updates weights with SGD or Adam. More generally, backpropagation is reverse-mode automatic differentiation over a directed acyclic computation graph — the exact mechanism behind PyTorch’s loss.backward().

From Text to Vectors: Tokenization and Embeddings#

Fully connected networks expect fixed-size numeric vectors, whereas text has variable length, order-dependent meaning, and context-dependent words (e.g., mole can mean an animal, a chemical unit, or a skin mark).

The remainder of this post focuses on autoregressive (Decoder-only) Transformers using the one row per token convention: for sequence length nn and hidden width dd, hidden states form a matrix H∈Rn×dH \in \mathbb{R}^{n \times d}.

Tokenization, Embeddings, and Superposition#

A tokenizer (such as BPE) splits text into discrete token IDs. For vocabulary size VV, a trainable embedding table E∈RV×dE \in \mathbb{R}^{V \times d} maps ID ii to row Ei∈RdE_i \in \mathbb{R}^d. Embeddings learned via prediction objectives (such as Word2Vec CBOW / Skip-gram [3]) place contextually similar words into semantic clusters, with some relations appearing as approximate linear offsets (eking−eman+ewoman≈equeene_{\text{king}} - e_{\text{man}} + e_{\text{woman}} \approx e_{\text{queen}}).

Word embedding semantic clusters before and after training

Two independent random unit vectors u,vu, v on the dd-dimensional unit sphere have inner product mean 00 and variance Var(u⋅v)=1/d\mathrm{Var}(u \cdot v) = 1/d. At d=4096d = 4096, the standard deviation is just 1/64≈0.01561/64 \approx 0.0156. When features are sparse, a dd-dimensional space can therefore pack far more than dd nearly orthogonal feature directions — a phenomenon called superposition [4].

Run a few steps of Skip-gram training with negative sampling and watch how the example words move in the embedding space. Switch to the high-dimensional view to compare the spread of random inner products across dimensions.

Step 0 · L=0.7681L = 0.7681 · E0=(0.85, 0.40)E_{0} = (0.85,\ 0.40) (king)
Embedding Space E∈R8×2E \in \mathbb{R}^{8\times 2}
kingqueenprinceappleorangepeardogcat
Lookup Table E∈R8×2E \in \mathbb{R}^{8\times 2}
idtokene1e_1e2e_2
0king0.850.40
1queen-0.95-0.55
2prince0.15-0.90
3apple0.700.55
4orange-0.350.85
5pear-0.80-0.35
6dog0.45-0.75
7cat-0.650.60
Pos u⋅vu\cdot v
-0.31
Neg u⋅vu\cdot v
-0.05
Superposition vs. the Johnson–Lindenstrauss Lemma

The Johnson–Lindenstrauss lemma guarantees approximate pairwise distance preservation under random low-dimensional projections and illustrates high-dimensional near-orthogonality, but it is not a lossless fact-storage capacity formula for language models; actual capacity depends on feature sparsity and interference tolerance.

Self-Attention#

Single-Head Matrix Form and Causal Masking#

Given H∈Rn×dH \in \mathbb{R}^{n \times d}, project with WQ,WK∈Rd×dkW_Q, W_K \in \mathbb{R}^{d \times d_k} and WV∈Rd×dvW_V \in \mathbb{R}^{d \times d_v} to obtain Q=HWQQ = H W_Q, K=HWKK = H W_K, and Vh=HWVV_h = H W_V, then compute scaled dot-product attention [5]:

S=QK⊤dk+M∈Rn×n,Aij=exp⁡(Sij)∑r=1nexp⁡(Sir),O=AVh∈Rn×dv.S = \frac{QK^\top}{\sqrt{d_k}} + M \in \mathbb{R}^{n \times n}, \qquad A_{ij} = \frac{\exp(S_{ij})}{\sum_{r=1}^n \exp(S_{ir})}, \qquad O = A V_h \in \mathbb{R}^{n \times d_v}.

Dividing by dk\sqrt{d_k} keeps dot-product variance independent of dkd_k so Softmax does not saturate. In autoregressive models, the causal mask sets Mij=0 (j≤i)M_{ij} = 0\ (j \le i) and Mij=−∞ (j>i)M_{ij} = -\infty\ (j > i) so future positions receive exact weight 00, allowing parallel training across all positions while preserving sequential generation at inference.

Worked 3-Token Example#

Take n=3, dk=dv=2n = 3,\ d_k = d_v = 2 with:

Q=(100111),K=(100111),Vh=(200411).Q = \begin{pmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{pmatrix}, \qquad K = \begin{pmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{pmatrix}, \qquad V_h = \begin{pmatrix} 2 & 0 \\ 0 & 4 \\ 1 & 1 \end{pmatrix}.

Computing QK⊤QK^\top, dividing by 2≈1.414\sqrt{2} \approx 1.414, applying the causal mask MM, taking row-wise Softmax, and multiplying by VhV_h:

S=(0.71−∞−∞00.71−∞0.710.711.41)→softmaxA≈(1.00000.330.6700.250.250.50)→×VhO=(2.000.000.662.681.001.50).S = \begin{pmatrix} 0.71 & -\infty & -\infty \\ 0 & 0.71 & -\infty \\ 0.71 & 0.71 & 1.41 \end{pmatrix} \xrightarrow{\text{softmax}} A \approx \begin{pmatrix} 1.00 & 0 & 0 \\ 0.33 & 0.67 & 0 \\ 0.25 & 0.25 & 0.50 \end{pmatrix} \xrightarrow{\times V_h} O = \begin{pmatrix} 2.00 & 0.00 \\ 0.66 & 2.68 \\ 1.00 & 1.50 \end{pmatrix}.

Position 3 combines all three values with weights (0.25,0.25,0.50)(0.25, 0.25, 0.50). Toggle the causal mask and scaling or drag q3q_3 below:

Query "creature" · ΔE⃗=(0.79, 0.79)\Delta \vec{E} = (0.79,\ 0.79)
Weights A=softmax(QK⊤/dk+M)A = \mathrm{softmax}(QK^\top/\sqrt{d_k} + M)
Q\KQ \backslash KAfluffybluecreature
A1.00−∞-\infty−∞-\infty−∞-\infty
fluffy0.180.82−∞-\infty−∞-\infty
blue0.140.220.64−∞-\infty
creature0.070.400.400.12
E⃗′(creature)=E⃗+ΔE⃗\vec{E}'(\text{creature}) = \vec{E} + \Delta\vec{E}
← plain fluffy → blue ↑ creature′
ΔE⃗=0.07 vA+0.40 vfluffy+0.40 vblue+0.12 vcreature=(0.79, 0.79)\Delta\vec{E} = 0.07\,v_{\text{A}} + 0.40\,v_{\text{fluffy}} + 0.40\,v_{\text{blue}} + 0.12\,v_{\text{creature}} = (0.79,\ 0.79)

Multi-Head Attention and Complexity#

Multi-head attention (MHA) runs hh heads in parallel, concatenates their outputs, and projects back to width dd via WO∈Rhdv×dW_O \in \mathbb{R}^{hd_v \times d}:

MHA(H)=Concat(O1,…,Oh) WO=∑r=1hOrWO(r).\mathrm{MHA}(H) = \mathrm{Concat}(O_1, \dots, O_h)\,W_O = \sum_{r=1}^{h} O_r W_O^{(r)}.

Computing QK⊤QK^\top and AVhAV_h takes O(n2d)O(n^2 d) arithmetic operations. A naive implementation also uses O(n2)O(n^2) memory to materialize the attention matrix; FlashAttention [6] uses tiling and recomputation to cut memory to O(n)O(n) while still computing exact dense O(n2)O(n^2) attention.

Positional Encoding and RoPE#

Without masking or position signals, applying any permutation matrix PP to the input rows (H′=PHH' = PH) yields:

softmax ⁣(PQ(PK)⊤dk)PV=P Attention(Q,K,V).\mathrm{softmax}\!\left(\frac{PQ(PK)^\top}{\sqrt{d_k}}\right) PV = P\,\mathrm{Attention}(Q, K, V).

Self-attention is permutation-equivariant and needs explicit position encoding. Modern models widely use Rotary Position Embedding (RoPE) [7]: pair adjacent coordinates of q,k∈Rdkq, k \in \mathbb{R}^{d_k} and rotate position mm‘s pair by Rmθ=(cos⁡mθ−sin⁡mθsin⁡mθcos⁡mθ)R_{m\theta} = \begin{pmatrix} \cos m\theta & -\sin m\theta \\ \sin m\theta & \cos m\theta \end{pmatrix} and position nn‘s pair by RnθR_{n\theta}. By orthogonality Rmθ⊤Rnθ=R(n−m)θR_{m\theta}^\top R_{n\theta} = R_{(n-m)\theta}:

(Rmθ q)⊤(Rnθ k)=q⊤R(n−m)θ k.(R_{m\theta}\, q)^\top (R_{n\theta}\, k) = q^\top R_{(n-m)\theta}\, k.

Position enters the dot product strictly through the relative offset n−mn - m. Click Shift m, n (+1) below to verify this invariance directly:

m=2,  n=5,  n−m=3m = 2,\; n = 5,\; n - m = 3 · High ⟨q,k⟩=−0.6000\langle q, k \rangle = -0.6000 · Low ⟨q,k⟩=0.5754\langle q, k \rangle = 0.5754
High freq θ=30∘\theta = 30^\circ · 126.9∘126.9^\circ
q k
Low freq θ=6∘\theta = 6^\circ · 54.9∘54.9^\circ
q k

Feed-Forward Networks, Normalization, and the Decoder Block#

Modern autoregressive LLMs use a Pre-LN Decoder Block:

U=H+MHA(LN(H)),H′=U+FFN(LN(U)).U = H + \mathrm{MHA}(\mathrm{LN}(H)), \qquad H' = U + \mathrm{FFN}(\mathrm{LN}(U)).

Because sequence lengths vary and decoding runs one token at a time, LayerNorm [8] normalizes each token’s own dd-dimensional vector rather than relying on batch statistics like BatchNorm [9]:

LN(x)=γ⊙x−μσ2+ϵ+β.\mathrm{LN}(x) = \gamma \odot \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta.

The feed-forward network FFN(x)=W2 ϕ(W1x+b1)+b2\mathrm{FFN}(x) = W_2\,\phi(W_1 x + b_1) + b_2 transforms each position independently, typically with dff=4dd_{ff} = 4d. Geva et al. (2021) [10] interpret it as key-value memory: rows of W1W_1 match input patterns and columns of W2W_2 write corresponding updates into the residual stream. Under the standard dimensions hdk=hdv=d, dff=4dh d_k = h d_v = d,\ d_{ff} = 4d (ignoring biases and norms), the per-layer parameter budget is:

SublayerParameter MatricesParametersShare
Multi-Head Attention (MHA)WQ,WK,WV,WO∈Rd×dW_Q, W_K, W_V, W_O \in \mathbb{R}^{d \times d}4d24d^21/31/3
Feed-Forward Network (FFN)W1∈R4d×d, W2∈Rd×4dW_1 \in \mathbb{R}^{4d \times d},\ W_2 \in \mathbb{R}^{d \times 4d}8d28d^22/32/3
Layer Total—12d212d^2100%100\%

In the toy model below, toggle Michael and Jordan to see which feature combination activates the basketball association. The ReLU threshold controls which association is written to the residual stream.

Input xx:
Residual write: +Basketball
Michael∧Jordan\text{Michael} \land \text{Jordan} z=2.0−1.4=0.6z = 2.0 -1.4 = 0.6
ReLU(z)=0.6\mathrm{ReLU}(z) = 0.6
+Basketball
Eiffel∧Tower\text{Eiffel} \land \text{Tower} z=0.0−1.4=−1.4z = 0.0 -1.4 = -1.4
ReLU(z)=0.0\mathrm{ReLU}(z) = 0.0
+Paris
¬Michael∧Jordan\neg\text{Michael} \land \text{Jordan} z=0.0−0.4=−0.4z = 0.0 -0.4 = -0.4
ReLU(z)=0.0\mathrm{ReLU}(z) = 0.0
+Country (Jordan)

Autoregressive Inference, KV Cache, and Modern Variants#

The full single-step forward pass and autoregressive decoding loop look like this:

Autoregressive LLM inference and Decoder Block dataflow

After LL Decoder Blocks, the final-position hidden vector hL∈Rdh_L \in \mathbb{R}^d passes through a final normalization and unembedding projection WU∈Rd×VW_U \in \mathbb{R}^{d \times V} to produce vocabulary logits zz. Dividing by temperature T>0T > 0 gives the sampling distribution pi=exp⁡(zi/T)/∑jexp⁡(zj/T)p_i = \exp(z_i/T)/\sum_j \exp(z_j/T), from which Top-kk / Top-pp sampling picks the next token and appends it to the context until EOS.

KV Cache and Memory Bandwidth#

Because causal masking prevents earlier tokens from attending to later ones, prefix keys and values remain unchanged across decoding steps. Caching them lets step tt compute only qt,kt,vtq_t, k_t, v_t for the single new token. For LL layers, context length nn, batch size BB, hkvh_{kv} KV heads, head dimension dkd_k, and bb bytes per element:

MemoryKV=2⋅B⋅L⋅n⋅hkv⋅dk⋅b.\mathrm{Memory}_{\text{KV}} = 2 \cdot B \cdot L \cdot n \cdot h_{kv} \cdot d_k \cdot b.

With L=80,hkv=64,dk=128,b=2L=80, h_{kv}=64, d_k=128, b=2 (BF16), a single 32K32\text{K}-context request under standard MHA requires roughly 85.9 GB85.9\ \text{GB} of KV Cache — already exceeding a single 80 GB GPU.

Four Key Upgrades in Modern LLMs#

From GPT-2 [11] to current open-weight models, the overall skeleton remains the same while four components have been replaced to ease compute and memory bottlenecks:

  1. RMSNorm [12]: drops mean centering and rescales solely by the root mean square 1d∑xi2\sqrt{\frac{1}{d}\sum x_i^2} times γ\gamma.
  2. SwiGLU [13]: gated three-matrix block (Swish(W1x)⊙W3x)W2\bigl(\mathrm{Swish}(W_1 x) \odot W_3 x\bigr) W_2 with intermediate width 83d\frac{8}{3}d to keep parameter count near 8d28d^2.
  3. MQA and GQA [14][15]: directly shrink hkvh_{kv} in the KV Cache formula. Llama 2 70B [16], for instance, shares 8 KV groups across 64 query heads, cutting KV Cache memory to 1/81/8 of standard MHA.
  4. MLA (Multi-head Latent Attention) [17]: DeepSeek-V2 jointly compresses KK and VV into a low-dimensional latent vector and absorbs the up-projection matrices at inference, reducing KV Cache by 93.3%93.3\% relative to DeepSeek 67B.
L=80,  hq=64,  n=32K,  B=1L=80,\; h_q=64,\; n=32\text{K},\; B=1 · BF16 · MHA 85.90 GB → GQA 10.74 GB → MLA 3.02 GB
MHA (64 KV) 85.90 GB (100.0%)
GQA (8 KV) 10.74 GB (12.5%)
MLA (576) 3.02 GB (3.5%)
MQA (1 KV) 1.34 GB (1.6%)

Red vertical line: 80 GB GPU VRAM (decimal GB, dₖ = 128).

References#

  1. Rumelhart, Hinton & Williams: Learning representations by back-propagating errors (1986) ↗
  2. Hendrycks & Gimpel: Gaussian Error Linear Units (2016) ↗
  3. Mikolov et al.: Efficient Estimation of Word Representations in Vector Space (2013) ↗
  4. Elhage et al.: Toy Models of Superposition (2022) ↗
  5. Vaswani et al.: Attention Is All You Need (2017) ↗
  6. Dao et al.: FlashAttention (2022) ↗
  7. Su et al.: RoFormer (2021) ↗
  8. Ba et al.: Layer Normalization (2016) ↗
  9. Ioffe & Szegedy: Batch Normalization (2015) ↗
  10. Geva et al.: Transformer Feed-Forward Layers Are Key-Value Memories (2021) ↗
  11. Radford et al.: Language Models are Unsupervised Multitask Learners (2019) ↗
  12. Zhang & Sennrich: Root Mean Square Layer Normalization (2019) ↗
  13. Shazeer: GLU Variants Improve Transformer (2020) ↗
  14. Shazeer: Fast Transformer Decoding (2019) ↗
  15. Ainslie et al.: GQA (2023) ↗
  16. Touvron et al.: Llama 2 (2023) ↗
  17. DeepSeek-AI: DeepSeek-V2 (2024) ↗
A Brief Introduction to Deep Learning
https://fxj.wiki/en/blog/deep-learning-brief
Author MakkaPakka
Published at May 27, 2026
Comment seems to stuck. Try to refresh?✨