I feel the same way about Math as I do about squatting at the gym. It may not be as fun as bench or easy as arms, but if you don’t squat once a week you will get chicken legs. I try to cover the building blocks of math that are needed to approach any machine learning paper with confidence, with a strong mathematical foundation based in a visceral, intuitive understanding of the concepts. I focus on explaining in layman’s terms, with machine learning based examples, visuals to bring the ideas to life and spaced repetition cards for retention. I would not recommend learning the concepts from scratch via this blog, but instead using it as a refresher of the core intuition pumps.
Linear Algebra
Notation used in this section
— -dimensional real vector space; is a vector with real entries
— real matrix with rows and columns
— transpose of : rows and columns swapped, so
— the -norm; subscript says which (1 = sum of absolutes, 2 = Euclidean, = max entry)
— Frobenius norm: flatten to a vector, take its L2 norm
— eigenvalue equation; is an eigenvector, its eigenvalue (a scalar)
— SVD factorization; are rotation matrices, is diagonal with singular values
Vectors
A vector can be described by how much of each basis vector it contains. A linear combination means multiplying a collection of vectors by scalars and adding the results:
The basis vectors provide the coordinate system; the scalars are the parameters of in that basis. In the standard two-dimensional basis,
Vectors as semantic representations
In machine learning, a vector usually represents something rather than a literal arrow. Word2Vec was an early, vivid example: training arranged words so that semantic similarity and some relationships became geometric—nearby points and useful directions in a learned space. Modern embedding models apply the same broad idea to sentences, images, and document chunks storing them in vector databases.
Even more intriguingly, different models sometimes appear to learn similar relational geometry. The Platonic Representation Hypothesis reports that as vision and language models improve, their representations increasingly agree about which datapoints are similar—even though their raw parameters and architectures differ. This does not mean they learn identical vectors: one space may be rotated, reflected, or otherwise reparameterized relative to another. The stronger claim that all models converge to one universal representation remains debated; newer work finds clearer agreement in local neighborhoods than in the full global geometry.
Matrix Multiplication
Almost everything inside a neural net is a vector getting linearly transformed by a matrix: , where is a weight matrix and is the incoming vector. Token embeddings and the residual stream are vectors; the attention projections , , , the MLP weights, and the unembedding head are matrices. This matrix-vector multiplication runs billions of times in a forward pass, so it is worth understanding what the matrix is actually doing to the vector.
There are several different ways to think about matrix multiplication. Mechanically, is the dot product of row of with column of . Shapes contract along the shared dimension: times gives .
Geometrically is performing a linear transformation on . You can think of a linear transformation as a function that takes a vector and can rotate, stretch, shear, reflect, or collapse it. The linear part means we never bend the vector or move the origin. What mathematicians like to do is compactly describe linear transformations with a matrix where the first column tells us where the basis vector lands, and the second column tells us where lands. can transform any vector so they think more about how it transforms the space and that is captured in how it transforms the basis vectors.
Lets take the vector, which means:
When the space moves via , transforms with it. Matrix multiplication is the shortcut that carries out this recipe and tells us where any vector lands in the transformed space. For an incredible visualization please watch the goat of math education 3B1B.
So if a matrix linearly transforms a vector how should we think about two matrices multiplying. Take two transformations and . The product applied to a vector means: apply first, then apply on top — short for . is the single matrix that does both transformations in one step. This explains why we need non linearities in neural networks:
- A linear layer is a matrix function applied to its input.
- Stack three linear layers and you get a single effective matrix. You could just compact them into a single matrix.
- That’s why nonlinearities exist. Drop a ReLU between each pair and they stop collapsing into one matmul; only then does depth grow expressivity.
Take a down-projection for example:
Each column does its own dot product against the vector. We can view this as asking the vector a learned questions: how strongly does align with this column? The answer becomes coordinate of the new vector. A down-projection from dimensions to dimensions is therefore a bank of dot products.
Dot Product
The dot product measures direction alignment, scaled by magnitude. Large and positive when two vectors point the same way, zero when they’re perpendicular, negative when they point opposite ways.
Mechanically: .
Geometrically: , where is the angle between them.
Note and are two notations for the same operation. Transposing turns it into a row, so the row-vector times column-vector multiplication produces the scalar .
Just like matrix multiplication this operation shows up everywhere in ML:
- Matmul is dot product in bulk. Each entry of is a dot product of a row of with a column of .
- Attention scores. In , each entry of is a dot product between a query and a key “how aligned is this token’s question with that token’s offering?”
- Embedding similarity. Cosine similarity is the dot product after normalizing to unit length: . The standard test for “are these two embeddings semantically close?”
Projection and Orthogonal Decomposition
A dot product measures alignment. Projection uses that measurement to extract the part of a vector that lies along a chosen direction. Suppose contains many directions mixed together, but we only care about one direction . When is a unit vector, , the dot product is the signed amount of pointing along . It is only a scalar. Multiplying that amount by turns it back into a vector:
This is the projection of onto : the part of that can be represented using only that direction. Projection splits into two pieces:
The residual is orthogonal to . We already extracted everything that points along , so the remainder cannot contain any more of that direction. This split into an explained component and a perpendicular residual is an orthogonal decomposition.
Norms (L1, L2, Lp)
Ever wondered “how big is this vector?” Well machine learning engineers sure have: weight decay, gradient clipping, cosine similarity. There are multiple ways to measure, and the one you pick changes what your model does.
- L2 (Euclidean): . Straight-line distance. The default: weight decay, gradient clipping.
- L1 (Manhattan): . Sum of absolute values. The norm you pick when you want sparsity.
- L∞ (max): . The single largest coordinate. The standard for adversarial perturbations (“change every pixel by at most ”).
Why does adding L1 norm to the loss produces sparsity? I like to picture every norm as a unit ball. That’s the set of vectors with . Its shape is what makes different norms behave differently. Minimizing a loss subject to a norm budget pushes the solution toward the surface of the unit ball. L1’s diamond has corners pointing at the axes and a corner is sparse. In a 5 dimensions space a corner coordinate may be (1, 0, 0, 0, 0). L2’s circle has no corners, so its generically decreases the vector size. That geometric fact is the reason L1 regularization zeros weights out while L2 just shrinks them.
Eigenvalues and eigenvectors
A matrix usually rotates and stretches vectors at the same time. But for certain special directions, it does only stretching no twist. Those directions are the matrix’s eigenvectors, and the scaling factors are its eigenvalues:
- Eigenvector - vector that maps to a scaled copy of itself. The direction goes in, the same direction comes out.
- Eigenvalue - the scalar that says how much stretches that direction.
For an matrix you typically get such pairs: the natural axes of the transformation.
Eigen Values are certainly more niche than dot product or norms. But when you pull out an eigen value reference in front of your machine learning friends at the white board they will be impressed. Here are some places you might use them:
- Principal component analysis (the standard technique for compressing high-dimensional data). The eigenvectors of the data covariance are the directions of maximum variance in your dataset; the eigenvalues tell you how much variance lies along each. Keep the top and you’ve projected your data onto its most informative directions.
- Eigenvalues of the Hessian tell you curvature at a critical point. All positive → minimum. All negative → maximum. Mixed signs → saddle (the failure mode that ate early deep learning).
- Condition number . Big → gradients pull in wildly different scales across directions → optimization is slow.
Singular Value Decomposition (SVD)
It’s great that we can visualize matrices by how they transform space. The problem is most matrices are just a pile of numbers making it impossible to understand. But remember the Matrix Multiplication as Composition section? Matrices are the same as applying transformation A then B. We can leverage this for matrix decomposition where we split any matrix into three separate matrices that rotate, scale then rotate.
- Rotate the input by .
- Scale each axis by its singular value — the diagonal entries of , always real and non-negative.
- Rotate the output by .
The singular values are the matrix’s stretch factors: how much it lengthens or shrinks vectors along its preferred directions. Mathematicians design SVD such that the singular values tell you a lot about the matrix you are dealing with. A practical example would be in matrix approximation. The singular values magnitudes rank the importance of those transformation directions… keep the directions with large singular values and discard those with small ones. For a more in depth explanation check out this channel.
Notation snag: here is just the capital Greek letter sigma, used as the name of a diagonal matrix not a summation. Also people usually make the leftmost column the largest singular value, the second largest and so forth. Since we can choose and we choose ones that work with this ordering. In three dimensions, it literally looks like this:
Another way to look at SVD is
- Columns of are the right singular vectors and each the input direction
- Diagonal entries of are the singular values and each says how strongly transmits
- Columns of are the left singular vectors and the the output direction becomes
If you feed the original matrix its -th right singular vector , it produces the corresponding left singular vector , scaled by the singular value .
From this view it makes a lot of sense why the rank of the transformation is the count of the non-zero singular values. Also note U and V the columns are of unit length 1, and each column is perpendicular to each other.
Rank, null space, column space
Three linear algebra jargon that describe what information a matrix preserves vs. destroys:
- Rank of — the number of dimensions in the output of ‘s linear transformation. For example if a matrix transforms all vectors via onto a plane we would say it has rank 2. Because math connects in bunch of ways you could also say the rank is the number of linearly independent columns (equivalently: rows) in . In SVD terms, the count of non-zero singular values.
- Column space — the set of all possible outputs of as varies. Also the span of ‘s columns. A subspace of dimension equal to the rank.
- Null space — the set of inputs such that . The directions the matrix completely forgets.
In machine learning low-rank structure is everywhere. Trained neural network weight matrices are often empirically close to low rank… most of the useful signal lives in a small number of directions. This observation underwrites weight pruning, LoRA (forcing updates to be rank-), and the broader claim that over parameterized models effectively use a far smaller subspace than their parameter count suggests.
Null space means the data cannot uniquely determine the parameters. If some features are redundant, different parameters can produce exactly the same predictions. The null space contains the parameter changes that the model’s predictions cannot “see” as the loss would be the exact same. L2 regularization resolves this ambiguity by preferring smaller parameters, preventing the parameters from drifting arbitrarily far while making the same predictions.
Linear Algebra — key ideas
Calculus & Optimization Math
Notation used in this section
— function taking -dimensional input, returning -dimensional output
— partial derivative: slope of along axis , all other variables fixed
— gradient at : the vector of all partials
— Jacobian: the matrix of all partials for a vector-valued function; row is the gradient of output
— Hessian entry; is the full matrix of second partials
— condition number; large means the surface has directions of very different curvature
— a small perturbation (a nudge), not machine epsilon
Derivatives and Partial Derivatives
Calculus enters ML through one question: which way should I nudge my weights to decrease the loss? If we think of the Neural Net as a giant function with many, many parameters the derivate answers this question by giving us the best constant approximation of the slope of the loss at the neural nets current parameters.
It’s helpful to think of as a tiny nudge given to the input variable and as the resulting tiny change in the output of the function . The derivative is the scaling factor that tells you how many times larger the output change is compared to your input nudge. In machine learning land you would think about or how nudging the weights will move the loss.
Partial derivatives add one rule: hold every other variable fixed.
A partial is the slope of along one axis, with every other axis frozen. For you get such slopes one per parameter and they’re the components of the gradient. In training, those inputs are weights and the function is the loss, so each partial answers “if I nudge only , how does move”? The catch is that each partial is myopic: it assumes every other weight stays still. In practice you move them all at once, and the gradient is just the vector of these one-knob-at-a-time answers. Interactions between weights live at the second-derivative level, in the Hessian.
The gradient is the vector of all the partials. During gradient descent we compute the gradient (aka weight nudges) for each example in the batch and then average them.:
Note the jacobian is a fancy term for the matrix of all first-order partial derivatives of a vector-valued function . In our case is the number of parameters, is a scalar the loss and we get a column of partials aka the gradient aka the nudges to the weights.
Chain rule
Neural networks are a composition of many functions and to differentiate a composition :
Multiply the local derivatives of each piece, but note where each one is evaluated: at the original input , at the value that actually received. Each derivative is evaluated at whatever its function saw on the forward pass, which is why every ML framework stores activations during the forward pass, backprop needs them to evaluate each local derivative at the right point.
Autodiff on a tiny neural network
Here is the chain rule in the form an autodiff library such as JAX actually encounters it. This network has one hidden neuron, a ReLU, and a squared-error loss:
import jax
import jax.numpy as jnp
def loss_fn(params, x, y):
z = params["w1"] * x + params["b1"]
h = jax.nn.relu(z)
y_hat = params["w2"] * h + params["b2"]
return 0.5 * (y_hat - y) ** 2
params = {
"w1": 1.0,
"b1": 0.0,
"w2": 0.5,
"b2": 0.0,
}
loss, grads = jax.value_and_grad(loss_fn)(params, 2.0, 0.5)
On the forward pass, JAX starts with the supplied example and runs the ordinary computation, retaining the intermediate values needed to differentiate it. The complete forward calculation is
Because the output is a scalar loss, JAX then applies reverse-mode autodiff and moves right to left through the recorded operations. Each operation receives the derivative accumulated from later in the graph, multiplies it by its own local derivative, and passes the result farther backward.
loss, grads = jax.value_and_grad(loss_fn)(params, x, y)∂L/∂b₁ = 0.25
∂L/∂b₂ = 0.50
{ w1: 0.50, b1: 0.25, w2: 1.00, b2: 0.50 }The result has the same pytree structure as params, so an optimizer can pair each parameter with its update directly:
grads = {
"w1": 0.50,
"b1": 0.25,
"w2": 1.00,
"b2": 0.50,
}
JAX does not need to materialize the full Jacobian of the network. Each primitive implements a local reverse rule (a vector-Jacobian product) and composing those rules performs the backward pass efficiently. For a scalar loss, one right-to-left sweep produces the gradient with respect to every parameter. This is the mechanism behind jax.grad and jax.value_and_grad.
Hessian
The gradient is the first derivative. The Hessian is the second, the matrix of all second partials of a scalar function :
For a neural network with scalar parameters, the Hessian is an matrix. Each entry measures how the gradient for parameter changes as parameter changes. Where the gradient gives the best linear approximation of near a point, the Hessian gives the best quadratic one: the curvature of the loss surface, how the slope itself changes as you move. The gradient tells you which way is downhill; the Hessian tells you whether you’re in a bowl, on a ridge, or somewhere in between.
For smooth , because of some smart math proofs we know is symmetric, so we can apply the rotate scale rotate decomposition from the eigenvalue section: ‘s eigenvectors are the principal directions of curvature, its eigenvalues are the curvatures along them. At a critical point (), the signs classify what’s there:
- All positive → bowl. Local minimum.
- All negative → dome. Local maximum.
- Mixed signs → saddle. Surface goes up in some directions, down in others.
What the notation ∂²f / ∂xᵢ∂xⱼ actually means
Read the denominator right-to-left: the variable closest to gets differentiated first.
It’s two ordinary partial derivatives stacked: first take (holding everything except fixed), giving you a new function; then take of that (holding everything except fixed). The “freeze everything else” rule applies at each step independently.
Worked example. Take , and compute — that’s first, then :
Flip the order:
Same answer. That’s Schwarz’s theorem in action — and exactly why , making the Hessian symmetric.
Saddles dominate high-dimensional loss landscapes. In a million-dimensional loss, a true local minimum needs all million eigenvalues to come out positive, vanishingly unlikely if their signs are even somewhat random. Saddles, which need only one eigenvalue of either sign, are way more numerous. Pre 2014, deep learning was supposed to be impossible because the loss had too many bad local minima. The real obstacle was always saddles, and SGD’s noise turns out to escape them readily as long as the gradient picks up the negative curvature direction.
Conditioning and ill-conditioned optimization
Condition number = optimization difficulty. The ratio of the Hessian’s eigenvalues at a minimum measures how stretched the bowl is. Small → roughly circular, gradient descent walks straight in. Large → long, narrow valley where gradient descent zig-zags.
Calculus & Optimization — key ideas
Zoom in close enough on any smooth curve and it looks like a straight line — is that line's slope. Gradient descent is this move once per step; backprop is this move chained through a computation graph.
is evaluated at the original input ; is evaluated at — the value actually received on the forward pass. This is why every ML framework caches activations during the forward pass — backprop needs them to evaluate each local derivative at the right point.
It tells you whether you're in a bowl, on a ridge, or somewhere in between.
All negative → dome. Local maximum.
Mixed signs → saddle. Surface goes up in some directions, down in others.
In high-dimensional loss landscapes, saddles dominate: a true minimum needs all eigenvalues positive (exponentially unlikely), while a saddle only needs one of either sign.
Probability
Notation used in this section
, — random variables (capital letters); , — specific values they take (lowercase)
— probability mass: how often discrete variable equals
— probability density: not a probability itself; integrate over a range to get probability
— joint distribution over two variables simultaneously
— conditional distribution of given
— expectation (probability-weighted average). The subscript in names the distribution: draw , evaluate , average — i.e. . The same appears as both the subscript label and the density inside the integral.
— variance; is the standard deviation
— Gaussian with mean and variance ; multivariate version uses covariance matrix
— ” is sampled from distribution ”
— and are conditionally independent given
Random variables, PMFs / PDFs
A random variable is a number you read off some random process - a die roll, a noisy sensor reading, the loss on a random minibatch. The random variable’s distribution maps possible outcomes to their probability of occuring represented as a number between 0 and 1.
A random variable has two flavours depending on if it takes discrete or continuous values:
- Probability Mass Function for discrete Random Variables. is the probability of each specific value, and the values sum to 1.
- Probability Density Function for continuous Random Variables. is a density its area under a range gives the probability of landing in that range, and the total area under is 1.
PMFs and PDFs are different mathemtical objects that you can’t really just exchange for one another. For a continuous random variable the probability that equals exactly 0.81485… is 0, you can always make the value more specific. It’s a bit confusing because in ML you constantly see continuous distributions but this is a probability density not a probability itself. For PDFs you have to consider ranges . You think of the area under the curve not the height of the curve as the probability and to find the area under a curve you integrate. Once I internalized this distinction probability clicked a lot for me.
A note on notation. Capital is the random variable itself, the unrealized abstraction. Lowercase is a specific value it might take. So reads “the probability that the random variable comes out equal to the specific value .”
Expectation and Variance
of a random variable is a tries to capture the center of the random variable’s distribution and can be interpreted as the long-run average of many independent samples from the given distribution:
of a random variable quantifies the spread of that random variable’s distribution:
Squaring does two things: deviations above and below the mean don’t cancel, and large deviations are penalized more than small ones. The standard deviation converts back to the original units.
Joint, marginal, conditional distributions
A joint distribution tells you how often each combination of values shows up, not just how often or separately, but how often the two happen together. It’s a 2D distribution or higher with more variables.
Marginal distribution: sum out the variable you don’t care about. You’re projecting the 2D joint down onto one axis. is what the distribution of would look like if you’d never bothered tracking at all.
Conditional distribution: slice the joint at a specific value, then renormalize. The distribution of now that you know .
Covariance and Correlation
Knowing the distribution of each variable separately does not tell us how they relate. Imagine a dataset containing each person’s height and weight. If we randomly shuffle the weights between people, the distribution of heights is unchanged and the distribution of weights is unchanged, but the relationship between height and weight has mostly disappeared. Covariance measures the part that the two marginal distributions miss: whether deviations in one variable systematically accompany deviations in the other. For each person, subtract the average height and average weight to get two signed deviations. Multiplying them gives a positive value when the person is above average in both variables or below average in both, and a negative value when the deviations point in opposite directions; covariance is the average of those products.
The scale depends on the units of and , which makes raw covariance hard to interpret across different features. Correlation fixes that by measuring both deviations in standard deviations:
- This normalization constrains correlation to the interval
- A correlation of means the standardized variables move in perfect lockstep: whenever one is a certain number of standard deviations above or below its mean, so is the other
- A correlation of means they move in exactly opposite directions
- A correlation near zero means there is little linear alignment between them
The word linear matters. Zero correlation does not imply that two variables are independent. If and is symmetrically distributed around zero, knowing determines completely, yet their covariance can be zero: positive and negative values of cancel when multiplied by . Covariance and correlation detect straight-line structure, not every possible kind of dependence.
The covariance matrix is something you will run across and generalizes this to random variables at once. Entry ; the diagonal is just the variances.
Common distributions
It’s good to know some of the common distributions that show up over and over again, especially the gaussian.
Central Limit Theorem
The Central Limit Theorem states that the sample mean of a sufficiently large number of independent identically distributied random variables is approximately normally distributed. The larger the sample, the better the approximation. Its a two part operation:
- Sample a batch and take their average
- As you take more and more batch averages you see that the averages are normally distributed
Central Limit Theorem comes up constantly in ML and it is the reason why Gaussians also appear everywhere. Any quantity that’s the sum or average of many independent effects ends up Gaussian.
Two things to notice: averaging samples leaves the mean unchanged, while the variance shrinks by , so the standard deviation shrinks by . Four times as many samples therefore gives half the spread. Repeating the experiment across batches gives us more draws from this same sampling distribution; it does not narrow the distribution, whereas increasing does. Minibatch gradients are a classic example. A batch gradient averages per-example gradients, so the CLT suggests , where is the true gradient. Doubling halves the gradient-noise variance and reduces its standard deviation by ; quadrupling halves the standard deviation. This cleaner gradient estimate is one reason larger batches can often support larger learning rates, although the exact scaling depends on the training regime.
Bayes’ rule
Bayes’ rule answers a specific question: you know how to compute the probability of seeing your data given a hypothesis. But what you want is the reverse: given the data you actually observed, how probable is each hypothesis? That’s , and Bayes’ rule is how you flip the arrow:
- — prior: your belief about before seeing any data.
- — likelihood: how probable is this data if were true.
- — posterior: your updated belief after seeing the data. The prior reshaped by evidence.
In ML, is the model parameters and is the training data. The three terms translate directly to things you already know:
- Likelihood — how well do these weights fit the training data? This is your loss function in disguise: low loss = high likelihood.
- Prior — what weight values do you expect before seeing any data? A prior that prefers small weights is L2 regularization.
- Posterior — the full distribution over weight settings after training.
doesn’t depend on (a constant that gets ignored in the gradient) so to find the best you can ignore it.
Tak the log: maximizing is exactly loss + regularizer. When you train a network with weight decay, you are doing Bayesian MAP estimation — a Gaussian prior on the weights is L2, a Laplace prior is L1. Every regularizer is a prior in disguise.
Independence and conditional independence
A joint distribution over binary variables has cells. For a 28×28 image that’s . No dataset fills it, and no model stores it. The whole history of generative modeling is the story of how to get around this.
Independence means knowing one variable tells you nothing about another — . Conditional independence is subtler: and may be correlated overall, but become independent once you fix , written :
All shared variation between and flows through . Fix , nothing is left to share.
Early ML solved the tractability problem with explicit independence assumptions. Naive Bayes assumed each feature is independent given the class label, turning one enormous joint into a product of small marginals. N-gram language models assumed each word depends only on the previous words. Both assumptions are obviously wrong — but they made estimation possible from limited data, and the predictions were often good enough anyway.
Naive Bayes: worked example
Take spam detection. You want to classify an email as spam or not. An email is a bag of words, each present or not — the full joint has entries. With a 10,000-word vocabulary that’s cells. No dataset fills it.
Naive Bayes assumes each word is independent of every other word given the class:
Now you just need one number per word: “how often does this word appear in spam?” Count frequencies in your training data and you’re done.
To classify a new email, you want . By Bayes’ rule, that’s proportional to — so compare:
Pick the larger one. “Nigerian” and “prince” co-occur in spam far more than chance predicts, so the independence assumption is wrong — but the rank order between classes survives anyway. The genuinely likelier class still wins even with miscalibrated probabilities.
Modern generative models dropped the explicit assumptions. A transformer doesn’t assume any token is independent of any other — it attends to the full context. Instead it uses the chain rule, which is always valid:
Then approximates each conditional with a neural network. No hardcoded independence structure — just a flexible function trained on enough data to learn whatever conditional structure actually exists.
One catch: conditioning can create dependence, not just destroy it. Talent and luck are independent in the population. Filter to successful hires — conditioning on their shared effect — and they become negatively correlated. Knowing someone got lucky makes talent less necessary to explain their success. You manufactured a dependence that wasn’t there.
This is the collider trap: filter to high-quality training examples, evaluate only on accepted submissions, control for a mediator in a causal analysis — any time you condition on something downstream of two variables, you induce a spurious dependence between them. d-separation gives you the formal rules for when this happens.
Finally, the iid training assumption is also a conditional independence claim — each example contributes new information. Violate it (correlated sequences, duplicate data, patients from the same hospital) and your effective sample size is smaller than your dataset, and your generalization gap is larger than train loss suggests.
Monte Carlo Methods
Often in ML we don’t know a probability distribtuion be we can sample from it. The Monte Carlo methods are ways to learn about the unkown probability distribution through sampling.
| Method | What access do we have? | What do we do? |
|---|---|---|
| Direct Monte Carlo | Can sample | Average |
| Importance sampling | Can sample from and evaluate | Draw from , then reweight |
| MCMC | Can evaluate up to a constant, but cannot sample directly | Construct correlated draws whose long-run distribution is |
Note Bootstrapping is a related but different technique. In bootstrapping we have an observed dataset (we can’t just sample) and we typically create simulated datasets by sampling the original datasets with replacement. We then compute our statistic on each resampled dataset and see how much it varies. For example, repeatedly resample a test set, calculate model accuracy each time, and use the spread to estimate an accuracy confidence interval.
“I’m averaging random samples to approximate a quantity” → Monte Carlo
“I’m resampling my dataset to see how my estimate would vary” → bootstrap
Direct Monte Carlo: estimate an expectation by taking a bunch of samples and averaging.
- is the data distribution.
- is a randomly selected training example.
- is the -th example in your minibatch.
- is the model’s loss on that example.
- measures how much the loss varies between examples. If some examples have tiny losses and others have huge losses, is large, so you need a larger minibatch for a stable estimate.
Some interesting things to note
- This is a result of the Law of Large Numbers which says if you repeatedly sample from the same distribution, the sample average approaches the distribution’s true expected value
- The Central Limit Theorem quantifies how the number of samples determines how uncertain you answer is. The estimate has error , where is the standard deviation of under
The pain point with monte carlo methods is variance, when is large, you need huge . Policy gradient is a good example: rewards on rollouts are wildly variable, is enormous, and a single REINFORCE update looks like pure noise. Baselines, GAE the whole variance-reduction wing of ML exists to shrink so you can get away with fewer samples.
Importance sampling: reweight when you can’t sample from .
Importance sampling is a Monte Carlo method used to approximate the properties or expected values of a target probability distribution p(x) by drawing samples from a different, more convenient proposal distribution q(x). Sample from , multiply each by the importance weight , and you get an unbiased estimate of the expectation under . Regions where get upweighted; regions where get downweighted. In math notation the reason this works is:
PPO on an LLM is a canonical example where you have many samplers generating long rollouts. When you take a gradient step with your policy you don’t pause training to send the new weights to the samplers, and restart all the in progress rollouts. Instead you accept many of your rollouts are from and reweight using importance sampling.
The danger is when if an unlikely is sampled in a the importance weight can explode to 80 in this case. You generally want to fully cover and have strong support for all regions of and avoid having lighter tails than . In PPO, this is exactly what goes wrong when drifts far from : some blow up and training explodes. PPO’s fix is to clip to introducing a small bias in exchange for dramatically lower variance.
Markov Chain Monte Carlo: when no tractable proposal works.
If we can’t sample from and there is no alternative , but we can check the probability of for whatever we can come up with then Markov Chain Monte Carlo can help. Image generators are a good example as the image space is so vast and the distribution so complex that no clever proposal from the previous section will ever cover it. MCMC’s answer is to instead start with an image of random noise and wander through the space step-by-step, biased toward higher-probability regions by assessing the probability of generating that image. Over time the positions you visit look like samples from .
The textbook algorithm is Metropolis-Hastings. From the current position :
- Take a small random step from e.g., add a Gaussian nudge to get a candidate .
- Compare densities. If (the candidate is at least as likely), accept the move.
- Otherwise accept with probability the smaller the drop, the more often you still take the step.
- If you reject, stay at . Repeat.
The third rule is key, as over time, MCMC visits each region in proportion to its probability under . Once we obtain samples from MCMC we can utilize Direct Monte Carlo from earlier.
Probability — key ideas
PDF (continuous): is a density, not a probability. Integrate over a range to get probability: . Total area is 1, but itself can exceed 1 at any point.
is the partition function (a.k.a. normalizing constant). Often is cheap but is intractable — energy-based models with are the canonical case. MCMC and self-normalized IS exist to sample without ever computing .
It collapses a 2D distribution into a 1D one along the axis you kept. Conceptually: ignore , just tell me how often each happens.
Likelihood — how well these weights fit the data (= negative loss, up to a log).
Prior — what weights you expect before training (e.g., a Gaussian prior = L2 regularization).
Posterior — distribution over weights after training.
That's the surprising part. Variance only adds for independent variables: requires independence. Linearity of expectation is why minibatch gradients are unbiased estimates of the true gradient — you can swap and without caring about correlations between samples.
The second form (mean of square minus square of mean) only requires running sums of and , so you can compute variance in one pass over the data without first finding the mean. It's how
numpy.var and online statistics estimators work.is symmetric and positive semi-definite. Its eigenvectors are the principal axes of the distribution; eigenvalues are the variances along those axes — exactly what PCA computes.
In ML: a minibatch gradient is a sample average of per-example gradients, so by the CLT it's approximately Gaussian noise around the true gradient — doubling the batch size halves the noise standard deviation.
- Take a small random step (e.g., add a Gaussian nudge) to get a candidate .
- If , accept — uphill always.
- Otherwise accept with probability — the smaller the drop, the more often you still take the step.
- If you reject, stay at . Repeat.
Information Theory
Information
Notation used in this section
— a particular message or outcome; is the random variable that produces it
— the true probability that outcome occurs
— a model’s assigned probability for outcome
— the codeword assigned to message : the actual bit string sent for that message
— the code length of message : the number of bits in its codeword
A codeword is the bit string assigned to one message; its code length is simply the number of bits in that string. With four equally likely movement commands, a straightforward fixed-length code is:
| Message | Codeword | Code length |
|---|---|---|
| up | 00 | 2 bits |
| down | 01 | 2 bits |
| left | 10 | 2 bits |
| right | 11 | 2 bits |
— information content (or surprisal) of one outcome, in bits
— entropy: ideal average code length for data drawn from
— cross-entropy: average code length when data comes from but the code is based on
— extra average code length from using instead of
What does it mean for an observation to contain information? Not “is it interesting?” and not “how many characters did we write down?” In information theory, the question is sharper: how much uncertainty did seeing this particular outcome remove? “The sun rose this morning” may matter enormously, but if it was nearly certain, observing it communicates little new information.
Compression gives this information concept a physical meaning. If sender and receiver agree on a distribution over messages, they can compress the messages by giving likely messages short bit strings and unlikely messages long ones. The number of bits an outcome deserves is its information content.
The core formula for information falls out when you realize that you cannot compress random noise. Imagine receiving an -bit message whose bits are independent fair coin flips. There are possible strings of that length, all equally likely, so any particular one occurs with probability
There is no regularity to exploit: knowing the first bits tells you nothing about the last one. A lossless compressor cannot make this uniform collection of messages shorter on average. In other words, an ideal compressor should look like random noise. It has removed every predictable pattern it can.
If a message has probability and an ideal code assigns it bits, then . Solving for gives
We call the information content (or surprisal) of outcome , measured in bits. For a sequence, the probability of the complete message is the product of the probabilities of its successive symbols, each conditioned on the preceding context:
Taking turns that multiplication into addition. So the information in a whole message is its sequence of per-symbol information, added together:
Entropy
Before a sample arrives, we do not know which outcome will occur; we only know the distribution . So the natural question is: how many bits will we need on average? Weight each outcome’s information by its chance of occurring:
This is Shannon entropy. It is the average surprisal of a draw from , and more operationally the theoretical lower limit on the average number of bits per symbol needed to losslessly encode independent samples from that distribution.
In ML classification labels, token sequences, and latent variables are all draws from distributions. Entropy tells you the compression limit. For example, the compression limit of code is lower than books because of the boilerplate and repeatable patterns in code.
Move toward an even split to make the next observation harder to predict.
Cross-entropy
Entropy was the ideal case: your encoding matches reality. A message that occurs with probability gets an ideal code length of bits. Averaging over messages gives the irreducible compression limit aka entropy.
Cross-entropy changes one thing: your compressor is built using a model , which may be wrong. “If the world draws messages from distribution , but I compress them using beliefs , how many bits per message will I spend on average?”
Try the two codebooks. When $q=p$, the average extra-bit bucket is empty; a mismatched $q$ makes it fill.
There is one practical wrinkle: ML libraries almost always use natural logs, so cross-entropy loss is reported in nats, not bits. Optimizing either gives the same model. Bits are better for intuition; nats are conventional because calculus with is convenient.
KL divergence
Cross-entropy measures the total average code length, and entropy the best possible code length. KL divergence is the difference between them: the extra bits per message from encoding -data with .
Entropy is the unavoidable uncertainty in the data; the KL term is the extra code length from a wrong model.
- : the best possible average code length
- : extra bits paid because does not match
- : total bits your particular model needs
KL divergence is not symmetric. means “data comes from ; I encode it using .” Reversing the arguments changes both the data source and the codebook.
Perplexity
Perplexity is just cross-entropy converted back out of logarithmic units. Cross-entropy tells you the model’s average surprise in bits (or nats in most ML libraries). Perplexity exponentiates that quantity.
where
The best intuition is that perplexity is the effective number of plausible choices. If the model is equally uncertain among four next tokens, it assigns each probability . Its cross-entropy is bits and its perplexity is . So the model is, in effect, choosing among four equally plausible continuations.
A few important caveats:
- Lower is better. It means the model assigned more probability to the tokens that actually appeared.
- Perplexity depends on tokenization. A character-level model and a BPE-token model cannot compare perplexities directly; one predicts many more, smaller units.
- It is not a general intelligence score. Perplexity measures predictive/compression performance on a particular distribution. A model can have excellent perplexity yet still be bad at reasoning tasks, tool use, or following instructions.
- It is especially natural for language modelling. It is less commonly reported for classification because “effective number of classes” is often less informative than accuracy, calibration, or log loss.
Information Theory — key ideas
“The sun rose this morning” may matter enormously, but if it was nearly certain, observing it communicates little new information.
More probable outcomes get shorter codes; an outcome with probability costs bits.
It is the average information and the theoretical minimum average number of bits per independent draw needed for lossless compression when the encoder knows the true distribution .
is the distribution that produces the data (the internet); is the model used to assign probabilities (the llm).
So chooses which outcomes are averaged over, while determines the surprise/cost charged to each outcome.
Therefore:
Training with cross-entropy therefore increases the probability assigned to the true label.
: the best possible average code length—the unavoidable uncertainty in the data.
: extra bits paid because does not match .
: total average code length using your particular model.
So KL divergence is the extra average code length from encoding -data with .
when cross-entropy is measured in bits.
It is the model's effective number of equally plausible next-token choices. For example, bits of cross-entropy corresponds to perplexity : roughly the uncertainty of choosing among four equally likely continuations.
Only compare perplexities computed with compatible tokenization and evaluation data.
Statistics & Estimation
Notation used in this section
— population mean: the true average of the whole population
— population standard deviation: the true spread of individual values around
— sample mean: the average of the values we observed
— sample standard deviation: our estimate of from the observed sample
or — number of observations in a sample or dataset
— an estimate of ; the hat means “estimated from data”
— standard error: how much would vary across repeated samples
— an observed dataset
— probability or density assigned to given parameters
— likelihood: how well the parameter setting explains the observed data
— expected value: the probability-weighted average of
— variance: the average squared distance of from its mean
Expected loss and Empirical Estimates
Ideally, we would evaluate the model on every example it might encounter in the real world and calculate its average loss. For a language model, it is the average prediction error across all text the model might encounter not merely the text in its training set. Learning theory calls this quantity the population risk
We cannot compute this directly because we do not possess every possible example. Instead, we average the loss over a finite dataset. This dataset average is the empirical risk our measurable estimate of the expected loss on the real world.
During training, even that average is expensive, so each update uses a smaller random minibatch:
Likelihood and Maximum Likelihood Estimation (MLE)
In MLE, you choose a probability distribution such as a Gaussian or a model such as a neural network and then simply choose the parameters that best fit the samples you have. Thats the whole idea. Put another way MLE chooses the parameter setting under which the data we observed looks least surprising. Suppose we record the maximum squat of everyone at a gym and model those weights with a Gaussian distribution. The Gaussian has two parameters: controls the typical squat weight, and controls how much lifters vary around it. For any choice of and , the Gaussian assigns a density to every observed squat. In stats likelihood has a specific definition that asks: under these parameters, how plausible is the dataset we actually observed?
Maximum Likelihood Estimation chooses the parameters that maximize this value:
Maximum a Posteriori (MAP)
MLE chooses the parameters that best explain the observed data. MAP does the same thing, but also considers what parameter values were plausible before seeing the data. Suppose we observe only three people at a gym squatting 315, 335, and 350 lb. MLE would estimate the gym’s typical squat near their average but perhaps we happened to sample the powerlifting team. From experience with similar gyms, we may have a prior belief that the typical squat is closer to 225 lb.
Let represent the gym’s unknown true average maximum squat, the center of the Gaussian for all its lifters. We compare possible values of . For simplicity, assume the spread is already known and estimate only . Bayes’ rule combines our prior with the evidence from the three observed lifters:
- is the squat data we observed.
- is the likelihood: if the gym’s true average were , how plausible would it be to observe these three squats?
- is the prior: before sampling anyone, how plausible did we think each possible gym average was?
- is the posterior: after seeing the three squats, how plausible is each possible gym average now?
MAP chooses the peak of that posterior:
With little data, the prior pulls the estimate toward 225 lb. As we observe more lifters, the likelihood becomes sharper and the data overwhelms the prior. MAP approaches MLE.
This connects directly to regularization in neural networks. A Gaussian prior that prefers small weights contributes an L2 penalty. The data says “fit the examples”; the prior says “prefer simpler, smaller parameters unless the data strongly demands otherwise.”
Bias, Variance, and Consistency of Estimators
An estimator is a rule that uses a sample to guess an unknown quantity. For example, we might estimate a gym’s true average maximum squat using the average of ten observed lifters. If we repeatedly sampled ten different lifters, we would get a slightly different estimate each time. The pattern across those repeated estimates tells us whether the estimator is good:
- Bias: Are its estimates centered on the true value, or systematically too high or low?
- Variance: How much do its estimates change from one sample to another?
- Consistency: As the sample grows, does the estimator converge to the true value?
Imagine the gym’s true average squat is 275 lb. Estimates clustered around 300 lb have high bias but low variance. Estimates scattered from 200 to 350 lb have low bias but high variance if their center is still 275 lb. Estimates tightly clustered around 275 lb have both low bias and low variance.
These two errors combine:
An estimator can deliberately accept some bias to reduce variance. MAP does exactly this: its prior pulls estimates away from the sample mean, introducing bias, but can make them much more stable when data is scarce.
Standard Error, Confidence Intervals, and The Bootstrap
A dataset gives you one estimate. A different dataset would give you a slightly different estimate. Standard error measures how much that estimate would wobble across repeated datasets. For the average squat,
Standard deviation and standard error describe the spread of two different things:
- Standard deviation: How much individual observations vary
- Standard error: How much an estimate would vary if you repeatedly collected new datasets
Here, is the sample standard deviation of the individual squat weights: is one lifter’s squat, is their average, and is the number of lifters. More samples leaves the observations’ standard deviation roughly unchanged, but more samples reduces the mean’s standard error at roughly .
A confidence interval turns that uncertainty into a range. A rough 95% interval is
“95% confidence” means that if we repeatedly collected data and built intervals this way, about 95% of them would contain the true value. But is only for the mean. Other ML statistics, such as F1, calibration error, or the performance difference between two models, do not have a simple standard-error formula, so we instead use the bootstrap to approximate repeated data collection using the dataset we already have:
- Sample examples from the dataset with replacement
- Compute the statistic
- Repeat many times
The standard deviation of those bootstrap estimates gives the standard error; their central 95% gives a confidence interval.
Bayesian and Frequentist Framing
Statiticians have been locked in metal warfare for centuries on how to frame their field Bayesians vs Frequentists. This probably doesn’t matter much for an ML engineer, but it is good context. The cleanest difference is what is allowed to vary. Suppose is the gym’s unknown true average squat.
- Frequentist: is fixed; the dataset is random. Imagine repeatedly sampling lifters and ask how often your method finds the truth.
- Bayesian: the dataset is fixed; our uncertainty is over . Combine the observed squats with a prior to obtain .
This changes the meaning of a 95% interval:
- A 95% confidence interval comes from a procedure that would contain the fixed in 95% of repeated datasets.
- A 95% credible interval contains 95% of the posterior probability for , given the observed data and model.
The Bayesian statement is more direct: “given our assumptions and this data, there is 95% posterior probability that lies here.” But it depends on the prior and model being reasonable. The frequentist statement is less direct, but gives a repeated-experiment guarantee without assigning probabilities to the fixed parameter.
In ML, frequentist tools such as confidence intervals and the bootstrap ask whether a reported improvement would survive a new test sample. Bayesian methods are useful when we want a distribution over parameters or predictions, especially when prior knowledge matters or data is scarce. With enough data and compatible assumptions, the two often give similar answers.
Training Loss, Generalization, and Calibration
Training loss measures how well a model fits examples it has already seen. Generalization asks how well it performs on new examples from the same distribution. That is why we evaluate on held out data. The difference between held out loss and training loss is the generalization gap:
Calibration asks a different question: when the model says “80% confident,” is it correct about 80% of the time?
A model can have good accuracy but poor calibration. If it gets 8 of 10 predictions right while claiming 95% confidence, its accuracy is still 80%, but it is overconfident.
Statistics & Estimation — definitions
Empirical risk is the average loss on an observed dataset—our measurable estimate of population risk.
Likelihood asks: “If these were the parameters, how well would they explain the data we observed?”
MAP also incorporates a prior:
The prior matters most when data is scarce.
Variance: how much the estimates change from one sample to another.
Consistency is an asymptotic guarantee; it does not guarantee a good estimate from a small sample.
The standard error measures how much the estimated mean would vary across repeated samples:
The standard deviation of the resulting estimates approximates the statistic's standard error.
A 95% credible interval contains 95% of the posterior probability for the parameter, given the observed data, model, and prior.
A growing gap means the model is improving on seen examples without transferring that improvement to unseen examples.
For example, predictions labeled 80% confident should be correct about 80% of the time.
Geometry & High-Dimensional Intuition
Curse of dimensionality
If each of features can take meaningfully different values, the number of possible combinations is . Each added dimension multiplies the space by . Unless the dataset grows just as quickly, training data is like stars in outerspace, small specs in a vast sea of nothing.
The counter of this idea that all data lives on a small sub manifold due to the physics of our universe. Take Tesla self driving which has used eight external cameras; modeling each as a RGB image gives roughly million values per instant and possible inputs. Yet most images it sees occupies only a thin, structured subset of that space.
The Square Root Scaling Rule
Imagine repeatedly flipping a coin and moving +1 if heads and -1 if tails. After 100 steps, you would usually not be 100 steps from the origin as the directions cancel. A typical final distance is around . This also works more generally even if the random variable is not centered. If the random variable has mean , then
The sum grows like , while the standard deviation grows only like . As we will see in the next section the relative difference, versus , is what causes concentration in high dimensions.
Attention Scaling
Square-root scaling shows up all over the place in ML. For example this is the reason why we divide by the in attention. An attention score is a dot product:
Since the query and key weights are roughly independent and centered their dot product is going to be mean 0 with a standard deviation away from zero, just like our coin walk was. Therefore attention uses:
to keep the logits at roughly the same scale as the head dimension grows. Without this scaling, wider query and key vectors produce increasingly large logits. Softmax then becomes extremely peaked, and its gradients can become very small.
Neural Network Initialization
Neural network initialization also uses . A neuron computes
If every weight had the same scale regardless of , the output would grow like as the layer became wider. To cancel that growth, initialize each weight with a scale proportional to . Xavier and He initialization are refined versions of this idea: choose weight variance so activations and gradients maintain a reasonable scale across layers.
Concentration of Measure
Concentration of measure is the phenomenon that in high dimensions, individual coordinates remain noisy, but aggregate quantities like a vector’s norm often become highly predictable, even though the space itself is enormous.
Square-root scaling describes the standard deviation when we add roughly independent terms. Concentration occurs when the standard deviation becomes small relative to the quantity’s overall scale. If the expected sum grows like while its standard deviation grows only like , then
In ML this shows up whenever we aggregate many roughly independent contributions. A high-dimensional vector has many coordinates, each of which can vary substantially. But quantities that combine all those coordinates, such as the vector’s norm, often vary surprisingly little.
The visual samples vectors . Their individual coordinates keep jumping around as increases, but their lengths become steadily more predictable. That happens because the squared length is itself a sum:
so almost every vector has length . Geometrically, the samples collect in a thin shell at radius .
Here is the surprising part: the Gaussian density is highest at the origin, yet a high-dimensional Gaussian sample almost never lands near it. As we move away from the origin, each individual point becomes less likely, but the shell of available points becomes vastly larger. In high dimensions, the abundance of points wins: no particular point on the shell is especially likely, but a sample will almost certainly land somewhere on it.
This is the difference between the mode and the typical set. The mode is the single point with the highest density—the origin in this example. The typical set is the thin shell containing nearly all the samples. High dimensions separate “the most likely point” from “where samples are likely to be.”
For ML, the practical intuition is simple: high-dimensional randomness can be chaotic coordinate by coordinate while remaining highly structured in aggregate. Gaussian initialization and Gaussian noise produce unpredictable entries but a dependable overall scale. Norms and distances in many high-dimensional representations likewise cluster into narrow ranges.
Check out Sander’s excellent blog for a deeper dive.
Near-orthogonality in high dimensions
In high dimensions, two independent random directions are usually close to perpendicular.
To see why, imagine a simplified pair of random vectors whose parameters are either or . In each coordinate, their signs either match, creating some alignment, or oppose each other, creating an equal amount of anti-alignment. Because the vectors are unrelated, both outcomes are equally likely.
Across many dimensions, roughly half the parameters match and half oppose, so their effects nearly cancel. For example, if of parameters match and oppose, pairs cancel completely, leaving only net alignment. They will not always balance perfectly, but the leftover imbalance becomes a smaller fraction of the whole as more dimensions are added. Real random vectors have parameters of varying sizes rather than just , but the same cancellation occurs and pushes their cosine similarity toward zero.
The leftover accidental alignment has a typical scale of , so in dimensions random cosine similarities are commonly around . This gives embeddings room to encode many directions that interfere only weakly with one another. Learned embeddings are not truly random, but a cosine near zero is still a useful baseline for “no more aligned than chance.”
Why this matters for LLMs: the residual stream and superposition
At each token position, a transformer’s residual stream is one dimensional vector that acts like a shared workspace. Every attention head and MLP reads selected information from it through a linear projection, then writes its result back by addition. Information written by an early layer therefore remains available to later layers unless some later computation removes or overwrites it. This read/write view is developed in A Mathematical Framework for Transformer Circuits.
That one vector may need to simultaneously carry many facts about the current token: which entity is being discussed, its grammatical role, facts retrieved about it, the task being performed, and partial conclusions produced by earlier layers. The model can associate each feature with a direction and represent the current state as a sum:
A later component can look for the basketball feature by projecting onto . The basketball direction contributes strongly to that read, while unrelated feature directions contribute only their small accidental overlap. Near-orthogonality therefore lets the residual stream behave like many weakly interfering communication channels laid on top of one another. More complex information can occupy a multi-dimensional subspace rather than a single direction, allowing an attention head to read or write a structured bundle of features at once.
There is an important limit: a -dimensional space can contain at most exactly orthogonal directions. But it can contain far more than approximately orthogonal directions. Models exploit this by assigning more features than dimensions and accepting some cross-talk between them, a compression strategy called superposition. This works because features are sparse: the model may know an enormous number of possible features, while only a small fraction are relevant to any particular token. When few are active, their interference remains manageable; if too many activate together, the noise accumulates and starts to obscure the signal. Toy Models of Superposition explores this trade-off directly.
This has several practical consequences:
- Features are not the same as neurons. A meaningful concept may be a direction spread across many parameters, while a single neuron can participate in many different features. Sparse autoencoders try to undo this compression by expanding a dense residual vector into a much larger space where only a few interpretable features are active.
- Wider models can form cleaner representations. More residual-stream dimensions give important features more room to separate, reducing interference. A narrower model may know many of the same features but represent them less reliably.
- Many computations can coexist. Different heads and MLPs can read and write different directions or subspaces of the same residual stream, allowing syntactic, semantic, factual, and task-related information to move through the model in parallel.
Geometry & High-Dimensional Intuition — key ideas
Unless the dataset also grows exponentially, it becomes increasingly sparse relative to the space.
As a result, aggregate quantities such as a vector's norm can vary surprisingly little.
For a high-dimensional Gaussian, two factors compete as you move away from the origin: each individual point becomes less likely as density falls, but the amount of available space grows dramatically. The vast number of possible points in the larger shell outweighs their lower individual density, so samples typically land away from the mode.
“Orthogonal” is the vector-space version of “perpendicular.”
The leftover imbalance becomes a smaller fraction of the whole as dimension grows, pushing cosine similarity toward .
This makes the residual stream a shared communication channel across layers.
This is superposition: it supports more possible features than dimensions at the cost of some interference.
Deeper Connections and a Bag of Tricks
The Gradient Reveals the Update Rule
A loss tells us how a model is scored. Its gradient with respect to the parameters tells us what gradient descent will actually change. When a loss looks opaque, take one training example and ask: Which parameters move, in what direction, and when does the update vanish?.
Take softmax cross-entropy. A linear classifier stores one weight vector for each class. For an input representation , it computes
The gradient with respect to each class’s weight vector is
where is for the correct class and otherwise. Gradient descent therefore updates
The loss has become an update rule:
- The correct class weight moves toward .
- Incorrect class weights move away from ; the class receiving the most mistaken probability gets pushed hardest.
- If the model is confidently correct, and the entire update is nearly zero.
Every weight moves along the example’s representation . In a neural network, is the final hidden representation and these are the final-layer weights; backpropagation carries the same correction signal into earlier layers.
Stable probability computations
Logs and exponentials let us switch between multiplicative and additive views of the same calculation. Taking a log turns a product into a sum so multiplying many probabilities becomes adding log-probabilities, which is both easier to work with and less likely to underflow. Exponentiation reverses it: softmax exponentiates logits into positive scores, while cross-entropy takes the negative log of the correct class’s probability so that confident mistakes receive a large penalty.
When ML engineers say they are working in log space, they mean storing and manipulating instead of itself. Multiplication becomes addition, division becomes subtraction, and the result is exponentiated only when an ordinary probability is actually needed. This keeps the probability of a long token sequence from being rounded down to zero.
Exponentials create the opposite danger: large logits can overflow. Softmax is unchanged if every logit is shifted by the same amount, so implementations subtract the largest logit before exponentiating:
The related log-sum-exp trick computes as . In practice, stay in log space and use fused operations such as logsumexp and log_softmax rather than exponentiating and then taking a log again.
y = eˣ
additive input → multiplicative output
y = ln x
multiplicative input → additive output
y = −ln x
small inputs → large penalties
Loss Functions as Probabilistic Assumptions
A nueral network produces numbers (ex logits), but those numbers do not have probabilstic meaning by themselves. We give them meaning by choosing a likelihood family. Gaussian, Bernoulli, Categorical and so on and letting the network predict the distrution’s parameters:
Training then adjusts to make the observed targets likely. Each term asks: “How surprising is the observed target under the distribution predicted for ?”
For example, we can choose the probabilistic model to be Gaussian and decide that its output should mean “the mean of a Gaussian” and that the residual noise should be Gaussian. With fixed , minimizing the negative log-likelihood reduces to MSE.
The neural network computes
The same thing occurs in Large Language Models. The network determines the logits, while we chose to interpret their softmax as the parameters of a categorical distribution. This choice leads to cross-entropy.
So choosing a loss means deciding how to interpret the network’s outputs and which errors the model should consider plausible. MSE heavily penalizes large residuals because Gaussian noise treats them as exceptionally unlikely; MAE is more tolerant because the Laplace distribution assigns more probability to large deviations. The likelihood family supplies the assumption, the neural network predicts its parameters, and the resulting negative log-likelihood supplies the loss.
Equivalent Objectives and Disappearing Constants
Two formulas can look different but still lead training to exactly the same model parameters. An optimizer only cares about ranking the choices of . Adding the same number to every score, or multiplying every score by the same positive number, cannot change which one wins:
An strictly increasing function such as also preserves the ordering. This is why maximizing a product of likelihoods is equivalent to maximizing their log-likelihood sum, and therefore to minimizing negative log-likelihood:
Avoiding Optimizing Constraints
Some quantities are only valid inside a restriced range: a standard deviation must be positive, a probability must lie between zer and one, and a set of class probabilities must sum to one. Directly optimizing these constrained values is akward, a gradient step could make a standard deviation negative or push a probability above one.
The usual trick is instead of forcing the opimizer to obey a constraint, choose parameters in which every possible value is already valid. The transformation enforces the constraint automatically, although it also changes the geometry through which the gradient moves. For example, sigmoid turns an real number into a probabilities between 0 and 1, and softmax turns any vector of logits into nonnegative values that sum to one.
Parameters are Not the Model
A neural network’s weights are one way of writing down a function, but they are not the function itself. Different parameter values can produce exactly the same output for every input. Adding the same constant to every logit leaves softmax unchanged. ReLU networks allow some weights to be scaled up if the following weights are scaled down.
This means that two independently trained networks can implement similar functions while having very different raw weights. It also explains why loss landscapes contain many equivalent solutions and why comparing neurons or parameters across models can be misleading.
Differentiating Through Randomness
When a model samples a random value during its forward pass, we do not differentiate the randomness itself. We need to differentiate how the model’s parameters influence the distribution of possible outcomes. For a Gaussian sample,
sampling appears to interrupt the path from the loss back to and . The reparameterization trick rewrites the same sample as
The randomness now lives entirely in . During backpropagation, is held fixed, making an ordinary differentiable function of and . The model can learn how shifting or stretching its distribution would have changed the loss. This is used in VAEs and other models with continuous latent variables.
Discrete samples, such as choosing a word or an action, cannot change smoothly. Methods such as REINFORCE instead use the result as feedback: increase the probability of choices that performed better than expected and decrease the probability of choices that performed worse. This works, but usually produces noisier gradients.
The general strategy is: separate the random noise from the learnable transformation whenever possible; when that is impossible, learn by adjusting the probability of sampled outcomes.
Reading ML Math Like Code
Dense math becomes much less intimidating when you stop trying to read it like prose and start reading it like code.
Shapes are types
It can be helpful to think of a Math variable’s type like a tensor’s shape in code. It tells you which operations are legal and often reveals what the equation means. A scalar such as a learning rate is one number. A vector is a list of numbers. A matrix maps a -dimensional vector to an -dimensional one. Even in Math it can be helpful if we think of the axis names carry meaning and standard broadcasting rules still apply. Tensors can only be added when their shapes match or when a smaller tensor is deliberately broadcast across a missing axis.
The common machine learning operations
A few symbols account for a huge fraction of ML papers, and often you can think of them as control flow:
- means loop over and accumulate.
- means draw from , evaluate , and average in practice, usually a dataset or minibatch mean.
- returns the input that makes the loss smallest, not the minimum loss value itself.
- means the two sides have the same shape but differ by a constant normalization factor.
- A subscript such as says that the function’s behavior depends on the parameters .
- means sample from the probability distribution .
- means compute the gradient of loss with respect to parameters ie the vector of partial derivatives that backprop produces.
- means replace with its updated value. The arrow means assignment, not mathematical equality.
- means elementwise multiplication: multiply corresponding entries. This differs from the dot product and matrix multiplication .
Read from the inside out
Finally, execute nested notation from the inside out. For
first compute the model probability of the observed target, then take its negative log, average that loss over data, and finally find the parameters that minimize the average. Math notation sure is compact.
Worked example: Attention
The transformer paper wrote the scaled dot-product attention as one nested expression:
B = examples in the batch
T = token positions in each example
d = features stored at each token position
Suppose and . Translate the equation from the inside out, assigning each intermediate result a name:
scores = Q @ K.transpose(-2, -1) # [B, T, T]
scaled = scores / sqrt(d_k) # [B, T, T]
weights = softmax(scaled, dim=-1) # [B, T, T]
output = weights @ V # [B, T, d_v]
contracts the feature dimension, leaving two token dimensions: one query token against every key token. That is why scores has shape . Softmax turns each query token’s row into weights over the key tokens. The final multiplication contracts that key-token dimension with , producing one weighted mixture of value features for every query token.
Annoyingly, mathematical expressions often suppress implementation details, so translating them into code requires information from the surrounding text and conventions. Here, the scores have shape . Attention requires each query token to produce a distribution over key tokens, so softmax must normalize the final, key-token dimension: dim=-1.