Skip to content
← writing

The math behind deep learning

Jan 21, 2026 · 50 min read · ml

contents
  1. 1time for some calculus
  2. 2how do we take this "step" in the right direction
  3. 3feed forward neural network (FFN)
  4. 4backpropagation
  5. 5batch normalisation
  6. 6resnets ~ residual networks
  7. 7transformers
  8. 8conclusion

Why do we even need math for AI? Computers understand numbers, not words. We didn't either. We learned what words mean and how sentences carry meaning from years of examples and labels. Teaching a computer is the same idea, minus the 12 years: it's basic math.

So how do we teach these computers? We must ask, how did we teach ourselves.

Geoffrey Hinton (cognitive psychologist and computer scientist) studied psychology because he wanted to know how a human learns. We all have neurons in our brains. Somehow they capture the relationships between things in our lives. How do these neurons work? Each neuron connects to other neurons, passes messages to them, and learns over time.

For example -> How do we know the difference between a car and a bike? Simple; since childhood we have seen millions of cars and bikes. Our parents told us "this is a car" or "this is a bike", and somehow our brain kept that information.

Geoffrey Hinton wanted computers to learn in a similar way. He did not want to hard-code rules. He wanted to show the computer examples and labels, and give it 'neurons' that learn from them.

Neurons connected together make a neural network (like ours make a brain).

Making the neurons in a neural network learn a task is the basis of AI.

Before jumping into neural networks, what does 1 neuron compute?

You can think of a neuron as a function. It has some inputs -> function -> output

These inputs have weights associated with them. They define how significant that input is to the function.

A neuron:

  • Receives inputs
  • Performs some computation
  • Gives back output

neuron

This computation has 2 stages

  • Multiply each weight (importance we give to the input) with inputs and sum them.
  • Sum of weighted inputs is passed through an 'activation function' to produce output

Now you might have some questions. The first stage makes sense: it is the line equation we studied as kids, y=wx+by = wx + b, with more inputs. Each weight is the slope for its input.

y=activation_function(b+∑iwixi)y = \text{activation\_function}\left( b + \sum_i w_i x_i \right)

here b = bias (allows sum to be non zero (even if all inputs (xix_i) are 0)) -> think of bias as another weight

What the hell is an activation function and why are we passing our sum (stage1) output to it?

  • Activation functions decide if a neuron should "fire" based on its input.
  • If the input looks important for prediction, the function activates the neuron. Otherwise it doesn't.

Different neurons can have different activation functions

  • Linear function (the activation function is y = x) ~ Used for regression tasks
  • Step function (y = 0 if x ≤ 0, y = 1 if x > 0) ~ Used for classification tasks
  • Many more (we'll discuss them in a bit)

So what problem are we solving here?

For any ML or deep learning problem, we choose the weights and biases (the parameters) that best represent our dataset -> This is called 'training'

Think about learning cars and bikes as a kid. Both have the same features (tyres, engine etc) but with different values. We look at millions of cars and bikes and learn which is which. So when we see a new car (or something that looks like a car) we can confidently say "Oh that's a car"

To do this 'training' we need a loss function.

The loss function measures how wrong the model is, for the current parameter values, at representing our data.

For example, we show the model a photo of a car and it predicts truck. We need a loss function to tell the model "Oops, you made an error there, that's not accurate representation of our data, please adjust yourself to learn it's a car"

To score the error as a number, the model outputs a number (a confidence for "car") and we compare it to the target. A good loss function -> sum of squared errors.

Loss=∑(ytarget−yprediction)2\text{Loss} = \sum (y_{\text{target}} - y_{\text{prediction}})^2

  • y_target is the value we want: for a car photo, the "car" score should be 1
  • y_prediction is the score our model produced

Squaring keeps the error positive and punishes big misses more than small ones. To choose between discrete classes (car vs truck) we later use cross-entropy. Cross-entropy compares probability distributions instead of subtracting labels.

  • We want the loss to be at its minimum. That is where the model is closest to our ground truth.

If we divide the sum by the number of data points NN, we get the mean squared error (MSE):

Loss(w1,w2,…,wn,b)=1N∑(y−model(x))2\begin{aligned} &\text{Loss}(w_1, w_2, \ldots, w_n, b) \\ &= \frac{1}{N} \sum \left( y - \text{model}(x) \right)^2 \end{aligned}

The 1/N1/N does not move the minimum. The toy problem below uses the plain sum, without 1/N1/N.

Now we know how 'wrong' our model is, we can minimise it.

By 'it' here I mean updating the parameters (weights and bias) in a way that reduces the loss (making our model less wrong)

How do we do this??

Gradient Descent

Toy problem time

toy_example

  • x -> input
  • y -> output
  • f is our function y = weights * x + bias

With w = 2 and b = -2, the loss is 10. This is our initial loss.

Our goal is to minimise this, how? We move in the direction that decreases the loss. That direction is the negative of the gradient.

So we need the gradient of this loss function with respect to the weight and the bias

You may ask what even is a gradient??

time for some calculus

All you need to know is partial derivatives

  • How does the output change when we wiggle one input?

  • In single-variable calculus, the derivative dy/dx tells us the rate of change of y with respect to x.

  • But neural networks have millions of parameters. A loss function can depend on weights w1,w2,…,w1000000000w_1, w_2, \ldots, w_{1000000000}.

  • We can't ask "what's the slope?" because the function slopes differently in every direction. Instead, we ask: "How does the output change if I wiggle one input and hold all others constant?"

  • Gradient Descent: The gradient is a vector of partial derivatives.

Computing the partial derivatives for every weight in a neural network is called backpropagation. Finding the direction that reduces the loss the most is called optimization.

Stepping back to calculate the partial derivative for a general neuron, not only the toy problem.

L(w1,w2,w3,…,wn,b)=∑(output−f(x))2\begin{aligned} &L(w_1, w_2, w_3, \ldots, w_n, b) \\ &= \sum \left( \text{output} - f(x) \right)^2 \end{aligned}

A partial derivative is the derivative of a function with respect to 1 input at a time. We treat the other inputs as constants.

For example, take L=x2+y2L = x^2 + y^2. We treat y2y^2 as a constant to get the first result, and x2x^2 as a constant to get the second:

∂L∂x=2x\frac{\partial L}{\partial x} = 2x ∂L∂y=2y\frac{\partial L}{\partial y} = 2y

Okay back to our problem.

L(w1,w2,…,wn,b)=∑(output−f(x))2\begin{aligned} &L(w_1, w_2, \ldots, w_n, b) \\ &= \sum \left( \text{output} - f(x) \right)^2 \end{aligned}

Here X is the error: X=output−prediction=y−f(x)X = \text{output} - \text{prediction} = y - f(x)

∂L∂wi=∑2X(−∂f(x)∂wi)\frac{\partial L}{\partial w_i} = \sum 2X \left( - \frac{\partial f(x)}{\partial w_i} \right)

We also apply the chain rule here.

Derivative of (y-y')^2 is 2 * (y-y') * derivative of (y-y')

∂L∂wi=−2∑(y−f(x))∂f(x)∂wi\frac{\partial L}{\partial w_i} = -2 \sum (y - f(x)) \frac{\partial f(x)}{\partial w_i}

pd

more on chain rule

The chain rule is the whole game. Everything below applies it.

To find the derivative of a composition, multiply the derivatives of each step.

Example:

y=(3x+1)2y = (3x + 1)^2

Let u=3x+1⇒dudx=3u = 3x + 1 \quad \Rightarrow \quad \frac{du}{dx} = 3

Since y=u2⇒dydu=2uy = u^2 \quad \Rightarrow \quad \frac{dy}{du} = 2u

By the chain rule, dydx=dydu⋅dudx=2u⋅3\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx} = 2u \cdot 3

Substituting back u=3x+1u = 3x + 1, dydx=6(3x+1)\frac{dy}{dx} = 6(3x + 1)

forward: compute the value x g: u = 3x + 1 u f: y = u² y du/dx = 3 dy/du = 2u each step knows only its own local derivative backward: multiply the local derivatives dy/dx = 2u · 3 = 6(3x + 1) at x = 2: u = 7, so dy/dx = 42

Figure: The forward pass computes u, then y. The backward pass multiplies the local derivatives of each step. At x = 2, PyTorch autograd also gives 42.

Consider one neuron with a sigmoid activation, σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}). We meet the sigmoid properly in a moment. For now you need one fact: its derivative is σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)).

z=wx+bz = wx + b a=σ(z)a = \sigma(z) L=(a−y)2L = (a - y)^2
  • ∂L/∂a = 2(a-y). This is the derivative of the loss with respect to a only. The dependency of a on z comes in the next chain rule step.

  • ∂a/∂z = σ'(z) = a(1-a)

  • ∂z/∂w = x (remember z = wx + b, so the partial derivative is x)

  • For the bias, ∂z/∂b = 1. So ∂L/∂b = 2(a-y) * a(1-a) * 1

  • Hence ∂L/∂w (partial derivative of the final loss with respect to the weight):

∂L∂w=∂L∂a⋅∂a∂z⋅∂z∂w=2(a−y) a(1−a) x\begin{aligned} \frac{\partial L}{\partial w} &= \frac{\partial L}{\partial a} \cdot \frac{\partial a}{\partial z} \cdot \frac{\partial z}{\partial w} \\ &= 2(a - y)\, a(1 - a)\, x \end{aligned}

that's all the calculus. once the chain rule clicks, everything else is bookkeeping. the derivatives get messier as the network gets deeper, but the idea stays the same: trace how the loss flows backwards through each operation. pytorch does this for you, but you can only debug it if you know what it does under the hood.

Dependencies and computation graph for this:

w→  x  z→  σ  a→  (⋅−y)2  Lw \xrightarrow{\;x\;} z \xrightarrow{\;\sigma\;} a \xrightarrow{\;(\cdot - y)^2\;} L

You can also read 2(a-y) * a(1-a) * x as error * activation derivative * input.

  • Direction of Steepest Ascent
    • The gradient ∇f points in the direction where f increases fastest. If you're standing on a hill, the gradient points uphill.
    • To minimize f (like a loss function), move in the opposite direction: new_params = old_params - small_step * gradient
    • The magnitude ∣∣∇f∣∣ tells you how steep the slope is. Large gradient = steep terrain = big updates.

backprop_For_MSE

more on backpropagation

  • When training a neural network, we need ∂L/∂wi∂L/∂w_i for every weight wiw_i
  • The chain rule computes all of them in one backward sweep through the network. Each layer reuses the gradient of the layer after it.

Back to our toy problem:

  • L(w=2, b=-2) = 10 # we calculated this

Now let's find the gradient vector for this:

toyexamplefinal

how do we take this "step" in the right direction

  • Subtract a 'small multiple' of the gradient from the current value of each parameter
  • This 'small multiple' is the learning rate -> how far we move in one step (e.g -> learning_rate = 0.01)

new = old - learning_rate * gradient

new_weight = 2 - 0.01 * 22 = 1.78

new_bias = -2 - 0.01 * 4 = -2.04

plot_contour

  • Apply the same method to a classification problem and it fails. The step function has a derivative of 0 everywhere (except at 0, where it jumps), so the gradient is 0.
  • To fix this, we make the step smooth -> sigmoid function

So from now on our new activation function is sigmoid function.

derivative_sigmoid

Now we've seen how 1 neuron works. How does it generalise to a "neural network"?

feed forward neural network (FFN)

Hyperparameter: a setting of the model that training does NOT update (e.g: step size/learning_rate, number of iterations, etc...)

nn

The network has 4 inputs, two layers of 3 neurons, and 2 outputs. The two middle layers are the hidden layers.

weights 4 inputs * 3 neurons in the first hidden layer + 3 * 3 neurons in the second hidden layer + 3 * 2 outputs

= 12 + 9 + 6 = 27

also bias 3 for the first hidden layer + 3 for the second + 2 for the outputs = 8

Hence the number of parameters in this neural network = 27 + 8 = 35.

this is what it means when Llama 3.1 405B has 405 billion parameters. It has 405 billion tunable parameters (weights and biases) which training tweaks to find the best results for our answer.

  • What does one computation look like in this neural network?

example_for_comp

Question

  • Why is a neural network with hidden layers better than a single layer?
  • Answer: It isn't better if we use linear activation functions.
    • Why?
  • If we compose 2 linear functions -> the result is another linear function
    • Take f(x) and g(x). Pass x through g, then f, and the output f(g(x)) is still a line. The extra layer DOES NOT HELP. this has no meaning
  • Hence we need non linearity to get some value out of the extra layers.

Examples of non-linearity

nonlin

All in all, this is the entire training process:

  • Save activations on the forward pass
  • The backward pass computes gradients
  • Update weights and biases with the computed gradients

The backward pass is the part called backpropagation (backprop).

how do we train this neural network?

  • We train the parameters of this neural network (weights, biases) -> with gradient descent

  • For each data point, the loss function adds up the errors over all the outputs.

gd

What is the loss in a neural network?

  • For any point jj in the dataset, the loss of the model on that point is a sum over the output neurons. Each term is the squared difference between target and activation

loss_in_nn

backpropagation

For each neuron, compute the partial derivative of the loss with respect to xx, the weighted sum of the inputs at that neuron:

G = ∂L/∂x∂L/∂x

G sets the weight update for every edge coming into that neuron.

backprop

update

  • Average the partial derivatives, but NOT over the entire dataset
  • Pick a random subset and calculate for that subset -> it "can move roughly in the right direction & still reduce error rapidly"
  • To choose this "random sample", shuffle the dataset and group it into batches. For each batch -> compute activations (FORWARD PASS) and partial derivatives (BACKWARD PASS) then UPDATE!!

types of optimisers

Vanilla gradient descent has no memory. Each step uses only the current gradient. It does not know if the gradient kept the same direction for 1000 iterations or turned around on the last step.

Problems:

  • Oscillation: In narrow valleys, SGD bounces back and forth between steep walls. Wasted computation.
  • Slow progress: Along flat directions, gradients are tiny. SGD crawls.
  • Think of a ball rolling down a hill in tiny baby steps. It should pick up speed early on and slow down near the bottom.

Standard SGD treats parameters like a massless particle: apply a force (gradient), it moves; remove the force, it stops.

batch gradient descent

In batch gradient descent, we compute the gradient using the entire dataset:

θt+1=θt−η⋅1N∑i=1N∇L(θt;xi,yi)\theta_{t+1} = \theta_t - \eta \cdot \frac{1}{N} \sum_{i=1}^{N} \nabla L(\theta_t; x_i, y_i)

The gradient is exact (no sampling noise) and convergence is stable. But every step needs a full pass over the data. For a model trained on a large part of the internet, one update would need a pass over trillions of tokens. That makes batch gradient descent impractical for modern deep learning. With no noise, it also can't escape local minima.

stochastic gradient descent (SGD)

Other extreme: stochastic GD uses a single random sample (xi,yi)(x_i, y_i):

θt+1=θt−η⋅∇L(θt;xi,yi)\theta_{t+1} = \theta_t - \eta \cdot \nabla L(\theta_t; x_i, y_i)

Gradient from one sample is noisy. But that noise isn't always bad:

mini-batch SGD

In practice, we use mini-batches: small random subsets of the data. BB is a mini-batch, e.g. ∣B∣=32,64,128,256|B| = 32, 64, 128, 256:

θt+1=θt−η⋅1∣B∣∑i∈B∇L(θt;xi,yi)\theta_{t+1} = \theta_t - \eta \cdot \frac{1}{|B|} \sum_{i \in B} \nabla L(\theta_t; x_i, y_i)

Averaging over ∣B∣|B| samples cuts the standard deviation of the gradient noise by a factor of ∣B∣\sqrt{|B|}. A GPU processes the samples of a batch in parallel, so a bigger batch costs less than its size suggests. The main cost is memory: the batch has to fit on the GPU. The leftover noise even helps. It "kicks" the parameters out of local minima where the average gradient is near zero.

activation functions

  • Until now we used sigmoid for binary classification (2 classes: car, truck)
  • What if we have a multi-class problem? For example, MNIST: predict the correct digit (0 to 9) from an image of a handwritten digit.

What is the problem with sigmoid then??

sigmoid_prob

Alternative : Softmax activation

  • Only for the output / final layer of a classification problem
  • The hidden layers still use sigmoid, since the problem above was only in the final layer

softmax

code

python
import torch
 
def softmax(X):
    # numerically stable softmax (if you still want explicit probs)
    X_shift = X - X.max(dim=1, keepdim=True).values
    X_exp = torch.exp(X_shift)
    partition = X_exp.sum(1, keepdim=True)
    return X_exp / partition
 
 
# Torch has this built in btw.
 
X = torch.rand((2,5))  # random, so your numbers will differ
Xprob = softmax(X)
print(Xprob, Xprob.sum(1)) # each row should sum to 1
 
# tensor([[0.2075, 0.2380, 0.2615, 0.1074, 0.1856],
#         [0.2310, 0.2398, 0.2227, 0.1600, 0.1465]])
# tensor([1., 1.])

What it achieves:

  • It pushes the largest input toward 1
  • It pushes the other inputs toward 0

This is what we want!!

increasing one xix_i decreases others -> sensible probabilities

At inference / testing time the softmax outputs are the class probabilities.

Now the question is::

How to combine this new softmax activation function with a loss function that gives us effective gradient descent updates?

We can't use mean squared error (MSE) Loss.

Why?

  • After softmax, your model predicts a categorical probability distribution, not free numbers.

  • In classification, the true label is usually one-hot encoded: y = [0, 0, 1, 0]. This is also a probability distribution: 100% probability on the correct class, 0% elsewhere.

So the problem becomes: “How different is my predicted probability distribution from the true distribution?”

For this problem, MSE doesn't work... MSE treats probabilities like ordinary numbers, but probabilities are coupled (increasing one decreases others)

The gradient also gets messy. With MSE + sigmoid, the derivative carries the factor p(1−p)p(1-p). With MSE + softmax, take L=∑j(pj−yj)2L = \sum_j (p_j - y_j)^2, where p=softmax(z)p = \text{softmax}(z). The gradient with respect to the logit ziz_i is:

∂L∂zi=2∑j(pj−yj) pj (δij−pi)\frac{\partial L}{\partial z_i} = 2 \sum_j (p_j - y_j)\, p_j\, (\delta_{ij} - p_i)

Here δij\delta_{ij} is 1 when i=ji = j and 0 otherwise. Every term has a factor pjp_j and a factor (δij−pi)(\delta_{ij} - p_i). When the model is confidently wrong, each pp is near 0 or near 1, so one of the two factors is near 0. The gradient vanishes when the model needs it most. I checked this in PyTorch: with logits [8, 0, 0] and the correct class at index 2, the largest MSE gradient is 0.002.

Solution? Cross Entropy Loss

Cross-entropy measures how surprised the model is by the true label:

LCE=−∑iyilog⁡(pi)\mathcal{L}_{CE} = -\sum_i y_i \log(p_i)

For one-hot labels, only the correct class survives the sum:

LCE=−log⁡(pcorrect)\mathcal{L}_{CE} = -\log(p_{\text{correct}})
  • If the model gives high probability to the correct class → low loss
  • If it gives low probability to the correct class → huge penalty

Not going to derive the partial derivative here, but you can do it in your free time. With softmax + cross-entropy, the gradient with respect to the logits is:

∂L∂zi=pi−yi\frac{\partial \mathcal{L}}{\partial z_i} = p_i - y_i
  • With softmax + cross entropy, the derivative is clean and stable. It gives a strong signal even when the model is wrong. For the same logits [8, 0, 0], the gradient is [0.999, 0.0003, -0.9997].

  • When we take a step in the -grad direction -> we increase the activation where the target is 1 and decrease all others.

LLMs use cross-entropy loss for next-token prediction: it penalizes wrong guesses and rewards right ones. If the model is confident about a wrong token, it gets punished hard.

cross entropy loss code

This is the loss function that trains almost all LLMs. It measures how wrong the predicted probabilities are for the correct class.

It is LogSoftmax + Negative Log Likelihood, so the math is −log⁡(softmax)-\log(\text{softmax}) of the correct class.

Given:

  • the scores the model outputs (logits)
  • the correct class index

It answers: “How much probability did you assign to the correct answer?”

  • High probability → low loss
  • Low probability → high loss
python
import torch
 
def main():
    logits = torch.tensor([[2.0, 1.0, 0.1]])  # (batch, num_classes)
    target = torch.tensor([0])               # correct class index (batch_size,)
 
    loss_fn = torch.nn.CrossEntropyLoss()
 
    loss = loss_fn(logits, target)
    print(loss) # tensor(0.4170) (Our goal is to minimise this using backprop)
 
main()

Running through the output. CrossEntropyLoss expects raw logits and applies the softmax itself. Inside, it does three steps:

python
log_probs = log(softmax(logits))                     # Step 1: log(softmax)
correct_log_prob = log_probs[range(batch), target]   # Step 2: pick the correct class
loss = -mean(correct_log_prob)                       # Step 3: negate + average

Here softmax gives [0.659, 0.242, 0.099], and −log⁡(0.659)=0.417-\log(0.659) = 0.417.

In LLMs the logits have shape (batch, seq_len, vocab_size) and the targets are token IDs with shape (batch, seq_len). We flatten both into 1 list and apply the loss:

python
logits = logits.view(-1, vocab_size)       # (batch * seq_len, vocab_size)
targets = targets.view(-1)                 # (batch * seq_len,)
loss = CrossEntropyLoss()(logits, targets)

For each token the loss asks: “How surprised was the model by the correct next token?”

  • High probability on the correct token → low loss
  • Low probability on the correct token → higher loss
  • High confidence in a wrong token (so near 0 on the correct one) → very high loss

The loss is the average over all tokens. A minimal version for one example:

python
def loss(logits, correct_class):
    probs = softmax(logits)
    return -log(probs[correct_class])

how to scale neural networks?

Some problems:

1. vanishing gradients

How does a neural network scale through multiple layers, and what goes wrong?

scale

  • Unfortunately the derivative of the sigmoid is small
  • Each time we go one layer backwards through the network, we multiply by a sigmoid derivative. The gradients get smaller at each layer -> This is the vanishing gradient problem.
  • Information from the loss function -> propagates back -> the early layers don't get updated, because their gradient steps are too small (they vanish)
  • The sigmoid derivative is at most 0.25. The maximum is at 0: sigmoid'(0) = sigmoid(0) * (1-sigmoid(0)) = 0.5*0.5 = 0.25. After 10 layers the factor is at most 0.25^10 ≈ 0.000001
  • The gradient shrinks by at least 75% at every layer, so the early layers learn almost nothing during backprop.

Solution: Use another activation function, for example ReLU. Its derivative is 0 or 1, so an active neuron does not shrink the gradient.

relu

BTW ReLU: f(x)=max(0,x). It is continuous everywhere but has a corner at x = 0 (not differentiable there). Modern LLMs such as Llama use SwiGLU in the feed-forward layers instead. SwiGLU is a gated activation that combines Swish and GLU (gated linear unit). Shazeer (2020, "GLU Variants Improve Transformer") found that it gave better results than ReLU.

relu code

The simplest non-linearity. torch.nn.ReLU kills negative values and lets positive values pass: ReLU(x)=max⁡(0,x)\text{ReLU}(x) = \max(0, x). It has no parameters and learns nothing. It only adds non-linearity, so networks can:

  • model complex functions
  • learn hierarchies
  • represent interactions
python
import torch
 
def main():
    x = torch.tensor([[-2.0, -0.5, 0.0, 1.5, 3.0]])
 
    relu = torch.nn.ReLU()
 
    y = relu(x)
 
    print(y) # tensor([[0.0000, 0.0000, 0.0000, 1.5000, 3.0000]])
 
main()

Running through the output. The output has the same shape as the input. Internally, every negative value becomes 0.

If we backprop, d/dx(ReLU(x)) = 1 if x > 0 else 0. Positive neurons learn normally. Negative neurons get zero gradient.

GPT-2 and BERT use a smoother variant of ReLU called GELU. GELU is smooth at 0 and has a non-zero gradient for most negative inputs, so those neurons still learn a little.

You can look up graphs of ReLU and GELU and instantly tell why it is better.

2. overfitting

  • The model memorises the training set and does badly on new data (this happens when the network is too big for the data)
  • Solution: Dropout (drop some of the neurons randomly)
  • Randomly zero out some of the neurons/activations during training (hyperparameter p)

During training, torch.nn.Dropout zeroes each element of the input tensor with probability p. This reduces overfitting: no neuron can rely on one particular other neuron, because that neuron may be gone on the next step.

To compensate for the dropped neurons, dropout scales the remaining outputs by 1/(1−p)1/(1-p) during training. So during evaluation the module is the identity function (y = x), and we don't scale anything at test time.

Parameters:

  • p (float): probability that an element is zeroed. Default: 0.5
  • inplace (bool): if True, do this operation in-place. Default: False

As a function, with the scaling that keeps the expected value the same:

yi={0with probability pxi1−pwith probability 1−py_i = \begin{cases} 0 & \text{with probability } p \\ \dfrac{x_i}{1-p} & \text{with probability } 1-p \end{cases}

With the default p = 0.5, the scale factor is 1 / (1-0.5) = 2. So we randomly zero out about 50% of the inputs during training and multiply the rest by 2. Makes sense.

python
import torch
def main():
    input_data = [[1., 2., 3.],
                 [4., 5., 6.]]   # shape: (rows/batch=2, columns/features=3) 
    input_data_tensor = torch.Tensor(input_data)
    dropout = torch.nn.Dropout(p=0.5)
 
    after_dropout = dropout(input_data_tensor)
 
    print(f"Shapes of input and output remain the same: {input_data_tensor.shape}, {after_dropout.shape}")
    print(f"Input : {input_data}")
    print(f"Output : {after_dropout}")
 
 
main()
 
# Shapes of input and output remain the same: torch.Size([2, 3]), torch.Size([2, 3])
# Input : [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
# Output : tensor([[ 0.,  4.,  0.],
#                  [ 0.,  0., 12.]])

Running through the output. Dropout zeroed some of the inputs at random and scaled the rest by 2. Each run zeroes different inputs. Running it again gave:

python
# Output : tensor([[ 0.,  0.,  0.],
#                  [ 8., 10., 12.]])

Training mode (model.train())

  • Random masking
  • Scaling applied

Eval mode (model.eval())

  • Dropout is DISABLED
  • Output = input (identity)

The original transformer paper applies dropout to the output of each sub-layer, before the residual add. It also applies dropout to the sum of the token embeddings and the positional encodings. Implementations such as PyTorch's also apply it to the attention weights and to the FFN hidden layer. It is not used on the final logits.

Modern large LLMs often reduce or remove dropout, because the huge amount of training data already regularizes the model.

Where does it go in a network? After the activation:

python
model = torch.nn.Sequential(
    torch.nn.Linear(128, 256),
    torch.nn.ReLU(),
    torch.nn.Dropout(p=0.1),   # HERE
    torch.nn.Linear(256, 10)
)

how to make these optimisers better?

What's wrong with gradient descent / SGD?

  • w = w - learning_rate * gradient for every batch we train on
  • we take 1 step, scaled by learning_rate, in the direction opposite to the gradient.

problem_with_Gd sgdbad

We want a smoother path, straight to the minimum loss, not the zig zag in the image above.

local minima

The classic fear: getting stuck in a local minimum, a shallow valley that isn't the lowest point.

Local Minimum: A point where the function value is lower than at all neighboring points.

  • You're at the bottom of a bowl. Every direction goes UP.
  • A saddle point is the other trap: gradient = 0, but it's a minimum in some directions and a maximum in others.
  • At both, θ_new = θ_old - α * 0 = θ_old (gradient is 0, parameters don't move, the model thinks it has converged)

How to make it better? ADAM.

2 key ideas:

  • Momentum: give it a little push in the direction it is taking steps in:

    • Helps with the plateau problem
    • Helps it roll out of shallow local minima
  • A moving average of the squared partial derivatives

    • It estimates the 'second moment' of the partial derivative (the uncentered variance). Its square root gives the typical gradient size, so we can normalise by it -> similar size steps -> stable training (less zig zag)

adam

Since vanilla gradient descent gets stuck, we use techniques that add "momentum" or "noise"

  • Momentum
    • Like a ball rolling downhill. If it enters a flat saddle region, its existing velocity carries it across the plateau.

    • vt=βvt−1+gtv_t = \beta v_{t-1} + g_t, where gtg_t is the current gradient

Every optimization problem: you have a loss function (landscape of mountains and valleys) and you want to find the lowest point.

What does your landscape look like?

  • Bowl (convex): exactly one lowest point. No matter where you start, you'll get there. Life is good.

  • Egg crate (non-convex): countless dips and valleys. You might roll into a shallow puddle and get stuck, and never find the lowest minimum.

Momentum: treat it like a heavy ball rolling downhill. It has inertia. Once moving, it keeps going in the same direction even if the local slope changes.

  • Velocity v: the ball moves by its accumulated velocity, not only by the current gradient. The gradient is a force that nudges the velocity.
  • Friction beta: without it, the ball oscillates forever. We need some decay so it stops at the bottom.

So instead of updating weights directly with the gradient, we update a velocity vector (SGD with momentum):

vt+1=βvt+η∇L(θt)v_{t+1} = \beta v_t + \eta \nabla L(\theta_t) θt+1=θt−vt+1\theta_{t+1} = \theta_t - v_{t+1}

another problem: learning rates

Momentum uses a single learning rate for all parameters. But neural networks have millions of parameters, and they're not equal:

  • Parameters connected to frequent features (common words, bright pixels) get big, stable gradients.
  • Parameters connected to rare features (unusual words, edge cases) get small, noisy gradients.

Adaptive optimizers give each parameter its own learning rate, based on its gradient history. Rare features can catch up.

the fix: Divide the learning rate by the magnitude of recent gradients. Big gradients get a small effective LR. Small gradients get a large effective LR. Playing field leveled.

RMSprop (Root Mean Square Propagation)

RMSprop keeps an exponential moving average of the squared gradients. The average forgets ancient history.

Moving average:

E[g2]t=βE[g2]t−1+(1−β)gt2E[g^2]_t = \beta E[g^2]_{t-1} + (1 - \beta) g_t^2

Parameter update:

θt+1=θt−ηE[g2]t+ϵ⋅gt\theta_{t+1} = \theta_t - \frac{\eta}{\sqrt{E[g^2]_t} + \epsilon} \cdot g_t

lr

Figure: A fixed learning rate, the adaptive idea, and RMSprop. The RMSprop panel simplifies the formula. The square root is over the moving average of the squared gradients.

Adam (Adaptive Moment Estimation)

the final boss of optimisation. combines momentum + rmsprop

Adam (Kingma and Ba, 2014) keeps two moving averages per parameter. The first moment (mean) is the momentum part:

mt=β1mt−1+(1−β1)gtm_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t

The second moment (uncentered variance) is the RMSprop part:

vt=β2vt−1+(1−β2)gt2v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2

Both averages start at 0, so early on they are biased toward 0. Adam corrects this bias. Here βt\beta^t is β\beta to the power tt, the step number:

m^t=mt1−β1t,v^t=vt1−β2t\hat{m}_t = \frac{m_t}{1 - \beta_1^t}, \qquad \hat{v}_t = \frac{v_t}{1 - \beta_2^t}

Adam update. The ϵ\epsilon goes outside the square root and stops a division by zero:

θt+1=θt−η m^tv^t+ϵ\theta_{t+1} = \theta_t - \frac{\eta \, \hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}

The paper's default settings are η=0.001\eta = 0.001, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 and ϵ=10−8\epsilon = 10^{-8}. These are also the defaults of torch.optim.Adam. The stackgrad post implements AdamW, Adam with decoupled weight decay, from scratch.

batch normalisation

TLDR: it speeds up + stabilises training using mean and variance, nothing fancy here.

Before batch norm (BN), deep networks were a pain to train. Gradients would vanish or explode. BN normalizes the inputs to each layer so training doesn't blow up.

The Batch Normalization Transform (Ioffe and Szegedy, 2015) has three steps. For a mini-batch of mm values of one feature:

Step 1: compute the batch statistics.

μB=1m∑i=1mxiσB2=1m∑i=1m(xi−μB)2\begin{aligned} \mu_B &= \frac{1}{m} \sum_{i=1}^{m} x_i \\ \sigma_B^2 &= \frac{1}{m} \sum_{i=1}^{m} (x_i - \mu_B)^2 \end{aligned}

Step 2: normalize. ϵ\epsilon is a small constant (10−510^{-5} in PyTorch) that prevents division by zero.

x^i=xi−μBσB2+ϵ\hat{x}_i = \frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}}

Step 3: scale and shift. γ\gamma and β\beta are learnable parameters.

yi=γx^i+βy_i = \gamma \hat{x}_i + \beta

γ\gamma and β\beta let the network undo the normalization if that helps. With γ=σB2+ϵ\gamma = \sqrt{\sigma_B^2 + \epsilon} and β=μB\beta = \mu_B, the layer gives back the original xix_i.

batch and layernorm code

python
class torch.nn.BatchNorm1d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None)

BatchNorm1d applies Batch Normalization over a 2D or 3D input.

Why even apply batch normalization? More importantly, what is normalisation?

Batch norm keeps the outputs of each layer at a consistent scale and distribution as data flows through the network. In simpler words -> it stabilizes and accelerates the training of deep neural networks by normalising features.

For each feature, independently, it subtracts the mean of the batch from x and divides by the standard deviation of the batch. The inputs are now on the same scale across the batch:

xnew=x−μBσB2+ϵx_{new} = \frac{x - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}}

Then it applies the affine parameters: y=γ xnew+βy = \gamma \, x_{new} + \beta. Training learns γ\gamma (scale) and β\beta (shift).

It expects input of shape (batch_size, num_features) from fully connected layers, and normalizes over the batch dimension.

python
import torch
def main():
    x = torch.tensor([[1., 2., 3.],
                      [4., 5., 6.]]) # here number of features = columns = 3 (think of features as age, name, job in a dataset)
    
    bn = torch.nn.BatchNorm1d(num_features=3)
 
    y = bn(x)
    print(f"Input: {x}")
    print(f"Output: {y}")
    # shapes are preserved (both have (2,3))
    print(bn.weight)  # γ (gamma)
    print(bn.bias)    # β (beta)
 
 
main()
 
# Input: tensor([[1., 2., 3.],
#                [4., 5., 6.]])
# Output: tensor([[-1.0000, -1.0000, -1.0000],
#                 [ 1.0000,  1.0000,  1.0000]], grad_fn=<NativeBatchNormBackward0>)
# Parameter containing: tensor([1., 1., 1.], requires_grad=True)   # gamma
# Parameter containing: tensor([0., 0., 0.], requires_grad=True)   # beta

Running through the output. The output is normalised. You can see bn.weight (gamma) and bn.bias (beta), the learnable parameters. They start at γ = 1 and β = 0.

Internally, for each column:

  • mean = [2.5, 3.5, 4.5]
  • var = [2.25, 2.25, 2.25] (the biased variance, divided by m)
  • normalise = (x - mean) / sqrt(var + eps) = ±1.5 / 1.5 = ±1
  • scale and shift = γ * normalized + β

During training

  • BN uses the current batch mean & variance
  • BN updates running_mean and running_var (an exponential moving average, momentum = 0.1)

During evaluation

  • BN uses running_mean and running_var, so the output for one sample does not depend on the other samples in the batch

With BN → distributions stay centered & scaled. Where is it placed? Linear → BatchNorm → ReLU. Benefits: faster convergence and a smoother optimization landscape.

Transformers do not use BatchNorm, because it breaks with variable sequence lengths. Transformers use LayerNorm instead. LayerNorm normalizes each token over its own features, not over the batch.

Why does batchnorm break in transformers? Transformers operate under these conditions:

  • Variable sequence lengths, with padding tokens in the shorter sequences
  • Autoregressive decoding (token by token)
  • Small batches, down to batch size 1 at inference (one token is sent at a time)
text
step 1 → token 1
step 2 → token 2
step 3 → token 3

Each step has batch size 1 and a growing sequence length. At training time, batchnorm computes its mean over the batch. Padding tokens and sequences of different lengths pollute those statistics, and small batches make them noisy. At inference the running statistics from training may not match the sequence the model sees.

Order matters per token, not across the batch. To fix this we use LayerNorm.

How batchnorm is implemented internally:

python
import torch
 
class BatchNorm1d:
    def __init__(self, num_features, eps=1e-5, momentum=0.1):
        self.eps, self.momentum = eps, momentum
        self.gamma, self.beta = torch.ones(num_features), torch.zeros(num_features)
        self.running_mean, self.running_var = torch.zeros(num_features), torch.ones(num_features)
 
    def forward(self, x, training=True):
        if training:
            mean = x.mean(dim=0)
            var = x.var(dim=0, unbiased=False)  # normalize with the biased variance
            # update running stats with an exponential moving average (unbiased variance, like PyTorch)
            self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mean
            self.running_var = (1 - self.momentum) * self.running_var + self.momentum * x.var(dim=0, unbiased=True)
        else:
            mean = self.running_mean
            var = self.running_var
 
        x_new = (x - mean) / torch.sqrt(var + self.eps)
        return self.gamma * x_new + self.beta

layernorm

LayerNorm takes the mean over the feature dimension. This makes normalisation independent of batch size, which is what we want. So normalisation happens per sample: for input (batch_size, seq_len, hidden_dim), LayerNorm normalizes over hidden_dim.

python
class torch.nn.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, bias=True, device=None, dtype=None)
python
import torch
 
def main():
    x = torch.tensor([
        [[1., 2., 3.],
         [4., 5., 6.]],
        
        [[7., 8., 9.],
         [10., 11., 12.]]
    ])  # shape: (2, 2, 3) -> 2 matrices (batch size = 2, but LayerNorm doesn't rely on it), both have 2 rows (tokens) and 3 columns (features)
    # layer norm normalizes each row (token vector) of both matrices on its own (same as in transformers)
    layernorm = torch.nn.LayerNorm(normalized_shape=3) # features = 3
    y = layernorm(x)
 
    print("Input shape:", x.shape)
    print("Output shape:", y.shape) # shape is same as input, no batch interaction
    print("Output:\n", y)
 
main()
 
# Input shape: torch.Size([2, 2, 3])
# Output shape: torch.Size([2, 2, 3])
# Output:
#  tensor([[[-1.2247,  0.0000,  1.2247],
#          [-1.2247,  0.0000,  1.2247]],
#
#         [[-1.2247,  0.0000,  1.2247],
#          [-1.2247,  0.0000,  1.2247]]], grad_fn=<NativeLayerNormBackward0>)

Running through the output. Every row is normalised.

  • The vector: in an input matrix each row is a token (e.g., "The," "cat," "sat"). LayerNorm looks at the row of feature activations for that one token only.
  • The calculation: it calculates the mean and variance from the values of that single token's feature vector.
  • Independence: the normalization of the word "cat" uses no information from the word "sat" or "the".

How does it work? For a single token vector [4, 5, 6], mean = 5 and var = 2/3. Normalise: [-1.22, 0.0, 1.22]. Then scale + shift with the learnable parameters (gamma, beta), same as BatchNorm.

  • Step 1: Pick one sentence in the batch (sequence independence).
  • Step 2: Pick one token (word) in that sentence (token independence).
  • Step 3: Calculate the mean and variance across all features (e.g., all 512 embedding values) of that token.
  • Step 4: Normalize that token's vector with its own statistics.

LayerNorm behaves IDENTICALLY in model.train() and model.eval().

Where does this happen?

Post-Normalization (Post-LN): the original "Attention Is All You Need" paper puts LayerNorm after the residual connection of each sub-layer. This works, but it needs careful hyperparameter tuning and a learning rate "warm-up" phase for stability.

text
x → Sublayer → Add → LayerNorm

Pre-Normalization (Pre-LN): modern, deeper transformers use the Pre-LN setup. Normalization comes before the attention and feed-forward sub-layers, inside the residual path. This gives more stable gradients and faster, more reliable training, often without learning rate warm-up (Xiong et al., 2020). It also makes very deep models trainable.

text
x → LayerNorm → Sublayer → Add

Every token is normalized with its own statistics, so variable sequence lengths and padding do not change the result.

How is LayerNorm implemented internally:

python
import torch
 
class LayerNorm:
    def __init__(self, dim, eps=1e-5):
        self.eps = eps
        self.gamma, self.beta = torch.ones(dim), torch.zeros(dim)
 
    def forward(self, x):
        mean = x.mean(dim=-1, keepdim=True)
        var = x.var(dim=-1, keepdim=True, unbiased=False)
        x_new = (x - mean) / torch.sqrt(var + self.eps)
        return self.gamma * x_new + self.beta

resnets ~ residual networks

Suppose you have an image; you need to classify it. How to?

Answer -> a CNN (convolutional neural network) with many layers, trained with backpropagation.

Problem: stack 50 layers and the deep network trains worse than a shallow one.

outputfn=f50 ⁣(f49 ⁣(⋯f2 ⁣(f1(input))⋯ ))\begin{aligned} &\text{output}_{\text{fn}} \\ &= f_{50}\!\left( f_{49}\!\left( \cdots f_2\!\left( f_1(\text{input}) \right) \cdots \right) \right) \end{aligned}
  • In Theory; deeper = more expressive, more it learns (complex features)

  • In Practice; the ResNet paper (He et al., 2015) found a degradation problem. A 56-layer plain network had a higher training error than a 20-layer one. Overfitting does not explain this, because overfitting lowers the training error. The authors also checked that the gradients did not vanish (the networks used batch norm). The deep network is harder to optimize.

  • Instead of making every layer produce the entire transformed output, we compute

    • output = input (original data) + delta (small improvement computed by current block)

Resnet blocks don't rewrite the whole representation; they apply patches on top of what already exists.

Residual/Skip connections make it easier for the network to learn. Instead of a direct mapping from input x -> output y, a ResNet learns the residual (difference) between input & output.

res

python
def residual_block(x):
    return x + F(x) # input to block + output of series of layers
# Addition of x (skip connection) allows network to skip certain layers during training making it easier to optimise
  • If a layer is not useful, the network can learn F(x) = 0, and the output becomes y=x, the original input (it skips the layer)

After activation:

y = ReLU(F(x) + x)

intuition

  • You have a lower resolution image, and you want your network to output the correct, higher resolution image
    • lower res image = input and higher res image = output
    • output - input = RESIDUAL (the missing piece we need)

Now we can do input + residual = output. The network doesn't need to rebuild the entire signal. It learns only the bit we care about.

Why does this work so well??

  • Gradients flow back more easily, and each block has one small job
  • The input is passed along and is available to later layers. So a layer no longer has to figure out everything important about the input that needs to be passed along. It only has to figure out WHAT INFO it can add ON top of the input
  • The block doesn't have to start by figuring out what information the input contains. It starts by passing along all of the input
  • Every layer has a short path back from the loss for its gradients. Each block has 1 path that goes AROUND and 1 path that goes THROUGH. The derivative of x+F(x)x + F(x) with respect to xx is 1+F′(x)1 + F'(x), so the "1" carries the gradient through even when F′(x)F'(x) is small

transformers

neural network + attention = transformer

  • Idea: self attention encoder / decoder blocks.

Input

  • All word embeddings of a document stacked into a matrix (every row = the embedding of a different word)
    • What are word embeddings? They solve the problem of how to give text data to a Neural Network
      • What we want:
        • A vector representation of each word
        • Vectors of a reasonable size
        • Similar representations (King and Queen nearby) if and only if (iff) the words are semantically related
        • embeddings

Output

  • An encoding of the document. We can use it for different tasks: classification (cat/dog), translation (the decoder in the original attention paper), predicting the next word (ChatGPT)

code for embeddings

nn.Embedding(num_embeddings, embedding_dim) is a learnable lookup table. It maps an integer ID → a vector.

It stores a matrix, weight, of shape (num_embeddings, embedding_dim). Each row is the vector representation of one discrete symbol.

Neural Networks can't operate on integers directly. A tokenizer maps "hello" → 10321 and "world" → 45, but these numbers have no meaning geometrically. The embedding turns a token_id → a continuous vector.

python
import torch
 
def main():
    embedding = torch.nn.Embedding(num_embeddings=10, embedding_dim=4)
 
    token_ids = torch.tensor([1, 3, 7]) # shape (3,) input
    # lookup → adds embedding_dim
 
    vectors = embedding(token_ids)   # (3 tokens, 4 features)
 
    print(vectors.shape) # torch.Size([3, 4]) {Embedding adds one dimension at the end.}
    print(vectors)       # random init, so your numbers will differ
    # tensor([[ 0.7213, -0.7668,  0.2204, -1.0903],
    #         [-1.6225,  0.6308, -1.6110, -0.7528],
    #         [-1.1358, -2.2639, -0.7726, -1.6766]], grad_fn=<EmbeddingBackward0>)
 
main()

Running through the output. Each row of the embedding matrix is a trainable parameter. During backprop, only the rows used in the batch get gradients. The other rows are untouched.

How is it used in LLMs? The token embedding is the first layer of an LLM:

python
token_embed = nn.Embedding(vocab_size, d_model)
# Input:  (batch, seq_len)           token IDs
# Output: (batch, seq_len, d_model)

GPT-2 and BERT also learn their positional encoding this way: pos_embed = nn.Embedding(max_len, d_model). We get to positional encoding below.

How it works internally:

python
class Embedding:
    def __init__(self):
        self.table = random_matrix()   # (num_embeddings, embedding_dim)
 
    def forward(self, ids):
        return self.table[ids]

How info flows: Text → Tokenizer → Token IDs (integers) → nn.Embedding → Vectors.

Let's say your sentence is ["hello", "my", "name", "is"]. The tokenizer maps it to numbers:

python
{"hello": 1532, "my": 212, "name": 784, "is": 318}
token_ids = [1532, 212, 784, 318]

The table needs one row per possible ID, so num_embeddings must be larger than the largest ID. With nn.Embedding(num_embeddings=50000, embedding_dim=4), embedding.weight.shape is (50000, 4):

text
ID    → vector
0     → [ ... ]
1     → [ ... ]
...
1532  → [ ... ]   hello
...
49999 → [ ... ]

It turns each ID into its row of the table:

python
vectors = [table[id] for id in token_ids]

Anyway, back to transformers.

Attention goal: for each word, how much should it 'pay attention' to the other words.

ALGORITHM for Attention

  • Given input = X; find Query, Key, Value (Query: what we need to find, Key: What we have, Value: Answer we are looking for)
  • Do dot product similarity
  • Scale by 1/dk1/\sqrt{d_k}, where dkd_k is the size of each key vector
  • Softmax
  • Multiply with V
Attention(Q,K,V)=softmax(QKTdk)V\begin{aligned} &\text{Attention}(Q, K, V) \\ &= \text{softmax}\left( \frac{QK^T}{\sqrt{d_k}} \right) V \end{aligned}

Why divide by dk\sqrt{d_k}? If the entries of qq and kk are independent with mean 0 and variance 1, then q⋅kq \cdot k has mean 0 and variance dkd_k. For large dkd_k the dot products get large, and softmax goes into regions where its gradients are tiny. Dividing by dk\sqrt{d_k} brings the variance back to 1 (Vaswani et al., 2017).

attention attention_formula

howattnworks

causal masking

  • Sentence so far: "The quick brown fox". The model wants to predict "jumps". It can only look at "The", "quick", "brown", "fox". It can't see "jumps" or anything after it. That's autoregressive generation.

  • During training though, the model sees the entire sentence at once ("The quick brown fox jumps over the dog"). The goal is to predict each word from the previous ones only.

Without masking: Self-attention lets every word look at every other word. So when it learns to predict "jumps" (position 5), the model can peek at positions 5 to 8 ("jumps", "over", "the", "dog"). That's cheating. The model learns nothing about the real causal relationships.

With masking: The token at position t can only attend to positions 1 through t. Future tokens are blocked: their scores become −∞ before the softmax, and e−∞=0e^{-\infty} = 0.

Scores QKT/√d after the causal mask query ↓ key → The cat sat on mat The 0.47 −∞ −∞ −∞ −∞ cat 1.48 1.40 −∞ −∞ −∞ sat 1.79 2.07 1.14 −∞ −∞ on 2.30 0.77 1.29 2.35 −∞ mat 1.62 2.39 0.81 1.51 2.30 softmax per row ↓ (e^−∞ = 0) Attention weights (each row sums to 1) query ↓ key → The cat sat on mat The 1.00 0 0 0 0 cat 0.52 0.48 0 0 0 sat 0.35 0.47 0.18 0 0 on 0.38 0.08 0.14 0.40 0 mat 0.15 0.33 0.07 0.14 0.30

Figure: Causal masking on "The cat sat on mat". Each token can only attend to itself and previous tokens. The masked scores become −∞, so softmax gives them weight 0, and each row sums to 1 (up to rounding).

There are much better blogs out there that teach you transformers and how they work. This is the basic math they need. The microgpt post shows causal masking in code.

self attention code

output = F.scaled_dot_product_attention(Q, K, V) is PyTorch's fused, optimized implementation of the classic attention core. It computes softmax(QKT/dk) V\text{softmax}(QK^T / \sqrt{d_k})\,V, with optional masking, dropout, and a few performance features (GQA, fused kernels).

python
import torch
import torch.nn.functional as F
 
def main():
    Q = torch.randn(2, 3, 4)  # (batch, tokens(rows), dimensions(columns))
    K = torch.randn(2, 3, 4)
    V = torch.randn(2, 3, 4)
 
    out = F.scaled_dot_product_attention(Q, K, V)
 
    print(f"Output shape: {out.shape}")
    print(f"Output : {out}")
          
main()
 
# Output shape: torch.Size([2, 3, 4])   same as Q, K, V (2 batches, 3 rows, 4 columns)
# Output : tensor([[[-1.1798,  0.0962, -0.4744,  0.3941],
#                   [ 0.1781,  0.2997, -0.0952, -0.4089],
#                   [-1.3043,  0.0902, -0.5171,  0.4701]],
#
#                  [[-0.2180,  0.4441,  1.9291, -1.0765],
#                   [ 0.2576,  0.2707,  0.9700,  0.7783],
#                   [ 0.0606,  0.2904,  1.4156, -0.0605]]])   random inputs, so your numbers will differ

It can also apply a causal mask (token t can only attend to tokens ≤ t): masked positions get −∞. It can also apply dropout at training time:

python
out = F.scaled_dot_product_attention(
    q, k, v,
    attn_mask=None,
    dropout_p=(0.1 if model.training else 0.0),
    is_causal=True
)

LLMs do: Linear → Q, K, V → scaled_dot_product_attention → Linear.

How is this implemented:

python
import torch
import math
import torch.nn.functional as F
 
def scaled_dot_product_attention(Q, K, V, attn_mask=None, dropout_p=0.0, is_causal=False, training=True):
    # shape: Q, K, V: (batch, heads, seq_len, head_dim)
 
    B, H, L, d_k = Q.shape
    S = K.shape[-2]
 
    # dot product -> similarity score
    # (B, H, L, D) @ (B, H, D, S) → (B, H, L, S)
    scores = torch.matmul(Q, K.transpose(-2, -1))
 
    # scale by sqrt of the key size
    scores = scores / math.sqrt(d_k)
 
    # causal mask with torch.tril: query i can attend to keys j ≤ i
    #     i\j  0  1  2  3  4
    #     0    1  0  0  0  0
    #     1    1  1  0  0  0
    #     2    1  1  1  0  0
    #     3    1  1  1  1  0
    #     4    1  1  1  1  1
    #     0 = look ahead (blocked), 1 = look backward (and self)
    if is_causal:
        causal_mask = torch.tril(torch.ones(L, S, device=Q.device, dtype=torch.bool))
        scores = scores.masked_fill(~causal_mask, float("-inf")) # fill with -inf
 
    # attention mask: which tokens are valid to attend to for this input?
    #     Input: [Hello, world, <PAD>, <PAD>]
    #     Mask:  [1,     1,     0,     0]
    if attn_mask is not None:
        if attn_mask.dtype == torch.bool:
            scores = scores.masked_fill(~attn_mask, float("-inf"))   # True = keep
        else:
            scores = scores + attn_mask   # float mask: add 0 to keep, -inf to block
 
    # softmax
    attn_weights = F.softmax(scores, dim=-1)
 
    # dropout
    if training and dropout_p > 0.0:
        attn_weights = F.dropout(attn_weights, p=dropout_p)
 
    # Weighted sum of values
    # (B, H, L, S) @ (B, H, S, D) → (B, H, L, D)
    output = torch.matmul(attn_weights, V)
 
    return output

I checked this function against F.scaled_dot_product_attention with is_causal=True on random inputs: the outputs match within 10−610^{-6}.

This is the heart of attention in Transformers. It computes how much each word should 'pay attention' to the other words. Word embeddings put similar words together (king and queen are close in vector space). The dot product of a query vector Q and a key vector K measures how similar the two are. If the dot product is large, they point in the same direction -> similar. Otherwise they aren't.

Q, K, V are Query, Key, Value. They are not parameters themselves. The parameters are the projection matrices WqW_q, WkW_k, WvW_v that produce them from the input.

  • Query (Q): "What am I looking for?" Each token broadcasts what info it needs.
  • Key (K): "What do I have to offer?" Each token advertises what info it contains.
  • Value (V): "Here's my actual content." This is the payload that gets mixed in, weighted by the Q·K scores.

Q dot K tells you how relevant two tokens are to each other. High score = pay more attention to that token's V.

Example: "The cat sat on the mat because it was tired". When the model processes "it", it compares Q for "it" against K for every other word. K for "cat" scores high (an animal, can be tired). K for "mat" scores low. So "it" pulls in mostly the V of "cat" and barely any V of "mat". Result: the model figures out that "it" refers to "cat".

multi-head attention code

python
class torch.nn.MultiheadAttention(embed_dim, num_heads, dropout=0.0, bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None)

We know attention = softmax(QKT/dk) V\text{softmax}(QK^T / \sqrt{d_k})\,V. Let's take an example to see how this works, with one head first.

Input -> "I am good". 3 words -> 3 vectors, one per token. Let's take size 2 for each token vector:

text
[ 0.2  0.1]   "I"
[-0.9  0.4]   "am"
[ 0.7  0.8]   "good"
shape = [3, 2]  (seq_len, d_model)

So d_model = 2 (each word is represented by 2 numbers) and seq_len = 3 (there are 3 words in our sentence).

Compute Query, Key, Value. PyTorch initialises random weights in_proj_weight of shape (3 * d_model, d_model) = [6, 2]: 3 projections of size d_model × d_model. It also initialises in_proj_bias of shape (3 * d_model,) = [6]. The rows are in the order W_q, W_k, W_v:

text
in_proj_weight            in_proj_bias
[ . .    W_q (2, 2)       [ .    b_q (2,)
  . .                       .
  . .    W_k (2, 2)         .    b_k (2,)
  . .                       .
  . .    W_v (2, 2)         .    b_v (2,)
  . . ]                     . ]

Now we can compute Q, K, V (we take the transpose so the shapes match; the bias broadcasts over the rows):

text
Q = Input (3,2) @ W_q.T (2,2) + b_q (2,) = [3,2]
K = Input @ W_k.T + b_k                  = [3,2]
V = Input @ W_v.T + b_v                  = [3,2]

Now we calculate attention. Q @ K.T = [3,2] @ [2,3] = [3,3]. Dividing by dk\sqrt{d_k} and applying softmax don't change the shape. After softmax every score is between 0 and 1 and every row sums to 1. These are the attention weights (illustrative numbers):

text
      I    am   good
I     0.1  0.3  0.6
am    0.7  0.1  0.2
good  0.5  0.4  0.1

This is our softmax(QKT/dk)\text{softmax}(QK^T / \sqrt{d_k}) matrix. It tells how much attention each word pays to each other word.

Now out = weights [3,3] @ V [3,2] = [3,2]. This isn't the final output. PyTorch also creates an output projection out_proj with a weight of shape [d_model, d_model] and a bias of shape [d_model]:

text
final_out = out (3, 2) @ out_w.T (2, 2) + out_b (2,)
          = (3, 2)

(3, 2) is the final output of this layer. It goes on for further processing (normalise etc..).

That was one head. With h heads, MHA splits d_model into h parts of size dk=dmodel/hd_k = d_{model}/h and runs attention on each part. Then it concatenates the heads, concat(head1,…,headh)\text{concat}(head_1, \ldots, head_h), and applies the output projection. Every attention layer does this.

torch.nn.MultiheadAttention does (“Which tokens matter in different ways at the same time?”):

  • Projects inputs → Q, K, V
  • Runs attention per head
  • Concatenates heads + output projection
python
import torch
def main():
    x = torch.randn(3, 2, 2) # (seq_len, batch, d_model)
    mha = torch.nn.MultiheadAttention(embed_dim=2, num_heads=2)  # 2 heads, so d_k = 1
    out, attn_weights = mha(x, x, x)
 
    print(f"Output shape: {out.shape}") # final transformed embeddings
    print(f"Attention Weights: {attn_weights.shape}") # attention matrix (for debugging, LLMs do not use attention weights during inference)
 
main()
 
# Output shape: torch.Size([3, 2, 2])         (seq_len, batch, d_model): same as the input
# Attention Weights: torch.Size([2, 3, 3])    (batch, seq_len, seq_len), averaged over the heads

Running through the output. The output has the shape of the input, as we predicted. Each sequence in the batch gets its own (3, 2) output. The attention weights are one 3 × 3 matrix per sequence; PyTorch averages them over the heads by default.

Revising the process:

text
Q = X @ W_q,  K = X @ W_k,  V = X @ W_v
 
Q, K, V → (seq_len, batch, H, D)      split into H heads of size D
 
head_h = softmax(Q_h K_h^T / sqrt(D)) @ V_h
 
Concat(head_1, ..., head_H) → (seq_len, batch, E)
 
out = concat @ W_o

Causal mask in MHA:

python
attn_mask = torch.triu(torch.ones(L, L), diagonal=1).bool()   # True = blocked
key_padding_mask = (tokens == PAD_ID)

attn_mask blocks pairs (i → j). key_padding_mask blocks tokens entirely. Note the convention: in nn.MultiheadAttention, True means blocked. In F.scaled_dot_product_attention, a boolean True means keep.

How it works under the hood:

python
class MultiHeadAttention:
    def forward(self, x):
        Q, K, V = linear(x)
        # split heads
        for each head:
            head = attention(Q, K, V)
        # concat heads
        return output_projection

positional encoding

Self-attention processes all tokens in parallel. It has no idea which word came first. "The cat chased the dog" and "The dog chased the cat" would look identical without position info.

Why? The attention score between two tokens is q⋅kq \cdot k, and nothing in q⋅kq \cdot k depends on where the tokens sit. Shuffle the input tokens and the output rows shuffle the same way. So we add a position vector to each token's embedding.

What makes a good position vector?

  • It stays small. Embedding values sit near ±1. A raw position number like 500 would drown them.
  • Each position gets its own vector, for any sequence length.
  • A fixed offset looks the same everywhere, so the model can learn "the word 3 before me" one time, not one time per position.

The sinusoidal encoding from the original transformer paper (Vaswani et al., 2017) meets all three. Split the dd dimensions into d/2d/2 pairs. Each pair is a clock hand that turns at its own speed ωi\omega_i:

PE(p,2i)=sin⁡(p ωi)PE(p,2i+1)=cos⁡(p ωi)ωi=1100002i/d\begin{aligned} PE(p, 2i) &= \sin(p\,\omega_i) \\ PE(p, 2i+1) &= \cos(p\,\omega_i) \\ \omega_i &= \frac{1}{10000^{2i/d}} \end{aligned}
  • pp is the position (0, 1, 2, ...), dd is d_model, and ii is the pair index, from 0 to d/2−1d/2 - 1. Dimensions 2i2i and 2i+12i+1 share one speed.
  • Pair 0 turns 1 radian per token, like the seconds hand. Each next pair is slower, down to about 1/10000 radian per token, like the hour hand. The paper says the wavelengths go from 2π2\pi to 10000⋅2π10000 \cdot 2\pi tokens.
  • It works like a binary counter. The low bits flip fast and the high bits flip slowly, and all the bits together give the position.
  • Every value is between −1 and 1, and every position vector has the same length, d/2\sqrt{d/2}.
pair 0: 1 radian per token +1−1 -0.279 pair 1: 0.1 radian per token +1−1 +0.565 pair 2: 0.01 radian per token +1−1 +0.060 0 4 8 12 16 20 24 position p (dots: the only values a token uses) Position 6 reads one value from each curve

Figure: Three dimension pairs of an 8-dimensional encoding (only the sine of each pair is drawn). A token at position 6 takes one value from each curve. The fast curve tells nearby positions apart. The slow curves tell far positions apart.

Example: "good boy", d_model = 4. There are two pairs: ω0=1\omega_0 = 1 and ω1=1/100002/4=0.01\omega_1 = 1/10000^{2/4} = 0.01.

worddim 0: sin(p)dim 1: cos(p)dim 2: sin(0.01p)dim 3: cos(0.01p)
good, p = 00101
boy, p = 10.84150.54030.01000.9999

Each word gets its own row. Add each row to that word's embedding only. Do not add the rows together:

xgood=E[good]+PE[0]xboy=E[boy]+PE[1]\begin{aligned} x_{good} &= E[good] + PE[0] \\ x_{boy} &= E[boy] + PE[1] \end{aligned}

Why sin and cos in pairs? Move kk tokens forward and each hand turns by k ωik\,\omega_i. A turn is a rotation. It is a linear map that depends on kk only, not on pp:

[sin⁡((p+k)ω)cos⁡((p+k)ω)]=[cos⁡kωsin⁡kω−sin⁡kωcos⁡kω][sin⁡pωcos⁡pω]\begin{bmatrix} \sin((p+k)\omega) \\ \cos((p+k)\omega) \end{bmatrix} = \begin{bmatrix} \cos k\omega & \sin k\omega \\ -\sin k\omega & \cos k\omega \end{bmatrix} \begin{bmatrix} \sin p\omega \\ \cos p\omega \end{bmatrix}

So "3 tokens back" is one fixed matrix at every position, and attention can learn it. I checked this on an 8-dimensional encoding. The rotation reproduces the encoding 3 positions ahead with an error below 10−610^{-6}.

python
import torch, math
 
def sinusoidal_pos_enc(seq_len, d_model):
    pos = torch.arange(seq_len).unsqueeze(1)
    i = torch.arange(d_model).unsqueeze(0)
    angle = pos / (10000 ** (2*(i//2)/d_model))
    enc = torch.zeros(seq_len, d_model)
    enc[:, 0::2] = torch.sin(angle[:, 0::2])
    enc[:, 1::2] = torch.cos(angle[:, 1::2])
    return enc  # (seq_len, d_model)
 
# The "good boy" example: 2 positions, d_model = 4
print(sinusoidal_pos_enc(2, 4))
# tensor([[0.0000, 1.0000, 0.0000, 1.0000],
#         [0.8415, 0.5403, 0.0100, 0.9999]])
 
# Example: Encode positions for a sequence
seq_len = 10      # 10 tokens in sequence
d_model = 512     # Embedding dimension
 
pos_enc = sinusoidal_pos_enc(seq_len, d_model)
print(pos_enc.shape)  # torch.Size([10, 512])
 
# Add it to the token embeddings, then pass the result to attention
# embeddings = token_embeddings + pos_enc

Other choices exist. GPT-2 and BERT learn the position table instead: nn.Embedding(max_len, d_model), the same lookup as in code for embeddings. Most modern LLMs, such as Llama, use RoPE (rotary position embedding). RoPE does not add a vector. It rotates qq and kk by these same angles, so q⋅kq \cdot k depends only on the offset between the two tokens. The DeepSeek-V3 post shows how it fits into MLA (multi-head latent attention).

putting the encoder together

Now we have all the pieces of one encoder: word embeddings, plus positional encoding, into attention, with residual (skip) connections around each block.

encoder-decoder

Transformers use the same residual idea as ResNet. Each block adds a small improvement to the representation instead of rewriting it, so the gradients stay alive through dozens of layers:

resnet


Additional Math

linear algebra

Two operations you need to know:

  • Dot product (alignment)
  • Norms (magnitude)

dot product

  • Takes two vectors of equal length, returns a single scalar.
  • Also written as a.T * b (Row vector * Column vector, why transpose? To match shapes)
  • Measures alignment between vectors. Bridges algebra and geometry.

What it means geometrically:

a⋅b=∥a∥ ∥b∥cos⁡θa \cdot b = \lVert a \rVert \, \lVert b \rVert \cos\theta

If the result is:

  • Positive -> the vectors point in about the same direction (θ < 90°)
  • Negative -> the vectors point in opposite directions (θ > 90°)
  • Zero -> the vectors are orthogonal (perpendicular, θ = 90°)

dot_prod

Matrix Multiplication is a batch of dot products.

Quick refresher on matrix multiplication:

  • Shapes are always row x column. 2x4 = 2 rows, 4 columns.
  • To multiply: columns on the left must equal rows on the right. A is (m x n), B is (n x p), AB works. BA doesn't (unless p = m).
  • Result shape: rows of left x columns of right. (m x n) * (n x p) = (m x p).
  • Element at row i, column j = dot product of (row i of left) and (column j of right).

mm

Assume we have a row with 3 elements, (a1 a2 a3), and a column with 3 elements, (b1 b2 b3). Their dot product is a1b1 + a2b2 + a3b3 = ∑i=13aibi\sum_{i=1}^{3} a_i b_i. The same process works for rows and columns of other sizes.

the i, jth position in the matrix is the dot product of the ith row (transpose) with the jth column.

  • Transformer attention is a scaled dot product. It calculates the relevance scores between tokens.
  • Every neural network layer also uses it: y = activation(X_input @ Weights + bias)

probability

conditional probability

How does learning new info change what we believe?

Question: What is the chance of A happening given that B has already happened?

Another way to say this is P(A given B)

Solution to this is:

P(A∣B)=P(A∩B)P(B)P(A \mid B) = \frac{P(A \cap B)}{P(B)}

The probability that both A and B occur, divided by the probability that B occurs.

  • Why divide?

    • Once B has occurred, the only possible outcomes are the ones where B is true.
  • Original sample space → all outcomes

  • New sample space → only outcomes consistent with B

  • We renormalize probabilities so they sum to 1 again

  • Every time an LLM generates a token:

The model computes a conditional probability distribution over tokens

  • LLMs don’t “understand” text. They update beliefs about the next token given new evidence (context).
  • They don’t learn whole sentences at once. One conditional distribution at a time.

bayes theorem

It is conditional probability viewed from the other side:

P(A∣B)=P(B∣A) P(A)P(B)P(A \mid B) = \frac{P(B \mid A)\, P(A)}{P(B)}
  • Prior: P(A) is what you believed before seeing data
  • Likelihood: P(B|A) is how compatible the data is with that belief
  • Posterior: P(A|B) is the updated belief after seeing data

Bayes = belief updating, LLMs amortize those updates into weights

additional math code in PyTorch

cosine similarity

  • Scores from -1 (opposite) to 1 (same direction). How similar are two vectors?
  • The dot product of the vectors divided by the product of their magnitudes. That's the cosine of the angle between them.
  • Smaller angle = higher similarity

torch.nn.CosineSimilarity returns the cosine similarity between x1 and x2 along dim (default: 1). The small value ϵ=10−8\epsilon = 10^{-8} avoids a division by 0:

similarity=x1⋅x2max⁡(∥x1∥ ∥x2∥,ϵ)\text{similarity} = \frac{x_1 \cdot x_2}{\max(\lVert x_1 \rVert \, \lVert x_2 \rVert, \epsilon)}

It answers: how similar are two vectors by direction, not magnitude? (Are these two embeddings semantically similar?)

python
import torch
 
def main():
    x = torch.tensor([[1., 0., 0.]])
    y = torch.tensor([[0.9, 0.1, 0.]])
 
    cos = torch.nn.CosineSimilarity(dim=1)
 
    sim = cos(x, y)
    print(sim) # tensor([0.9939])
 
main()

Internally:

python
dot = (x * y).sum(dim)
norm_x = sqrt((x * x).sum(dim))
norm_y = sqrt((y * y).sum(dim))
cos_sim = dot / max(norm_x * norm_y, eps)

Here dot = 0.9 and the norms are 1 and 0.82=0.9055\sqrt{0.82} = 0.9055, so the similarity is 0.9 / 0.9055 = 0.9939.

LLM systems use this to compare embeddings: query_embedding vs document_embedding → CosineSimilarity. RAG (retrieval-augmented generation) uses it to rank the retrieved documents: embedding → cosine sim → top-k → LLM reasoning.

Why doesn't attention use cosine similarity? Attention uses the raw QKTQK^T, so magnitude matters as well as direction. A longer query vector gives sharper attention: it is the model's confidence in how important one word is to another word.


gradient descent

python
import torch
 
# Create parameter θ
theta = torch.tensor(5.0, requires_grad=True) # Enable gradient tracking
 
# Define hyperparameters
eta = 0.1 # Learning rate
total_steps = 15 # No. of iterations
 
print("Step 0 (initial θ):", theta.item())
print("Initial loss:", (theta ** 2).item())
print()
 
# Iterate for total_steps 
for step in range(1, total_steps + 1):
    # Forward pass
    loss = theta ** 2
    
    # Backward pass (calculates d(θ²)/dθ = 2θ and stores in theta.grad)
    loss.backward() 
    
    # Store gradient and loss to print later
    gradient = theta.grad.item()
    loss_value = loss.item()
 
    # Gradient descent update: θ = θ - η·∇J(θ)
    # Use no_grad() to prevent PyTorch from tracking this parameter update
    with torch.no_grad():
        theta -= eta * theta.grad
 
    print(f"Step {step}:")
    print(f"loss = {round(loss_value, 3)}")
    print(f"θ = {round(theta.item(), 3)}")
    print(f"gradient = {round(gradient, 3)}")
    print(f"update = {round(eta * gradient, 3)}")
 
    # Reset gradients for next iteration
    theta.grad.zero_()
 
print("Final θ:", round(theta.item(), 3))
print("Final loss:", round((theta ** 2).item(), 3))

Output:

text
Step 0 (initial θ): 5.0
Initial loss: 25.0
 
Step 1:
loss = 25.0
θ = 4.0
gradient = 10.0
update = 1.0
 
Step 2:
loss = 16.0
θ = 3.2
gradient = 8.0
update = 0.8
 
Step 3:
loss = 10.24
θ = 2.56
gradient = 6.4
update = 0.64
 
...
 
Final θ: 0.176
Final loss: 0.031

Each step multiplies θ by (1 - 2η) = 0.8, so after 15 steps θ = 5 × 0.8^15 = 0.176.

feed-forward layers are nn.Linear

nn.Linear(in, out) computes y = xW^T + b (PyTorch broadcasts the bias and transposes W for you). Every W_q, W_k, W_v, W_o, and FFN/MLP layer in a transformer is the same thing: nn.Linear with different shapes.


single neuron

python
import torch
 
# data OR gate (4 options: 00, 01, 10, 11)
 
x = torch.tensor(
    [[0.,0.],[0,1.],[1,0.],[1,1.]] # outputs (y) = 0,1,1,1 (shape: x: (4, 2))
    )
 
 
y = torch.tensor([0., 1., 1., 1.,]).unsqueeze(1) # add new dim (shape: y: (4, 1))
 
# nn.Sequential chains the layers; calling nn.Linear and then nn.Sigmoid separately works the same
model = torch.nn.Sequential(
    torch.nn.Linear(2, 1), # in_features = 2 (like 01), out_features = 1 (like 1)
    torch.nn.Sigmoid(),
)
 
# torch.optim.SGD; here every step sees all 4 points, so this is full-batch gradient descent
optimiser = torch.optim.SGD(model.parameters(), lr=0.1)
loss_function = torch.nn.MSELoss() # better to use BCELoss() for binary classification
 
epochs = 1000
for epoch in range(epochs):
    y_pred = model(x)
    loss = loss_function(y_pred, y) # calc mse 
    optimiser.zero_grad() # zero out the gradients: PyTorch adds new gradients to old ones unless we reset them
    loss.backward() # magic!! backward pass through the layers to find all gradients wrt weights and biases
    optimiser.step() # weight = weight - learning_rate * gradients (the update)
 
print("Prediction:", (model(x) > 0.5).int().squeeze().tolist()) 
 
# > uv run single_neuron.py
# Prediction: [0, 1, 1, 1]   for inputs [0, 0], [0, 1], [1, 0], [1, 1]: CORRECT!!

Running through the output. At first the model predicts jargon. Each iteration, backprop finds the gradients of the weights and biases, and the optimiser takes a 0.1 step in the negative direction of the gradient. I ran it with 5 random seeds and all 5 gave [0, 1, 1, 1].


how autograd works (backprop using PyTorch)

python
import torch
 
weight = torch.randn(3, requires_grad=True) # 3 features, track the gradient of this tensor
x = torch.tensor([1.,2.,3.])
y = (weight * x).sum() # dot product of weight and x
y.backward() # autograd computes the gradients here, with the chain rule + partial derivatives
# y = w1*1 + w2*2 + w3*3, so dy/dw_i = x_i -> [1, 2, 3]
 
print("grad:", weight.grad)  # derivative dy/dw == x
# grad: tensor([1., 2., 3.])

So we don't have to do this manually. Torch does this calculus magic for us when we call .backward(). The torch post shows how autograd works inside.

transformers using PyTorch

encoder layer

Let's go through the entire Encoder process. High level overview:

python
nn.TransformerEncoderLayer(
    d_model,
    nhead,
    dim_feedforward=2048,
    dropout=0.1,
    activation=relu,
    layer_norm_eps=1e-5,
    batch_first=False,
    norm_first=False
)

It is a prewired composition of multi-head attention, a feed-forward network, residual connections, layernorm and dropout.

Input shape: (seq_length, batch, d_model), or (batch, seq_length, d_model) if batch_first=True. The output shape is the same.

With the default norm_first=False it follows the original (post-norm) Transformer Encoder architecture:

text
x (input embeddings with positional encoding added)
↓
Self-Attention → Dropout → Add (residual) → LayerNorm
↓
FeedForward → Dropout → Add (residual) → LayerNorm

As functions:

text
x = LN(x + Dropout(SelfAttention(x)))
x = LN(x + Dropout(FFN(x)))

Connecting all blocks with an example:

  • "I am samit" -> Tokeniser -> [t0, t1, t2], the IDs of ["I", "am", "samit"]. So seq_length = 3 and batch size = 1
  • Hidden model size d_model = 8 and number of heads = 2, so head_dimension = d_model / nhead = 4
  • FFN size dim_feedforward = 32 (the original transformer uses 2048)
  • We keep the default batch_first=False, so tensors have shape (seq_len, batch, d_model) = (3, 1, 8)
  • We use norm_first=True: pre-norm, as in Transformer++ models (the modern Llama-style recipe). Pre-norm gives more stable gradients than post-norm
  • No padding and no causal mask (this is an encoder)

Step 0: Tokenization -> token IDs (text -> tokenizer -> ids). "I am samit" -> token_ids = [1532, 212, 784]. These go into nn.Embedding to create the vector embeddings of the tokens.

Step 1: Embedding + positional encoding = input tensor X

python
token_emb = token_embedding(token_ids)
pos_emb = pos_embeddings(positions)
X = token_emb + pos_emb   # shape: (3, 1, 8)
# X[0] = vector for "I"      shape (1, 8)
# X[1] = vector for "am"     shape (1, 8)
# X[2] = vector for "samit"  shape (1, 8)

Step 2: TransformerEncoderLayer (with norm_first=True)

text
x = x + self_attn(LayerNorm(x))
x = x + FFN(LayerNorm(x))

Breaking this down. First we compute x_norm = LayerNorm(X). LayerNorm normalizes each token vector across its 8 features. It computes the mean and variance per token (per position). Then x_norm = (x - μ)/sqrt(var + eps), scaled by the learnable γ and shifted by β. No shape change.

Then nn.MultiheadAttention does three linear projections from d_model -> d_model. For each token we compute Q_i = W_q · x_norm_i + b_q, and the same for K_i and V_i.

To split into heads, we reshape to (seq_length, batch, nhead, head_dim) and transpose to the common attention shape (batch, nhead, seq_length, head_dim):

text
Q.shape = (B, nhead, seq_length, head_dim) = (1, 2, 3, 4)
K.shape = (1, 2, 3, 4)
V.shape = (1, 2, 3, 4)

Then we do scaled dot product attention per head. The weight of query position i on key position j is softmaxj(Qi⋅Kj/head_dim)\text{softmax}_j(Q_i \cdot K_j / \sqrt{\text{head\_dim}}). The output for token i is the weighted sum of the VjV_j. We do this for every head and every token position.

We concatenate the heads, which gives the input shape back: (3, 1, 8). The output projection W_o (d_model, d_model) mixes the head outputs.

Dropout is optional here (the default is p = 0.1). It drops 10% of the values at random to reduce overfitting.

Then we add the residual (the original X): X = X + dropout(mha(ln(X))). The shape stays (3, 1, 8).

Then we have the FFN:

python
X_norm2 = LayerNorm(X)                      # shape still (3, 1, 8)
hidden = Linear1(X_norm2)                   # (3, 1, dim_feedforward) = (3, 1, 32): project to a higher dimension
hidden_activation = activation(hidden)      # ReLU / GELU / SwiGLU
hidden_drop = Dropout(hidden_activation)
out_ffn = Linear2(hidden_drop)              # (3, 1, 8) again: project back to the original dimension
X = X + Dropout(out_ffn)                    # add the residual again

The final output of the layer keeps the shape (seq_len, batch, d_model) = (3, 1, 8):

  • X[0] is the updated embedding for token "I", now informed by "am" and "samit".
  • X[1] is the updated embedding for "am".
  • X[2] is the updated embedding for "samit".

All values are differentiable. Gradients flow back through the FFN, attention, LayerNorm and embeddings to update the parameters.

Here is the same layer, step by step, without dropout:

python
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
 
sentence = ["I", "am", "samit"]
token_to_id = {"I": 0, "am": 1, "samit": 2}
 
token_ids = torch.tensor([token_to_id[w] for w in sentence])
seq_len = len(token_ids)
batch_size = 1
d_model = 8
nhead = 2
head_dim = d_model // nhead
dim_ff = 32
 
# embedding
embedding = nn.Embedding(num_embeddings=10, embedding_dim=d_model)
x = embedding(token_ids)              # (seq, d_model)
x = x.unsqueeze(1)                    # (seq, batch, d_model)
 
print("\n TOKEN EMBEDDINGS")
print("x shape:", x.shape)
print(x)
 
# layernorm (pre-norm)
ln1 = nn.LayerNorm(d_model)
x_norm = ln1(x)
 
print("\nAFTER LAYERNORM (PRE-ATTN)")
print(x_norm)
 
# qkv projection
W_q = nn.Linear(d_model, d_model, bias=False)
W_k = nn.Linear(d_model, d_model, bias=False)
W_v = nn.Linear(d_model, d_model, bias=False)
 
Q = W_q(x_norm)
K = W_k(x_norm)
V = W_v(x_norm)
 
print("Q shape:", Q.shape)
print(Q)
 
# reshape for heads
def split_heads(t):
    return t.view(seq_len, batch_size, nhead, head_dim).permute(1, 2, 0, 3)
 
Qh = split_heads(Q)
Kh = split_heads(K)
Vh = split_heads(V)
 
scores = torch.matmul(Qh, Kh.transpose(-2, -1)) / math.sqrt(head_dim)
 
print("scores shape:", scores.shape)
print(scores)
 
weights = F.softmax(scores, dim=-1)
 
print("\nATTENTION WEIGHTS (SOFTMAX)")
print(weights)
 
attn_out = torch.matmul(weights, Vh)
 
print("\nATTENTION OUTPUT PER HEAD")
print(attn_out)
 
# concatenate heads
attn_out = attn_out.permute(2, 0, 1, 3).contiguous()
attn_out = attn_out.view(seq_len, batch_size, d_model)
 
W_o = nn.Linear(d_model, d_model, bias=False)
attn_out = W_o(attn_out)
 
# residual
x = x + attn_out
 
print("\nAFTER ATTENTION + RESIDUAL")
print(x)
 
# ffn (pre-norm)
ln2 = nn.LayerNorm(d_model)
x_norm = ln2(x)
 
fc1 = nn.Linear(d_model, dim_ff)
fc2 = nn.Linear(dim_ff, d_model)
 
ff_hidden = fc1(x_norm)
ff_hidden_act = F.gelu(ff_hidden)
ff_out = fc2(ff_hidden_act)
 
print("\nFFN HIDDEN (AFTER GELU)")
print(ff_hidden_act)
 
# residual
x = x + ff_out
 
print("\nFINAL OUTPUT OF ENCODER LAYER")
print("output shape:", x.shape)
print(x)
 

The Transformer++ model: modern LLM engineering practice.

  • Pre-norm (LayerNorm before the sublayer) is preferred for stability in deep stacks.
  • Large LLM implementations rewrite the encoder/decoder block by hand for performance. They use fused QKV projections, scaled_dot_product_attention with FlashAttention or other memory-efficient kernels, and custom FFNs (SwiGLU / gated activations).
  • Many modern LLMs replace LayerNorm with RMSNorm (root mean square norm), which skips the mean subtraction and is cheaper.
  • Very large models often reduce or remove dropout (regularization comes from scale and data).
  • FFNs in modern LLMs often use gated activations (SwiGLU) with a different hidden size. Llama uses 23⋅4dmodel\frac{2}{3} \cdot 4 d_{model} instead of 4dmodel4 d_{model}, so the three weight matrices of SwiGLU cost about the same as the two of a plain FFN.
decoder layer

Let's go through the entire Decoder process. High level overview:

python
nn.TransformerDecoderLayer(
    d_model,
    nhead,
    dim_feedforward=2048,
    dropout=0.1,
    activation=relu,
    layer_norm_eps=1e-5,
    batch_first=False,
    norm_first=False
)

It is a prewired composition of:

  • masked multi-head self-attention
  • cross (encoder-decoder) attention
  • feed forward network
  • residual connections
  • layernorm
  • dropout

Input shapes:

  • tgt (decoder input): (tgt_seq_length, batch, d_model)
  • memory (encoder output): (src_seq_length, batch, d_model)

The output has the same shape as tgt: (tgt_seq_length, batch, d_model).

Decoder architecture (pre-norm variant, norm_first=True; each sublayer gets a LayerNorm on its input):

text
x (decoder input embeddings with positional encoding added)
↓
Masked Self-Attention (causal) → Dropout → Add (residual)
↓
Cross-Attention (attend to encoder memory) → Dropout → Add (residual)
↓
FeedForward Network → Dropout → Add (residual)

As functions (pre-norm):

text
x = x + Dropout(SelfAttention(LayerNorm(x)))           # causal self-attn
x = x + Dropout(CrossAttention(LayerNorm(x), memory))
x = x + Dropout(FFN(LayerNorm(x)))

The per-token walkthrough (embedding, LayerNorm, head splitting, shapes) is the same as in the encoder above. Only the two attention blocks differ: causal self-attention, then cross-attention onto the encoder memory. See the code below.

Modern LLM usage notes:

  • Decoder-only LLMs (GPT, LLaMA):
    • remove cross-attention
    • keep masked self-attention + FFN
  • Encoder-Decoder models (T5, BART):
    • use the full decoder with cross-attention
  • Production models:
    • use pre-norm + RMSNorm
    • use FlashAttention / SDPA
    • use SwiGLU FFNs
    • use KV caching during inference

nn.TransformerDecoderLayer is fine for learning, but large-scale LLMs reimplement it by hand for performance.

python
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
 
sentence = ["I", "am", "samit"]
token_to_id = {"I": 0, "am": 1, "samit": 2}
 
tgt_ids = torch.tensor([token_to_id[w] for w in sentence])
src_ids = torch.tensor([0, 1, 2])  # pretend encoder input
 
tgt_len = len(tgt_ids)
src_len = len(src_ids)
batch_size = 1
d_model = 8
nhead = 2
head_dim = d_model // nhead
dim_ff = 32
 
# embeddings
embedding = nn.Embedding(10, d_model)
 
x = embedding(tgt_ids).unsqueeze(1)       # decoder input (tgt)
memory = embedding(src_ids).unsqueeze(1)  # encoder output (memory)
 
print("\nDECODER INPUT x")
print(x.shape)
print(x)
 
print("\nENCODER MEMORY")
print(memory.shape)
print(memory)
 
# ---- helpers ----
def split_heads(t):
    return t.view(-1, batch_size, nhead, head_dim).permute(1, 2, 0, 3)
 
def causal_mask(L):
    return torch.tril(torch.ones(L, L)).bool()
 
# ---- Sublayer 1: Masked Self-Attention ----
ln1 = nn.LayerNorm(d_model)
 
Wq = nn.Linear(d_model, d_model, bias=False)
Wk = nn.Linear(d_model, d_model, bias=False)
Wv = nn.Linear(d_model, d_model, bias=False)
Wo = nn.Linear(d_model, d_model, bias=False)
 
x_norm = ln1(x)
Q = split_heads(Wq(x_norm))
K = split_heads(Wk(x_norm))
V = split_heads(Wv(x_norm))
 
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(head_dim)
scores = scores.masked_fill(~causal_mask(tgt_len), float("-inf"))
 
weights = F.softmax(scores, dim=-1)
out_self = torch.matmul(weights, V)
 
out_self = out_self.permute(2, 0, 1, 3).contiguous().view(tgt_len, batch_size, d_model)
x = x + Wo(out_self)
 
print("\nAFTER MASKED SELF-ATTENTION")
print(x)
 
# ---- Sublayer 2: Cross-Attention ----
ln2 = nn.LayerNorm(d_model)
 
Wq_c = nn.Linear(d_model, d_model, bias=False)
Wk_c = nn.Linear(d_model, d_model, bias=False)
Wv_c = nn.Linear(d_model, d_model, bias=False)
Wo_c = nn.Linear(d_model, d_model, bias=False)
 
x_norm = ln2(x)
Q = split_heads(Wq_c(x_norm))
K = split_heads(Wk_c(memory))
V = split_heads(Wv_c(memory))
 
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(head_dim)
weights = F.softmax(scores, dim=-1)
 
out_cross = torch.matmul(weights, V)
out_cross = out_cross.permute(2, 0, 1, 3).contiguous().view(tgt_len, batch_size, d_model)
 
x = x + Wo_c(out_cross)
 
print("\nAFTER CROSS-ATTENTION")
print(x)
 
# ---- Sublayer 3: FFN ----
ln3 = nn.LayerNorm(d_model)
 
fc1 = nn.Linear(d_model, dim_ff)
fc2 = nn.Linear(dim_ff, d_model)
 
x_norm = ln3(x)
ff = fc2(F.gelu(fc1(x_norm)))
 
x = x + ff
 
print("\nFINAL DECODER OUTPUT")
print(x.shape)
print(x)
 
  • The decoder has two attentions: masked self-attention (causal) + cross-attention (attends to the encoder output).
  • The decoder enforces the time order in self-attention. The encoder uses full (non-causal) self-attention.
  • Encoder-Decoder models (e.g., T5, the original Transformer for translation) use this decoder. Decoder-only LLMs omit the cross-attention and keep only the masked self-attention.
  • Cross-attention is the core conditioning mechanism in seq2seq models. RAG-style pipelines can use it too, with the retrieval results as the memory.

conclusion

  • These are basically notes I took while watching professor bryce videos and wanted to follow it up with code. The videos are great, but being the pompous prick I am and the amount of effort I have put in writing this:- this post is better.
  • To read more great math stuff for ML, check out tensortonic

reply by email

related