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.
Prerequisites: matrix multiplication and the chain rule for composite functions.
From Handcrafted Rules to Parameterized Functions#
In MNIST handwritten digit recognition, each input is a 28×28=784 grayscale image with pixel values normalized to [0,1], and the output is a score for each digit from 0 to 9. 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.
With two inputs x1,x2, a single neuron performs two steps:
z=w1x1+w2x2+b,a=σ(z).
Here w1,w2 are weights controlling each input’s direction and magnitude, b is a bias shifting the activation threshold, and σ is a nonlinear activation function.
A classic activation function is Sigmoid:
σ(z)=1+e−z1.
It maps real numbers into (0,1), and its derivative satisfies:
Because t(1−t) attains its maximum 41 at t=21, we have 0<σ′(z)≤41 for every z. This upper bound directly affects gradient propagation in deep networks.
Without hidden-layer activations, stacking two linear layers collapses into a single affine map:
W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2).
Setting W′=W2W1 and b′=W2b1+b2 yields W′x+b′. Regardless of depth, removing nonlinear activations reduces the network to a single linear model that cannot represent nonlinear decision boundaries.
In the fully connected sections we let wjk(l) denote the weight in layer l connecting neuron k in layer l−1 to neuron j in layer l. Row j of W(l) holds all incoming weights of neuron j, and column k holds all outgoing weights of neuron k from the previous layer. Forward propagation through layer l is:
z(l)=W(l)a(l−1)+b(l),a(l)=σ(z(l)).
Consider a 784→16→16→10 MLP for MNIST:
Connection
Weight Matrix Shape
Weights
Biases
Input → Hidden 1
16×784
12,544
16
Hidden 1 → Hidden 2
16×16
256
16
Hidden 2 → Output
10×16
160
10
Total
—
12,960
42
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.
Collect all network parameters into a vector θ. For a single sample, start with squared error between output a(L) and one-hot label y (the 21 cancels the exponent 2 upon differentiation):
C0=21j=1∑10(aj(L)−yj)2,C(θ)=N1n=1∑NCn(θ).
Consider a small displacement Δθ of fixed length ∥Δθ∥=ε. By first-order Taylor expansion:
C(θ+Δθ)−C(θ)≈∇C(θ)⋅Δθ=∥∇C(θ)∥∥Δθ∥cosα,
where α is the angle between Δθ and ∇C(θ). To make C(θ+Δθ)−C(θ) as negative as possible, choose cosα=−1, meaning Δθ points opposite to ∇C(θ):
Take the 1D quadratic C(w)=(w−3)2 with derivative C′(w)=2(w−3) and minimum at w=3. Starting from w0=0 and iterating wt+1=wt−2η(wt−3):
Learning rate η
First four steps w0→w1→w2→w3→w4
Behavior
η=0.1
0→0.6→1.08→1.464→1.771
Monotonic convergence to 3
η=0.5
0→3→3→3→3
Exact minimum in one step
η=1.0
0→6→0→6→0
Constant-amplitude oscillation
η=1.2
0→7.2→−2.88→11.23→−8.52
Growing 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:
Estimating each partial derivative via finite differences ∂wi∂C≈ϵC(wi+ϵ)−C(wi) costs O(PF) for P parameters and forward cost F, 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) time.
For a two-layer network with one neuron per layer:
xw1,b1z1σa1w2,b2z2σa2⟶C=21(a2−y)2.
Define the layer-l error signal δl≡∂zl∂C. Differentiating with respect to w2 gives δ2=(a2−y)σ′(z2) and ∂w2∂C=δ2a1; differentiating with respect to w1 reuses δ2 to give δ1=δ2w2σ′(z1) and ∂w1∂C=δ1x.
In a general multilayer network, neuron ak(l) feeds into every unit z1(l+1),z2(l+1),… of the next layer, so the multivariable chain rule sums all outgoing branches:
∂ak(l)∂C=j∑wjk(l+1)δj(l+1).
Forward propagation sums over row indices (W(l+1)a(l)), while backpropagation sums over column k, which is precisely the transpose (W(l+1))⊤δ(l+1). This yields the four core backpropagation equations (⊙ denotes elementwise multiplication):
One update step (η=0.05):
Updating gives Wnew(2)=(1.075,−0.975),bnew(2)=0.05, Wnew(1)=(0.550.950.60−0.35),bnew(1)=(0.05−0.05). Re-evaluating forward gives a(1)′=(1.80,0.20)⊤, y^′=1.79, and C′=0.02205 — a 95.6% drop in a single step.
Softmax + Cross-Entropy for classification: With Sigmoid and squared error, the output gradient δ=(a−y)a(1−a) vanishes when a prediction is confidently wrong (e.g., y=1,z=−10) because σ′(z)→0. Using Softmax pi=∑jezjezi with cross-entropy L=−logpc cancels the saturating derivative:
∂zi∂L=pi−yi.
z=−6.0 · σ(z)=0.0025 · CE 0.9975 vs MSE 0.00246 (405.4×)
Loss L(z)(y=1)
Gradient ∂z∂L
Cross-Entropy (solid)Sigmoid + MSE (dashed)
ReLU instead of Sigmoid in hidden layers: Since σ′(z)≤41, ten Sigmoid layers shrink gradients by roughly (1/4)10≈10−6. ReLU(z)=max(0,z) has derivative 1 on the positive half-line, mitigating vanishing gradients (modern Transformers also use smooth variants such as GELU [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 n and hidden width d, hidden states form a matrix H∈Rn×d.
A tokenizer (such as BPE) splits text into discrete token IDs. For vocabulary size V, a trainable embedding table E∈RV×d maps ID i to row Ei∈Rd. 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≈equeen).
Two independent random unit vectors u,v on the d-dimensional unit sphere have inner product mean 0 and variance Var(u⋅v)=1/d. At d=4096, the standard deviation is just 1/64≈0.0156. When features are sparse, a d-dimensional space can therefore pack far more than d 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.7681 · E0=(0.85,0.40) (king)
Embedding Space E∈R8×2
Lookup Table E∈R8×2
id
token
e1
e2
0
king
0.85
0.40
1
queen
-0.95
-0.55
2
prince
0.15
-0.90
3
apple
0.70
0.55
4
orange
-0.35
0.85
5
pear
-0.80
-0.35
6
dog
0.45
-0.75
7
cat
-0.65
0.60
Pos u⋅v
-0.31
Neg u⋅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.
Dividing by dk keeps dot-product variance independent of dk so Softmax does not saturate. In autoregressive models, the causal mask sets Mij=0(j≤i) and Mij=−∞(j>i) so future positions receive exact weight 0, allowing parallel training across all positions while preserving sequential generation at inference.
Multi-head attention (MHA) runs h heads in parallel, concatenates their outputs, and projects back to width d via WO∈Rhdv×d:
MHA(H)=Concat(O1,…,Oh)WO=r=1∑hOrWO(r).
Computing QK⊤ and AVh takes O(n2d) arithmetic operations. A naive implementation also uses O(n2) memory to materialize the attention matrix; FlashAttention [6] uses tiling and recomputation to cut memory to O(n) while still computing exact dense O(n2) attention.
Without masking or position signals, applying any permutation matrix P to the input rows (H′=PH) yields:
softmax(dkPQ(PK)⊤)PV=PAttention(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∈Rdk and rotate position m‘s pair by Rmθ=(cosmθsinmθ−sinmθcosmθ) and position n‘s pair by Rnθ. By orthogonality Rmθ⊤Rnθ=R(n−m)θ:
(Rmθq)⊤(Rnθk)=q⊤R(n−m)θk.
Position enters the dot product strictly through the relative offset n−m. Click Shift m, n (+1) below to verify this invariance directly:
m=2,n=5,n−m=3 · High ⟨q,k⟩=−0.6000 · Low ⟨q,k⟩=0.5754
High freq θ=30∘ · 126.9∘
Low freq θ=6∘ · 54.9∘
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)).
Because sequence lengths vary and decoding runs one token at a time, LayerNorm [8] normalizes each token’s own d-dimensional vector rather than relying on batch statistics like BatchNorm [9]:
LN(x)=γ⊙σ2+ϵx−μ+β.
The feed-forward network FFN(x)=W2ϕ(W1x+b1)+b2 transforms each position independently, typically with dff=4d. Geva et al. (2021) [10] interpret it as key-value memory: rows of W1 match input patterns and columns of W2 write corresponding updates into the residual stream. Under the standard dimensions hdk=hdv=d,dff=4d (ignoring biases and norms), the per-layer parameter budget is:
Sublayer
Parameter Matrices
Parameters
Share
Multi-Head Attention (MHA)
WQ,WK,WV,WO∈Rd×d
4d2
1/3
Feed-Forward Network (FFN)
W1∈R4d×d,W2∈Rd×4d
8d2
2/3
Layer Total
—
12d2
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.
Residual write: +Basketball
Michael∧Jordanz=2.0−1.4=0.6
ReLU(z)=0.6
+Basketball
Eiffel∧Towerz=0.0−1.4=−1.4
ReLU(z)=0.0
+Paris
¬Michael∧Jordanz=0.0−0.4=−0.4
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:
After L Decoder Blocks, the final-position hidden vector hL∈Rd passes through a final normalization and unembedding projection WU∈Rd×V to produce vocabulary logits z. Dividing by temperature T>0 gives the sampling distribution pi=exp(zi/T)/∑jexp(zj/T), from which Top-k / Top-p sampling picks the next token and appends it to the context until EOS.
Because causal masking prevents earlier tokens from attending to later ones, prefix keys and values remain unchanged across decoding steps. Caching them lets step t compute only qt,kt,vt for the single new token. For L layers, context length n, batch size B, hkv KV heads, head dimension dk, and b bytes per element:
MemoryKV=2⋅B⋅L⋅n⋅hkv⋅dk⋅b.
With L=80,hkv=64,dk=128,b=2 (BF16), a single 32K-context request under standard MHA requires roughly 85.9GB of KV Cache — already exceeding a single 80 GB GPU.
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:
RMSNorm [12]: drops mean centering and rescales solely by the root mean square d1∑xi2 times γ.
SwiGLU [13]: gated three-matrix block (Swish(W1x)⊙W3x)W2 with intermediate width 38d to keep parameter count near 8d2.
MQA and GQA [14][15]: directly shrink hkv 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/8 of standard MHA.
MLA (Multi-head Latent Attention) [17]: DeepSeek-V2 jointly compresses K and V into a low-dimensional latent vector and absorbs the up-projection matrices at inference, reducing KV Cache by 93.3% relative to DeepSeek 67B.