Addaly is in open beta. Things will change, and AI answers can be wrong — check anything that matters.

The Maths You Actually Need

Eight ideas that carry almost all the weight in machine learning.

The Maths You Actually Need

Eight ideas that carry almost all the weight in machine learning.

Level
Some background helps
Lessons
76
Reading time
676 min
Price
Free, no sign-up to read

Most people who avoid machine learning maths were failed by a teacher, not by their own brain. This course teaches the genuine minimum: vectors, dot products, matrices, derivatives, probability, distributions, expectation, and logarithms. Every lesson connects to something a real model does — an attention score, a training step, a loss curve. No proofs, no exercises with the answers in the back, no pretending a definition is an explanation.

Start the first lesson

Download the textbook (PDF) · free to print and teach from, with the exam paper and every answer at the back.

Module 1

9 lessons · 76 min

Vectors, and the space they live in

How a photo, a word, a date and a category all become lists of numbers, and how you measure agreement and distance between them once they are.

By the end you can

Turn a real piece of data into a vector and defend the choices made, compute a length, a distance, a projection and a cosine by hand, and explain using the 1/√d rule why a similarity threshold that works in a 3-dimensional picture is meaningless in a 768-dimensional embedding space

  1. 1Everything a model sees is numbers9 minA model never sees your data, only the numbers you chose to represent it with, and information discarded in that step cannot be recovered by any amount of model capacity.
  2. 2A vector is just a list7 minA vector is an ordered list of numbers, and in a model its direction carries the meaning, not its length.
  3. 3What a dot product measures7 minA dot product scores how much two lists agree, but it also grows with their length, so normalise before you compare.
  4. 4How long, and how far8 minA norm turns a whole vector into one number measuring size, and which norm you pick decides whether outliers dominate your answer or barely register.
  5. 5Cosine or distance, and why it often does not matter9 minFor unit-length vectors, cosine similarity and Euclidean distance are two readings of the same quantity and rank results identically, so the choice only matters when lengths differ.
  6. 6Projection, and the art of removing a direction9 minProjection splits a vector into the part that lies along a chosen direction and the part that does not, which is how you both read a feature out and attempt to strip one away.
  7. 7The same vector, written two different ways8 minA vector's numbers depend on the axes you chose to describe it with, which is why an individual dimension of an embedding usually means nothing on its own.
  8. 8Why your 3-D intuition is wrong in 768 dimensions10 minIn high dimensions random vectors are nearly perpendicular and all distances converge, so any similarity threshold has to be measured for your actual model rather than reasoned about from a picture.
  9. 9Sparse and dense, and the memory each costs9 minSparse representations record which items are present and dense ones record what they are like, and the arithmetic of storing each explains why serious search systems use both.
Case studySix hundred circulars and a scheme code nobody could findA district co-operative bank in Kolhapur, forty branches, building a search over its own loan circulars for the officers at the counter.Read it

The bank had six hundred circulars going back eleven years. Every one of them told a loan officer what a scheme allowed, what it required and when it changed. They lived in a shared folder, named by date, and finding the right one took a phone call to head office. In the sowing season that call took two days.

Two people in the IT cell built a search. They split the circulars into about seven thousand passages, embedded each with a free 384-dimensional model that runs on a laptop, and stored the vectors. The arithmetic said the scale was never going to be the problem: seven thousand passages at 384 numbers of four bytes each is eleven megabytes, and a brute-force comparison against all of them takes under a millisecond. Nothing here needed a vector database, a server, or a subscription.

The first version worked well on questions and badly on facts. "What is the margin requirement for a dairy loan?" returned the right passage. "KCC-2019/07" returned nothing useful at all. The embedding model had never seen that string as a token, so it had no row to look up and no direction to point in; the circular that carried the code was ranked forty-first.

They also found their threshold was meaningless. They had copied a rule from a tutorial: accept a match above cosine 0.8. On their model almost nothing scored above 0.8, and the search returned an empty list for most queries. So they labelled two hundred query-passage pairs by hand, matching and not matching, and plotted the scores. Unrelated pairs averaged 0.61. Matching pairs averaged 0.78. The whole signal lived in a band about fifteen points wide, sitting well above zero, because the model pushed all its vectors into a narrow cone. The right cut-off for their model and their documents was 0.71, and it could not have been guessed.

That left the real decision. The dense search alone would ship in a week. It would answer questions about schemes and it would fail, quietly and confidently, on scheme codes, account formats, circular numbers and the surnames of the officers who signed them. A hybrid search, running a BM25 index alongside the embeddings and merging the two rankings by position, would take about three more weeks: building the index was an afternoon, but the merge, the evaluation set and the retraining of forty branch managers were not.

The cost of waiting was concrete. The sowing season started in six weeks and the counter queues would double. Every week without search was another week of two-day phone calls, and the branch managers had been promised something before the season, not after it.

The cost of shipping the dense version alone was harder to see and worse. A loan officer who searches a scheme code, gets a confident-looking passage from a superseded 2017 circular, and quotes it at the counter has been actively misled by the tool. Nothing in the interface would say the code had not matched; the score would look ordinary. The IT cell had seen that failure in testing and could not think of a way to warn a user about it, because a dense model does not know that it has never seen a token.

They put both options to the general manager with the numbers attached: eleven megabytes, one millisecond, a measured threshold of 0.71, and a list of twelve real queries from the branches on which the dense search returned the wrong circular.

What actually happened

The general manager took the three-week delay. The team shipped hybrid search two weeks before the season, running BM25 and the embeddings together and merging by rank position rather than by score, because the two scores were on scales that could not be compared. The threshold went in as 0.71, with a note in the code saying it had been measured on two hundred labelled pairs against that specific model and had to be re-measured if the model ever changed. On the twelve failing queries, hybrid search returned the right circular for eleven; the twelfth was a code that had been typed wrongly in the original document. The team also added a line to the results page saying which half of the system had found each result, which turned out to be the feature the branch managers mentioned most.

Worth arguing about

  1. The dense search could not find "KCC-2019/07". Why does adding a keyword index fix that when a better embedding model would not?

    One answer

    A dense model represents a string only if its tokeniser produced tokens it has learned rows for. A rare code is split into fragments the model has almost no signal about, so its direction in the space is close to noise, and no amount of model quality changes that for a string it has never usefully seen. A sparse index does not represent the code at all; it matches it. The two systems fail in complementary ways, which is the whole argument for running both.

  2. Why was a threshold of 0.8, copied from a tutorial, the wrong number here, and what would make 0.71 wrong too?

    One answer

    Cosine scores are a property of one model's output distribution, not of meaning. This model was anisotropic: it packed its vectors into a narrow cone, so even unrelated passages averaged 0.61 and the useful signal sat in a band above that. A threshold has to be read off a labelled sample from the actual model. The 0.71 would become wrong the moment they changed embedding model, or re-chunked the documents, since both change the distribution the number was read from.

  3. The team merged the two rankings by position rather than by score. What goes wrong if you add a BM25 score to a cosine?

    One answer

    The two numbers are on incompatible scales. A cosine is bounded between minus one and one and, on this model, clustered around 0.6; a BM25 score is unbounded and depends on corpus statistics and document length. Adding or averaging them lets whichever happens to have the larger numbers dominate the ranking for reasons unrelated to relevance. Merging by rank position discards the magnitudes and keeps only the ordering each system is entitled to assert.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    A first search system ranks documents by the raw dot product between the query vector and each document vector, with no normalisation anywhere. Long pages keep coming top. What is the mechanism?

  2. 2

    A team moves from a 384-dimensional embedding model to a 1,536-dimensional one and keeps its cosine threshold of 0.35. What does the one-over-root-d rule say about that threshold?

  3. 3

    Two error vectors over four items: A is (10, 0, 0, 0) and B is (3, 3, 3, 3). Which norm calls A the larger, and why does the answer matter for a loss function?

  4. 4

    A team finds a direction in embedding space that encodes an unwanted attribute and projects every vector onto the space perpendicular to it. A classifier trained on the result still predicts the attribute well above chance. What went wrong?

  5. 5

    Why can you not average a 768-number embedding from one model with a 768-number embedding from another model trained with a different seed?

  6. 6

    A support search must handle both the sentence "my order has not arrived" and the order code AX-99182. Why does a dense embedding model handle the first and fail the second?

Module 2

9 lessons · 79 min

Matrices, and what a layer really does

Multiplying by hand, predicting shapes, and the three factorisations — rank, eigenvectors, singular values — that explain why a huge weight matrix can often be replaced by two small ones.

By the end you can

Multiply two matrices by hand and predict the output shape of any chain of layers, explain what the rank of a weight matrix costs and buys, and use singular values to justify replacing a 4096x4096 matrix with two thin ones and to state what that replacement gives up

  1. 10Doing a matrix multiplication yourself, once8 minEvery entry of a matrix product is one dot product between a row of the left matrix and a column of the right, which is why the inner dimensions must match and why order cannot be swapped.
  2. 11A matrix is a stack of questions8 minA matrix is a stack of questions, each row a dot product; without a bend between them, stacked layers collapse into one.
  3. 12Shapes, batches, and the broadcasting rules9 minBroadcasting silently stretches a dimension of size one to match its neighbour, which makes concise code possible and makes a whole family of bugs run without complaint.
  4. 13Undoing a matrix, and why you rarely should9 minThe inverse exists only when a matrix loses no information, and even then solving a system directly is faster and far more numerically stable than forming the inverse.
  5. 14The determinant, and what it says about collapse8 minThe determinant is the factor by which a transformation multiplies volume, so a determinant of zero means dimensions were flattened away and nothing downstream can restore them.
  6. 15The best fit, and what "best" was defined to mean9 minLeast squares finds the point in the space your model can reach that is closest to the data, and it does so by making the residual perpendicular to everything the model can represent.
  7. 16Rank, and why a huge matrix can be two small ones9 minRank counts the genuinely independent directions in a matrix, and when it is far below the matrix's size the matrix can be factored into two thin ones at a fraction of the parameters.
  8. 17The directions a matrix does not turn9 minAn eigenvector is a direction a matrix only stretches rather than rotates, and the largest eigenvalue governs what happens when the matrix is applied over and over.
  9. 18Singular values, and the honest measure of importance10 minEvery matrix without exception factors into a rotation, a set of axis stretches, and another rotation, and the sizes of those stretches tell you exactly how much you lose by throwing each one away.
Case studyRank eight, and the week it nearly costA two-person company in Pune adapting an open 1.3-billion-parameter translation model to Marathi legal notices, on one 16 GB graphics card.Read it

The product was narrow and useful: municipal notices, tenancy orders and consumer-court summonses translated from English into Marathi in a register that lawyers would accept. A general model got the words right and the register wrong, rendering "the respondent is hereby directed" into everyday Marathi that read like a text message. Their customers were law clerks, and to a law clerk that is a wrong translation.

They had 9,400 aligned pairs, collected over a year, and one graphics card with 16 GB of memory.

The first question was whether they could train at all. The base model has 1.3 billion parameters. Full fine-tuning holds about sixteen bytes per parameter once the optimiser's two moments and the float32 master copy are counted, which is 20.8 GB before a single activation is stored. Their card could not hold it. Renting two data-centre cards for thirty hours would cost roughly what they spent on rent in a month, and would have to be repeated every time they changed anything.

The alternative was a low-rank adapter. Freeze the base model at two bytes a parameter, 2.6 GB, and train only two thin matrices inserted at each attention projection. At rank 8 across twenty-four layers and four projections of width 2,048, that is about 3.1 million trainable parameters: a quarter of one per cent of the model. Sixteen bytes applies only to those. The whole run fits with room to spare, and takes four hours rather than thirty.

Before committing they ran one check that took ten minutes. They took the singular values of a query projection matrix from the middle of the model and looked at where the squared magnitude accumulated. Ninety per cent of it sat in the first 180 of 2,048 directions. That did not prove a rank-8 adapter would work — the singular values describe the weights, not the change the task needs — but it told them the matrices were nowhere near using their full width, which made the low-rank story plausible enough to try first.

The rank-8 adapter trained cleanly and the result was disappointing. Everyday sentences improved. The legal register did not: "hereby directed" still came out casual, and a set of twenty fixed formulae that appear in almost every notice were translated inconsistently, sometimes correctly and sometimes not, within the same document.

Here the decision had a cost on both sides, and it is the decision the module exists to prepare you for. The obvious hypothesis, and the one both of them wanted to believe, was that the learning rate was wrong. Adapters start from zero and need a larger rate than a full fine-tune; theirs might have been too small. Testing that meant a sweep, which meant a day, and if it was right they would have saved the memory.

The other hypothesis was less comfortable: that the change the task required simply was not rank 8. Legal register is not a small correction to general translation; it is a systematic shift in word choice across the whole vocabulary. Raising the rank to 64 costs eight times the adapter parameters, which is still only 25 million and still fits, and costs one more four-hour run.

One of them wanted the sweep, because a smaller adapter would keep their deployment cheap. The other wanted the rank raised, because the failure looked systematic rather than under-trained: everyday sentences had improved, which is not what an under-trained model does.

What actually happened

They raised the rank to 64 and kept the learning rate. The four-hour run fixed the register: the twenty fixed formulae came out consistently, and the everyday sentences held their earlier gains. They then went back and did the learning-rate sweep anyway, at rank 64, and found their original rate had been within a factor of two of the best one — so the day they did not spend on it would have been a day spent confirming that nothing was wrong. The deployed adapter is 50 MB against a 2.6 GB base, and they ship one adapter per customer segment. Their note in the repository reads: when a low-rank fine-tune underperforms, raise the rank before you tune anything, because raising the rank answers the question directly and tuning only ever tells you that tuning was not the problem.

Worth arguing about

  1. Why did full fine-tuning need 20.8 GB when the model itself is only 2.6 GB in half precision?

    One answer

    Training holds far more than the weights. In the usual mixed-precision recipe with Adam it is about sixteen bytes per parameter: two for the half-precision working weights, four for the float32 master copy, two for the gradient, and four each for Adam's two moment estimates. Twelve of those sixteen bytes are optimiser and master state, which exist only for parameters you are training. That is exactly why freezing the base and training a small adapter collapses the figure: the sixteen bytes then apply to a quarter of one per cent of the model.

  2. The singular-value check showed 90 per cent of the energy in 180 of 2,048 directions. Why was that not enough to justify rank 8?

    One answer

    The singular values describe the existing weight matrix, not the update the task needs. A matrix can be highly redundant while the change required to move it to a new register is spread across many directions. The check ruled out the worst case, a matrix already using its full width, and made the attempt reasonable. Only running it, and then running it at a higher rank, answered the actual question.

  3. Everyday sentences improved while the legal register did not. Why does that pattern point at rank rather than at the learning rate?

    One answer

    An under-trained model, which is what too small a learning rate produces, improves little at everything. Here one kind of change took and another did not, which is the signature of a capacity limit rather than of insufficient optimisation: the adapter could represent the easy correction and could not represent the systematic one. That reading is a hypothesis, not a proof, but it is cheap to test, since raising the rank and rerunning costs one afternoon and settles it.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    A network stacks a hundred linear layers with no activation function between them. What can it compute that a single linear layer cannot?

  2. 2

    Predictions have shape (4,) and targets have shape (4, 1). The code subtracts one from the other and takes the mean. What happens?

  3. 3

    A layer's square weight matrix has determinant zero. What follows for everything downstream of that layer?

  4. 4

    Replacing a 4096 by 4096 weight matrix with two matrices of shapes 4096 by 8 and 8 by 4096 cuts the parameters 256-fold. What does the replacement give up?

  5. 5

    Before compressing a layer you find that 90 per cent of the squared magnitude of its weight matrix needs the first 620 of its 768 singular values. What should you conclude?

  6. 6

    Least squares chooses the coefficients that make the residual perpendicular to every column of X. What does that geometric condition express?

Module 3

9 lessons · 80 min

Change, slopes and the walk downhill

Derivatives from first principles, the chain rule, backpropagation as bookkeeping, and how to read a loss curve for whether the problem is the learning rate, the curvature or the gradient itself.

By the end you can

Compute a partial derivative and a chain-rule derivative by hand, trace a gradient backwards through a two-layer network and say where the memory goes, and diagnose from a loss curve and a gradient-norm plot whether the learning rate, the curvature or a vanishing gradient is the cause

  1. 19Slope, before anyone says the word derivative8 minA derivative is the slope between two points as you shrink the gap between them, and you can compute a usable one with two evaluations and a small number.
  2. 20Slopes, and why training is walking downhill9 minA derivative says how the loss moves when you nudge one number; training just steps against it, over and over.
  3. 21Many knobs, one derivative each8 minA partial derivative is the slope in one variable with all others frozen, and the gradient collects them into a vector that points in the direction of steepest increase.
  4. 22The chain rule, which is the whole trick8 minWhen functions are nested, their rates of change multiply, which is why a network of many layers is differentiable at all and why signals can shrink or blow up as they pass back.
  5. 23Backpropagation, and where the memory goes10 minBackpropagation computes every gradient in one backward sweep by reusing stored forward values, which is why training memory is dominated by activations rather than by weights.
  6. 24Convexity, and why nobody promises anything about deep networks9 minA convex problem has one minimum that gradient descent is guaranteed to find, deep networks are not convex, and what saves them in practice is that most flat points in high dimensions are saddles rather than traps.
  7. 25Curvature, and what the optimisers are actually doing10 minThe ratio between the steepest and shallowest curvature decides how badly plain gradient descent zigzags, and momentum and Adam are two cheap ways of compensating without ever computing that curvature.
  8. 26Reading a training failure from the numbers9 minAlmost every training failure announces itself in the gradient norm, the activation statistics or the loss curve before it announces itself as a bad model, and each pattern has a specific mechanism behind it.
  9. 27The one hyperparameter worth your afternoon9 minThe learning rate is bounded above by the sharpest curvature and below by your patience, and a single sweep across a few orders of magnitude locates the usable band faster than any amount of guessing.
Case studyTwenty minutes of a shared GPU nightAn agricultural university in Ludhiana, a research assistant training a wheat-disease classifier from 11,000 photographs taken on farmers' phones.Read it

The department had one graphics card and six research students. The rota gave each of them one night a week, ten hours, from eight in the evening. Miss the slot and the next one is seven days away, which in a project with a June deadline is a real loss.

The assistant had 11,000 photographs across seven categories — yellow rust, brown rust, loose smut, karnal bunt, aphid damage, nitrogen deficiency, and healthy — collected by extension officers over two seasons. The plan for the night was to fine-tune an image model that had already been pre-trained on general photographs.

The first attempt died in forty steps. The loss fell from 1.94 to 1.6, then printed as NaN and stayed there. The learning rate was 3e-4, taken from a widely shared post about training transformers.

He restarted with the rate at 1e-4. The loss went to NaN in about ninety steps. He restarted at 5e-5, and it survived, and after two hours the loss was 1.71 and falling so slowly that it would clearly not reach anything useful by morning.

At that point three hours of a ten-hour slot were gone and the decision arrived. He could start a full run at 5e-5 and let it go overnight, and have something to show his supervisor in the morning even if it was poor. Or he could spend twenty minutes on a learning-rate range test — start absurdly low, multiply the rate by 1.1 after each of two hundred steps, and record the loss — which would leave under seven hours for the run and might still produce nothing.

His supervisor's meeting was at eleven the next morning. A run that finished and was mediocre could be discussed. A slot spent on diagnostics with no model at the end could not, and the next slot was a week away.

He also had two numbers he had not looked at. He had never logged the gradient norm, so he could not tell whether the NaN was an explosion or an overflow somewhere in the forward pass. And he had not counted dead units, so he did not know what the two failed runs had done to the network before he restarted them.

He spent five minutes adding both. The gradient norm at 3e-4 rose from 2.1 to 340 over the forty steps before the NaN, which is an explosion and not an overflow. And when he loaded the checkpoint from the failed run and counted, 41 per cent of the units in the third block were producing zero for every image in a batch: a large early step had pushed their inputs negative for the whole dataset, and a unit in that state has no gradient and never comes back.

That second number changed the argument. It meant the run at 5e-5, started from a model already damaged in the first minutes, was not a slow model but a smaller one than its parameter count suggested. Continuing it overnight would produce a number that told him nothing about his data.

What actually happened

He ran the range test. It took eighteen minutes and showed the loss falling steepest around 5e-5 and rising sharply past 3e-4, which put the usable band an order of magnitude below where he had started; he chose 2e-5, with five hundred steps of warmup so that the first steps could not kill units before the optimiser's estimates had settled. He also added gradient clipping at norm 1.0. The overnight run finished at a validation accuracy of 0.86 on a held-out set of 1,400 photographs, against 0.31 for always predicting the commonest class. He kept the gradient-norm plot in his thesis appendix. His note to the other five students, pinned above the machine, was two lines: log the gradient norm from the first run, and the learning rate a blog post gives you is for training from scratch, not for fine-tuning, which wants ten to a hundred times less.

Worth arguing about

  1. The gradient norm rose to 340 before the loss became NaN. Why does that distinguish an exploding gradient from an overflow in the forward pass?

    One answer

    An overflow in the forward pass, such as an exp of a large number or a log of zero, produces a non-finite loss directly, and the gradient computed from it is non-finite immediately rather than large and growing. A rising norm over dozens of steps is the chain-rule product of factors above one compounding as the optimiser takes steps that are too large for the local curvature. The two have different fixes: clipping and a lower rate for the first, a numerically stable formulation for the second.

  2. Why does a large learning rate early in training kill ReLU units permanently, and why does warmup help?

    One answer

    A ReLU unit whose input is negative for every example in the data outputs zero always, so its gradient is zero always, and no later step can revive it. One large step can push a whole block of units into that state at once. Warmup keeps the first steps small while the optimiser's estimates are still built from very few samples, so no single early step is large enough to do it.

  3. He had a working configuration at 5e-5 and threw away three hours of the slot to test something else. Was that defensible?

    One answer

    Yes, because the surviving run was starting from a network with 41 per cent of one block dead, so its overnight result would have measured a damaged model rather than his data. A number produced by a run you know to be compromised is worse than no number, since it invites a week of conclusions about the dataset. The range test cost eighteen minutes against a slot of ten hours and told him where the usable band was, which no amount of restarting at guessed values would have done.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    A 40-layer network uses sigmoid activations, whose derivative peaks at 0.25. Why do the earliest layers stop learning?

  2. 2

    Training a model needs far more memory than running it, even at a batch size of one. Why?

  3. 3

    The loss is a flat line from step one and the gradient norm is exactly zero. Which explanation fits?

  4. 4

    Why does gradient descent on a million-parameter network get stuck far less often than a two-dimensional picture suggests?

  5. 5

    Momentum with a factor of 0.9 speeds up descent in a long, narrow valley. What does the running average do to the two directions?

  6. 6

    A range test shows the loss falling steepest around 3e-4 and rising sharply past 3e-3. Which rate should you take, and why not the bottom of the curve?

Module 4

11 lessons · 95 min

Probability you can rely on

Counting, conditioning, Bayes with real base rates, the distributions that describe real processes, and the specific ways an average misleads when the tail is heavy.

By the end you can

Compute a posterior probability from a base rate and a classifier's error rates and explain why a 95%-accurate filter can still be wrong most times it fires, choose a distribution that matches a stated generating process, and predict from the shape of a tail when a mean is the wrong summary

  1. 28Counting, and the size of the spaces involved8 minProbability is counting favourable cases over possible ones, and in language and search the possible ones outnumber anything that could ever be enumerated.
  2. 29Probability is a degree of belief7 minA probability states a degree of belief; you judge it by calibration across many cases, never by one outcome.
  3. 30Probability once you know something8 minConditioning shrinks the space of possibilities to the cases consistent with what you know, and forgetting to shrink the right one is the source of most probability errors.
  4. 31Bayes, done slowly, with real numbers10 minBayes converts a detector's error rates into the probability that a fired alarm is real, and when the thing being detected is rare, most alarms are false however good the detector is.
  5. 32Correlation, dependence, and the gap between them9 minCorrelation measures straight-line association only, so a correlation of zero can sit on top of a perfect relationship, and a strong correlation can sit on top of no relationship at all.
  6. 33When you cannot solve it, simulate it9 minAny probability you can describe as a procedure can be estimated by running the procedure many times, and the error of that estimate falls with the square root of the number of runs.
  7. 34Distributions, and why the normal one keeps showing up8 minThe normal shape comes from many small independent effects adding up, and most real quantities are not built that way.
  8. 35Six distributions, and the process each one describes10 minEach standard distribution corresponds to a specific generating story, so choosing one is a claim about how your data was produced rather than a matter of which curve fits best.
  9. 36Expectation and variance in plain terms8 minAn expectation is a weighted average that may never occur, and its noise falls with the square root of the sample size.
  10. 37Covariance, and the shape of a cloud of points9 minA covariance matrix describes the shape and orientation of a cloud of data, and its eigenvectors are the directions along which that cloud is longest.
  11. 38Heavy tails, and the average that describes nobody9 minWhen a distribution has a heavy tail the mean is dragged by rare extremes and describes almost no one, so percentiles rather than averages are what you report and act on.
Case studyOne thousand seven hundred flags and two radiographersA municipal screening campaign in Nashik, twenty thousand chest X-rays over ten days, and a vendor's automated triage tool.Read it

The campaign was planned around a mobile van, three technicians and two radiographers. Twenty thousand people would be screened in ten working days. Every image the tool flagged would be read by a radiographer before anybody was contacted.

The vendor's numbers were good and honestly stated. The tool flags 96 per cent of the images a radiologist would call abnormal, and it wrongly flags 8 per cent of the images a radiologist would call normal. Those figures came from a study of thirty thousand images and there was no reason to doubt them.

The health officer running the campaign did the arithmetic before the contract was signed, and she did it by counting a population rather than by using a formula.

In the group being screened, the expected rate of abnormal images was about 0.8 per cent. Out of twenty thousand people that is 160 abnormal images and 19,840 normal ones. The tool would flag 154 of the 160 and miss 6. It would also flag 8 per cent of 19,840, which is 1,587. Total flags: 1,741. Of those, 154 are real. Precision is 8.8 per cent.

Two radiographers reading forty confirmatory images a day each can get through eighty a day, or eight hundred over the campaign. Seventeen hundred flags is twenty-two days of reading for a ten-day campaign. The plan did not fit, and nothing about the vendor's numbers was wrong; the base rate did that.

There were three ways out and each cost something.

Raise the threshold. Tuning the tool so that it wrongly flags 3 per cent rather than 8 brings false alarms down to 595. Recall falls too, to about 88 per cent, so the tool now flags 141 of the 160 and misses 19. Total flags 736, precision 19 per cent, nine days of reading. The plan fits. Thirteen more people are missed by the tool than before.

Add readers. Two more radiographers for ten days would clear seventeen hundred flags. There were not two more radiographers in the district who could be released for ten days, and hiring from outside had a cost the campaign budget did not carry.

Screen fewer people, more selectively. Restricting the campaign to wards with a higher prior rate would raise the base rate and therefore the precision, because precision depends on the ratio of the two groups. Doubling the rate to 1.6 per cent takes precision from 8.8 to about 16 per cent for the same tool. It also means not screening the people who were excluded.

A fourth option was raised and rejected quickly: contact people directly on a flag, with a radiographer reading only the ones who came in. At 8.8 per cent precision that meant telling roughly sixteen hundred people that an automated system had found something in their chest X-ray when it had not. The officer would not do it, and the arithmetic is why: a flag at that precision is a reason to look, not a finding, and an interface or a phone script that presents it as a finding is wrong nine times in ten.

The last complication was that the 0.8 per cent was itself an estimate, taken from the previous year's campaign in a neighbouring district. She ran the numbers again at 0.5 and at 1.5 per cent. At 0.5 the precision falls to 5.7 and the flag count rises; at 1.5 it rises to 15.5. The decision came out the same across that range, which is the useful thing to know about a prior you are not sure of.

What actually happened

She took the threshold change and wrote the reasoning into the campaign order, in the form of a table: the tool at the higher threshold is expected to flag about 736 images, of which about 141 are real and 595 are not, and to miss about 19. The order also required that the count of flags be checked against 736 at the end of day two, because if the real base rate was far from 0.8 per cent the plan would need to change while there was still time. On day two the count came to 71 flags against an expected 74, so the plan held. Two of the nineteen expected misses were later found by the routine referrals that ran alongside the campaign, which is roughly what the campaign's designers had assumed such referrals would catch.

Worth arguing about

  1. The vendor's tool catches 96 per cent of abnormal images. Why is only 8.8 per cent of what it flags actually abnormal?

    One answer

    Because the two error rates act on groups of wildly different sizes. There are 160 abnormal images and 19,840 normal ones. A 96 per cent catch rate on the small group gives 154 true flags; an 8 per cent error rate on the large group gives 1,587 false ones. The 8 per cent is applied to a group 124 times larger, so it dominates the total. The catch rate and the precision answer different questions, and the one you act on is the second.

  2. Improving recall from 96 to 99 per cent would help less than halving the false-positive rate. Why?

    One answer

    Recall acts only on the 160 abnormal images: going from 96 to 99 per cent adds five true flags. Halving the false-positive rate from 8 to 4 per cent removes 794 false ones. The denominator of precision is dominated by the false alarms, so the lever that moves precision is the error rate on the large group. This is the general shape of every rare-event deployment, and it is why the false-positive rate is usually the number worth optimising.

  3. She recomputed everything at base rates of 0.5 and 1.5 per cent. What did that test tell her that the single number could not?

    One answer

    It tested whether the decision was robust to the prior she was least sure of. The precision figure moved from 5.7 to 15.5 per cent across that range, which is a large relative change, but the conclusion — that seventeen hundred flags will not fit two radiographers and ten days — held throughout. When a decision is the same across the plausible range of a prior, the prior's uncertainty does not need resolving. When it is not, that is the number to go and measure.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    A detector catches 95 per cent of fraud and wrongly flags 1 per cent of legitimate transactions. Fraud is 0.1 per cent of all transactions. Roughly what share of its flags are real?

  2. 2

    A feature-selection step drops every feature whose Pearson correlation with the target is near zero. Which real relationship does it throw away?

  3. 3

    You model support tickets per hour as Poisson. The sample mean is 12 and the sample variance is 71. What does that tell you?

  4. 4

    A backend call exceeds 400 ms one time in a hundred. A page makes twenty such calls and the user waits for the slowest. How often is the page slow?

  5. 5

    Going from batch size 32 to batch size 128 costs four times the compute per step. By how much does the gradient noise fall?

  6. 6

    A vendor reports that its model flags 95 per cent of fraudulent transactions. Which quantity is that, and which do you need?

Module 5

10 lessons · 90 min

Logarithms, information and the shape of a loss

Logs and exponentials as tools rather than tables, surprise measured in bits, entropy and cross-entropy computed by hand, why a loss function is a likelihood in disguise, and the softmax arithmetic that every classifier ends with.

By the end you can

Compute a cross-entropy and a KL divergence by hand from two small distributions and say which part of a training loss is irreducible, derive the squared-error and cross-entropy losses from a stated noise assumption, compute a softmax and its gradient for a given set of logits, and explain by the overflow limit of float32 why every library subtracts the maximum before exponentiating

  1. 39What a log is, and why the axis got logged8 minA logarithm counts how many multiplications reach a number, which turns products into sums and equal ratios into equal spacings, and that is why probabilities are added in log space and why any axis spanning several orders of magnitude should be logged.
  2. 40Exponentials, decay, and the memory of a moving average9 minAn exponential moving average with factor β remembers roughly 1/(1−β) steps and weights the past geometrically, which is where Adam's 0.9 and 0.999 come from, why it needs a bias correction at the start, and why a smoothed loss curve shows a spike late and small.
  3. 41Logs, and why losses are logged8 minLogs turn products into sums and make confident mistakes expensive, which is exactly what training needs.
  4. 42Surprise, bits, and why prediction is compression9 minThe surprise of an outcome is −log p, additive across independent events and zero for certainty, and because any distribution can be turned into a code of that length, a model's loss in bits per token is literally the size it would compress the text to.
  5. 43Entropy: the average surprise, computed by hand9 minEntropy is the average surprise of a distribution, largest when outcomes are equally likely and zero when one is certain, and the entropy of your label column is the loss of a model that has learned nothing but the base rate, which is the first number to compute.
  6. 44Cross-entropy and KL: the cost of believing the wrong distribution10 minCross-entropy is entropy plus KL divergence, so minimising it against fixed data can only shrink the KL and never go below the data's own entropy, which is why a loss plateau above zero can be the floor rather than a failure.
  7. 45Loss functions are not arbitrary: maximum likelihood10 minEvery standard loss is minus the log-likelihood under a stated noise assumption, so squared error means Gaussian errors of constant variance, absolute error means Laplace, cross-entropy means Bernoulli or categorical, and a loss that fits badly is a noise assumption that was wrong.
  8. 46Softmax, its gradient, and the shift it cannot see9 minSoftmax exponentiates and normalises, so only logit differences matter and a shared shift is invisible, and with cross-entropy its gradient is simply probability minus target, which is why training pushes hard on confident mistakes and barely at all on what is already right.
  9. 47The log-sum-exp trick, and why exp(1000) is not a number9 minBecause float32 overflows at exp(88.7), softmax is computed by subtracting the maximum logit first, and log-probabilities are computed as z minus log-sum-exp rather than as the log of a softmax, which is why a loss function takes raw logits and why passing it probabilities trains toward a ceiling.
  10. 48Power laws, and the straight line on a log-log plot9 minA power law is a straight line on log-log axes whose slope is the exponent, so a slope of −0.5 means quadrupling the input halves the output, and a straight line over two decades is weak evidence for extrapolating that promise further.
Case studyA loss of 2.34, and the floor nobody had computedAn electronics retailer in Hyderabad training a classifier to route customer support tickets into eleven categories, with a board demonstration on Friday.Read it

The support team handled about four hundred tickets a day in a mixture of English, Hindi and Telugu, and routed them by hand into eleven queues. Routing took roughly three people-hours a day, and the point of the model was to give those three hours back.

An engineer trained a classifier on 38,000 labelled tickets from the previous eighteen months. It trained without any error. The loss fell from 2.44 to 2.34 over the first epoch and then sat there for four more, moving in the third decimal place. Accuracy on a held-out set was 34 per cent.

Thirty-four per cent across eleven categories sounds like learning. Eleven categories at random would be nine per cent, and the model was nearly four times that, so the team's reading was that the model had learned something real and needed more data or a bigger architecture. The plan agreed on Tuesday was to label another twenty thousand tickets, which would take the support team about three weeks of evenings.

One person asked what the loss would be for a model that had learned nothing at all, and computed it before the meeting ended.

The eleven categories were not balanced. Deliveries were 31 per cent of tickets, warranty claims 18, returns 12, payments 9, installation 7, missing parts 6, transit damage 5, cancellations 4, exchanges 3.5, spare parts 2.5, and everything else 2. The entropy of that distribution is the average surprise of the label column, and it came to 2.06 nats. That is the cross-entropy of a model that predicts the base rates every time and knows nothing else.

Their model's loss was 2.34. It was worse than the base rates.

The accuracy figure had hidden it, because 34 per cent looks respectable next to nine and nobody had computed the other comparison: always answering "deliveries" scores 31 per cent, and the model was three points above that.

The second number pointed at the cause. The natural log of eleven is 2.398, and 2.34 is just under it. A loss stalling immediately below the log of the number of classes is the signature of a model whose outputs have been flattened almost to uniform before they reach the loss. The engineer looked, and the training loop applied a softmax to the logits and then passed the probabilities into a cross-entropy loss that expects raw logits. The loss applied a second softmax. Probabilities all lie between zero and one, so treated as logits they differ by at most one, and a softmax over such numbers is close to flat: three classes with 0.9, 0.05 and 0.05 come out as 0.53, 0.23 and 0.23. The model was training, honestly and slowly, towards a ceiling it could not pass.

That was Wednesday. The decision was whether to fix it and retrain, or to demonstrate on Friday with the model they had.

Retraining was four hours, so time was not the constraint. The constraint was that nobody could promise what the fixed model would score, and the board had already been told a number. Showing a working demonstration with a model that routes worse than a rule saying "send everything to deliveries" was, in the engineer's phrase, a thing that would be true for exactly as long as nobody checked.

What actually happened

They removed the softmax, retrained on Wednesday night, and the loss fell to 0.71 nats by the second epoch with accuracy at 79 per cent. The demonstration went ahead on Friday with the real number and with the base-rate floor drawn on the loss plot as a horizontal line at 2.06, which the team kept in every plot afterwards. The twenty thousand extra labels were not collected. The engineer added two assertions to the training script: one that the loss function is given raw logits rather than probabilities, and one that fails the run if the first epoch's loss is above the entropy of the label column, since a model above that line has learned less than the base rates and there is no configuration in which continuing is the right response.

Worth arguing about

  1. Why is the entropy of the label column the loss of a model that has learned nothing but the base rates?

    One answer

    A model that predicts the class frequencies and nothing else assigns each outcome its base-rate probability, so its average surprise is exactly the sum of each probability times minus the log of that probability, which is the entropy. Any model whose cross-entropy is above that number is paying more per ticket than a constant predictor, which means it has learned less than the frequencies. It is a single line of arithmetic on the label column and it should be computed before training starts, not after.

  2. The loss stalled at 2.34, just under ln(11) = 2.398. Why is that particular value a fingerprint rather than a coincidence?

    One answer

    The log of the number of classes is the loss of a model that outputs a uniform distribution. A second softmax applied to probabilities compresses every output towards uniform, because probabilities differ by at most one and a softmax over differences of that size is nearly flat. The model can still improve slightly, which is why the loss sat just below the uniform value rather than exactly on it, but it can never get far from it. Whenever a classifier learns and then stalls close to ln of the class count, look for an extra softmax.

  3. Accuracy of 34 per cent against nine per cent for random guessing looked like progress. What comparison should the team have made instead?

    One answer

    Against the trivial baseline that matters, which is always predicting the commonest class: deliveries at 31 per cent. Random guessing is not the alternative anyone would deploy, so it is the wrong ceiling to be measured against. The same mistake in loss terms is comparing against the log of the class count instead of against the entropy of the actual label distribution, and on skewed labels the two differ enough to turn a failure into an apparent success.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    Why does every library subtract the largest logit before exponentiating inside softmax?

  2. 2

    A binary label is 1 in ten per cent of rows. A model reaches a cross-entropy of 0.40 nats. What should you conclude?

  3. 3

    A language model's loss plateaus at 2.1 nats and will not fall further. Which reading does the identity relating cross-entropy, entropy and KL divergence support?

  4. 4

    With softmax and cross-entropy the gradient with respect to a logit is the predicted probability minus the target. What does that shape do to training?

  5. 5

    You fit house prices with squared error and a few very large sales drag the whole fit. What does that say about the loss you chose?

  6. 6

    Adam's second moment uses a decay of 0.999. Roughly how many steps does that average remember, and why longer than the first moment's?

Module 6

9 lessons · 83 min

Estimation: from a sample to a number you can trust

What an estimator is and why the variance divides by n − 1, the mechanism behind the square-root law and the bell curve, standard errors and intervals you can compute on paper, what zero failures actually prove, the Beta distribution as a rate that learns, regularisation derived as a prior, and the selection effect that makes every winner look better than it is.

By the end you can

Compute a standard error and a confidence interval for an accuracy figure by hand, say from the sample size and base rate whether the textbook interval can be trusted, bound a failure rate from a run with zero failures, derive an L2 or L1 penalty from a stated prior on the weights, and predict how much the best of k noisy candidates will fall back when re-measured

  1. 49An estimator is a recipe, and why the variance divides by n − 19 minAn estimator is a rule from sample to number with a bias and a variance of its own, and the sample variance divides by n − 1 because distances measured from the sample's own mean are systematically too small by exactly one degree of freedom.
  2. 50The law of large numbers, and how fast it works9 minBecause variances of independent draws add, the spread of an average falls as σ/√n, which is slow, and the law stops applying when the variance is infinite or when correlated rows are counted as independent, in which case the effective n is the row count divided by 1 + (m − 1)ρ.
  3. 51Why averages look normal, and when they refuse to9 minAverages of independent draws with finite variance become normal because adding smooths and the normal is the shape smoothing leaves alone, but skew slows it, heavy tails defeat it entirely, and the theorem describes the average rather than the data.
  4. 52Standard error for a mean and a proportion, by hand9 minThe standard error of a proportion is √(p(1−p)/n), at most 0.5/√n, so 400 items give about ±5 points; independent errors combine by adding squares, while a paired comparison on shared items depends only on the items the two systems disagree about.
  5. 53What a 95 per cent interval promises, and where the textbook one breaks10 minA 95 per cent interval is a procedure that captures the truth in 95 per cent of repetitions, and the textbook estimate ± 1.96 SE breaks that promise near 0 or 1, covering only 63 per cent at p = 0.98 and n = 50, which the Wilson interval fixes by solving for the plausible true values instead.
  6. 54Zero failures in 300 tries, and what that does not prove8 minZero failures in n independent trials bounds the failure rate at roughly 3/n with 95 per cent confidence, so 300 clean runs are consistent with a one-per-cent failure rate, and observing a failure of rate p reliably needs about 3/p trials.
  7. 55Updating a rate as evidence arrives: the Beta distribution10 minA Beta(a, b) belief about a rate updates to Beta(a + k, b + m) after k successes and m failures, so the prior is just pseudo-counts that fade as data accumulate, which is why the same arithmetic gives credible intervals, click-rate smoothing and Thompson sampling.
  8. 56Regularisation is a prior: L2, L1 and the diamond10 minAdding a penalty to a loss is maximising a posterior rather than a likelihood, a Gaussian prior on the weights gives the L2 penalty and a Laplace prior gives L1, and L1 produces exact zeros because its pull stays constant as a weight shrinks while L2's pull fades with the weight.
  9. 57Regression to the mean, and the winner's curse in model selection9 minAny measurement is truth plus noise, so the best of k candidates was selected partly for lucky noise and falls back on re-measurement by an amount set by the reliability r and the count k, which is why the winner of a hyperparameter search scores lower on a fresh test set through no fault of its own.
Case studyNinety-four per cent on fifty scriptsA state board examination cell in Bhopal, deciding whether to use an automatic marker on 1.9 million Class 10 English answer scripts.Read it

The vendor's claim was specific and testable: on fifty scripts marked by both the system and a senior examiner, the two agreed on the grade 47 times. Ninety-four per cent. There were also no cases in the fifty where the system was more than one grade away from the examiner.

The examination cell had four weeks to decide. Marking 1.9 million scripts by hand takes six weeks and about eleven thousand examiner-days, and the results date is fixed by the academic calendar. The system, if it worked, would take four days and let examiners handle only the scripts it was unsure of.

An officer in the cell took the vendor's fifty-script table and did three pieces of arithmetic on it.

First, the interval. Forty-seven out of fifty is a proportion near the top of the range, where the textbook recipe of the estimate plus or minus 1.96 standard errors misbehaves. The Wilson interval, which solves for the true rates under which forty-seven of fifty would be unsurprising, gives 84 to 98 per cent. That is the honest reading of the vendor's evidence: somewhere between eighty-four and ninety-eight. At the bottom of that range, one script in six gets the wrong grade, which across 1.9 million scripts is three hundred thousand students.

Second, the zero. "No script more than one grade wrong in fifty" bounds that failure rate at roughly three divided by fifty, which is six per cent, with 95 per cent confidence. Six per cent of 1.9 million is 114,000 scripts. The zero was not evidence that the failure does not happen; it was evidence that it happens in under about one script in seventeen, which was not a reassuring sentence when written out in full.

Third, where the fifty came from. They had all been drawn from one school, marked by one examiner. Scripts from a single school share a teacher, a syllabus emphasis and a house style of answering, so they are not fifty independent observations of the system's behaviour. The officer could not compute the design effect without more data, but the direction was certain: the effective sample size was below fifty, so the true interval was wider than 84 to 98, not narrower.

There was a fourth thing, which the vendor volunteered when asked. Twelve configurations had been tried on the fifty scripts, and the one reported was the best of the twelve. The best of twelve draws from a distribution sits, on average, about one and a half standard errors above the truth, and the standard error here is about three and a half points. So the 94 was selected partly for having been lucky, and would be expected to fall back by four or five points when measured on scripts it had not been chosen on.

The decision had a cost on both sides and both were large.

A proper pilot meant drawing four thousand scripts across sixty districts, marking each twice by hand as well as by machine, and comparing. That is about eight hundred examiner-days and six weeks, and six weeks past the results date means 1.9 million students waiting, admissions calendars slipping and questions in the assembly.

Going ahead on the vendor's number meant accepting a system whose true agreement rate the cell did not know within fourteen points, evaluated on one school, tuned on the same fifty scripts it was measured on, and applied to every child in the state.

What actually happened

The cell did neither of the two options as posed. It ran the system in parallel on the whole cohort, taking no grading decision from it, and had human examiners mark as usual; the system's output was recorded but not used. That cost the four days of compute and nothing else, and it produced 1.9 million paired comparisons against human marks by the end of the normal marking cycle. Agreement on the full set came to 88.6 per cent, inside the Wilson interval and five points below the vendor's figure, in line with what the winner's curse and the single-school sample predicted. Scripts more than one grade apart were 2.1 per cent, or about forty thousand. On that evidence the cell approved the system for the following year in a narrower role: it marks first, every script it grades below a measured confidence goes to a human, and a five per cent random sample of the rest is checked regardless. The officer's note said the parallel run was not a compromise between the two options but a better third one, and that it existed because somebody wrote down what the fifty scripts could and could not support.

Worth arguing about

  1. Why does the textbook interval, the estimate plus or minus 1.96 standard errors, break down on 47 out of 50?

    One answer

    The standard error is computed from the estimate rather than from the truth, and near the boundary the estimate is a poor stand-in. At p = 0.94 and n = 50 the recipe produces an upper bound above 1, which is impossible for a proportion, and its real coverage is well below the 95 per cent it claims. The Wilson interval solves instead for the true rates under which the observation would be plausible, which keeps it inside zero to one and keeps the coverage near its promise.

  2. The vendor reported the best of twelve configurations. How much should the cell have discounted the 94?

    One answer

    The expected maximum of twelve draws sits about one and a half standard errors above the truth, and the standard error on fifty items near 0.94 is about three and a half points, so roughly five points of the 94 were selection on noise rather than quality. The full-cohort figure came in at 88.6, which is about that much lower. The general rule is that a score without the count of things it was chosen from cannot be read, and the only unbiased number comes from data nothing was selected on.

  3. Fifty scripts came from one school. Why does that make the interval wider rather than merely different?

    One answer

    Every standard error formula in this module assumes independent observations. Scripts from one school share a teacher, an emphasis and a house style, so the system's behaviour on one predicts its behaviour on the next, and the fifty carry the information of rather fewer independent cases. The effective sample size is the row count divided by one plus the correlation times one less than the cluster size, so any positive correlation shrinks it, and a smaller effective n means a wider interval than the one computed from fifty.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    Why does the sample variance divide by n minus one rather than by n?

  2. 2

    An evaluation set has 2,000 answers from 80 users, 25 each, with a within-user correlation of 0.5. What is the effective sample size?

  3. 3

    Three hundred independent test runs produced no failures at all. What can you claim?

  4. 4

    A model scores 50 out of 50 and the textbook interval comes out as 1.00 to 1.00. What is wrong with it?

  5. 5

    Why does an L1 penalty drive some weights to exactly zero while an L2 penalty never does?

  6. 6

    You try 100 hyperparameter configurations on a validation set with a one-point standard error and report the best, at 91. What should you report instead?

Module 7

9 lessons · 82 min

Counting the cost: complexity and the arithmetic of scale

Growth rates and why n² is the one to fear, counting the floating-point operations in a layer and a training run, the bytes a model needs to exist and to train, why a GPU spends most of its time waiting for memory, and the arithmetic of hashing, graphs, nearest-neighbour search and back-of-the-envelope estimation.

By the end you can

Count the FLOPs of a forward pass and a training run from a parameter count, compute the memory a model needs at each precision and in training, say from arithmetic intensity whether a workload is bound by compute or by memory bandwidth, recognise a quadratic cost in a pipeline and name the sub-quadratic replacement, and estimate the time or cost of an ML job to within a factor of three before running it

  1. 58Big-O, and the four growth rates you will meet8 minBig-O keeps only how work grows as input doubles, and the line that matters runs between n log n, which survives any dataset, and n², which stops working around a million items however fast the hardware.
  2. 59Counting the floating-point operations in a layer and a training run9 minA matrix multiply costs 2mnk FLOPs, so a forward pass costs about two FLOPs per parameter per token and a training step about six, which lets you compute that seven billion parameters on a trillion tokens is 4.2 × 10²² FLOPs before anyone tells you the price.
  3. 60Anything pairwise is quadratic: distances, attention and deduplication9 minAny computation that compares every item with every other costs n² in time and memory, which is fine at ten thousand items and impossible at a million, and the fix is always the same: sort, bucket, block or approximate so that most pairs are never formed.
  4. 61Bytes per parameter, and the arithmetic of what fits on a card9 minMemory is parameters times bytes per parameter, so a seven-billion model is 14 GB in fp16 and 3.5 GB in int4, while training the same model holds about 16 bytes per parameter plus activations that scale with batch and context, which is why fine-tuning needs adapters to fit where inference already did.
  5. 62Why a GPU idles: memory-bound versus compute-bound10 minA computation runs at the slower of its compute and bandwidth limits, and its arithmetic intensity in FLOPs per byte decides which, so single-token generation at one FLOP per byte is bandwidth-bound and takes weights ÷ bandwidth seconds regardless of how fast the chip's arithmetic is.
  6. 63Hashing, collisions, and the square-root law behind them9 minHashing gives constant-time lookup by scattering inputs evenly, and the birthday bound says a repeat is likely after only √(2m) draws from m values, which is why a 32-bit key collides by 77,000 items and why Bloom filters, the hashing trick and locality-sensitive deduplication can each be sized from one formula.
  7. 64A graph is a matrix, and its paths are its powers9 minA graph's adjacency matrix turns paths into matrix powers and random walks into repeated multiplication whose fixed point is the leading eigenvector, which is PageRank, and a graph neural network layer is simply that matrix averaging each node's neighbours before a learned linear map.
  8. 65Finding the closest vector among ten million: the arithmetic of approximate search10 minExact nearest-neighbour search costs n × d per query and n × d × 4 bytes to hold, which is fine to about a hundred thousand vectors and impossible at ten million, so every method past that shrinks the vectors, searches a fraction of them or walks a graph, and each pays for its speed in measured recall.
  9. 66Estimating anything to within a factor of three9 minBreak a question into factors you can guess to within three, multiply, and track the powers of ten; with k independent guesses the result is uncertain by about 3^√k rather than 3^k, so six rough factors still land within an order of magnitude, which is usually enough to decide.
Case studyEight million descriptions, and a server nobody needed to buyA garment exporter in Tiruppur with eight million product descriptions accumulated across fourteen years, and a merchandiser who wants to know whether they have made a style before.Read it

The question the business asked was ordinary. A buyer sends a technical sheet; a merchandiser needs to know within an hour whether the factory has made something close enough to quote from. Fourteen years of catalogues, spreadsheets and order files held about eight million descriptions, and the only way to search them was a name-based lookup that failed on anything phrased differently.

A consultant proposed a search system and quoted for a graphics-card server, about four and a quarter lakh rupees, plus setup. The owner asked her nephew, who was in the second year of a computer science degree, to check the number before she signed.

He did four multiplications and then a fifth.

Deduplication first, because half the eight million were near-copies of each other and the consultant's plan compared every description with every other one to find them. Eight million items make about thirty-two trillion pairs. At a microsecond a pair that is three hundred and seventy days. It was not a slow step in the plan; it was a step that would never finish, and nothing in the proposal said so. The standard replacement hashes each description into a short signature so that similar ones land in the same bucket, and only compares within buckets, which turns the work from the square of the item count into something close to linear. It runs in an afternoon on a laptop.

Embedding next. Eight million descriptions of about sixty tokens each is 480 million tokens. A small free embedding model of 33 million parameters costs about two FLOPs per parameter per token, so 66 million FLOPs per token, and the whole corpus is about 3.2 times ten to the sixteenth FLOPs. His laptop manages around a hundred billion FLOPs a second, which is 3.7 days of continuous running. A rented graphics card, at a hundred times that in practice, does it in under an hour for a few hundred rupees.

Memory. Eight million vectors of 384 numbers at four bytes each is 12.3 GB, which does not fit in the 8 GB laptop the office had. Stored as one-byte integers instead, it is 3.1 GB, which does.

Query time. Comparing a query against all eight million vectors is about six billion FLOPs, or sixty milliseconds on that laptop. For one merchandiser at a desk that is instant. For the catalogue website the owner also wanted to connect, at forty queries a second, it is not.

The fifth calculation was the one with a real decision in it. Partitioning the vectors into about two thousand eight hundred clusters and searching only the sixteen nearest clusters brings a query from eight million comparisons down to about forty-eight thousand: a hundred and sixty times faster, comfortably fast enough for the website. The cost is recall. The true nearest description sometimes sits in a cluster the search did not open, and at that setting it will be missed roughly six times in a hundred.

Six in a hundred is not an abstract number in a garment factory. A missed match means the merchandiser is told the style is new when it is not, and the factory re-develops a sample it already has: about eleven thousand rupees and nine days, each time it happens.

What actually happened

The nephew wrote the five calculations on one sheet and the owner did not buy the server. The work ran on the office laptop with one afternoon of rented graphics-card time for the embedding step, at a total cost under four thousand rupees. Deduplication by signature hashing cut eight million descriptions to 3.4 million distinct ones, which made every later number smaller than the ones he had estimated. For the merchandisers at their desks the system searches all 3.4 million exactly, because sixty milliseconds a query needs no index and an index would only lose recall. The clustered index runs only behind the website, where the speed is needed and a missed match costs a visitor a scroll rather than a factory a sample. He measured the recall himself against exact search on a sample of two hundred real queries and got 94.5 per cent, close enough to his estimate that he trusted the rest of the arithmetic.

Worth arguing about

  1. The consultant's deduplication step compared every description with every other. Why is that not merely slow?

    One answer

    Comparing every item with every other is quadratic: eight million items give about thirty-two trillion pairs, which at a microsecond each is over a year, and the pairwise matrix would not fit in any storage the business owns. The fix is never to form most of the pairs. Hashing each description into a signature so that similar ones share a bucket, then comparing only within buckets, turns the work into something close to linear, and the pairs that never shared a bucket were with high probability never near-duplicates anyway.

  2. Why did he use exact search for the merchandisers and an approximate index only for the website?

    One answer

    Because the two have different costs for a miss. An exact scan of 3.4 million vectors takes tens of milliseconds, which is instant for one person at a desk, and it returns the true nearest match every time. An approximate index is a hundred and sixty times faster and misses the true nearest a few times in a hundred. On the website the speed is needed and a miss costs a visitor a scroll; for a merchandiser a miss costs a re-developed sample. You buy speed with recall only where the recall is worth less than the speed.

  3. He estimated 3.7 days on a laptop and under an hour on a rented card, and neither number was measured. Why was that good enough to decide on?

    One answer

    Because the decision only needed the order of magnitude. The point of the estimate was to distinguish an afternoon from a season, and a factor of three either way does not change which of those it is. A Fermi estimate built from a few factors each good to within a factor of three lands within about an order of magnitude, which is usually enough to choose. When it is not, the estimate at least names the factor you were least sure of, and that is the one worth going and measuring.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    A loop checks whether each item is already in a Python list of seen items. On a million items it takes hours; changing the list to a set makes it seconds. Why?

  2. 2

    A 13-billion-parameter model is trained on 2 trillion tokens. Roughly how many floating-point operations is that?

  3. 3

    Quantising a model from fp16 to int4 makes single-token generation about four times faster. What is the mechanism?

  4. 4

    A deduplication system keys a million documents by a 32-bit hash. How many unrelated documents will it silently merge?

  5. 5

    In a transformer of width 4,096, attention costs about four times L times d FLOPs per token per layer, and the linear parts about 24 times d squared. Where do they cost the same?

  6. 6

    You estimate a cost by multiplying six factors, each of which you believe to within a factor of three. Roughly how uncertain is the product?

Module 8

10 lessons · 91 min

Numbers inside a machine

What a float32 actually stores and where its seven digits run out, the half-precision formats and why training keeps a full-precision copy, cancellation and summation order, integer overflow, quantisation as rounding with a scale, condition numbers, the variance that travels through a layer, random numbers that are not, checking a gradient numerically, and reading NaN and Inf for what they are.

By the end you can

Predict from the bit layout of float32, fp16 and bf16 which computation will overflow, underflow or lose its digits, explain why a long sum drifts and how to fix it, quantise a weight to int8 by hand and say what an outlier does to the rest of the tensor, derive the initialisation scale that keeps variance constant through a layer, and diagnose a NaN in training back to the operation that produced it

  1. 67What a float32 actually stores, and where its seven digits run out10 minA float32 is a sign, an 8-bit exponent and a 24-bit mantissa, giving about seven decimal digits and a range near 10^±38, so its spacing grows with the number, an integer counter stalls at 2^24, and equality between computed floats is an accident of rounding rather than a fact.
  2. 68bf16, fp16, and why training keeps a float32 copy9 minfp16 keeps three digits and a range to 65,504 while bf16 keeps two digits and float32's full range, and because a small update added to a half-precision weight rounds away entirely, training keeps a float32 master copy of every weight and accumulates matrix products in float32.
  3. 69Catastrophic cancellation, and why a sum depends on its order9 minSubtracting nearly equal floats leaves only their rounding error, and adding a small float to a large one loses it, so variances must subtract the mean before squaring, long sums must accumulate in float64 or pairwise, and because addition is not associative a GPU's varying reduction order makes identical runs diverge.
  4. 70Integers, overflow, and the token id that would not fit8 minFixed-width integers are exact inside their range and wrap silently outside it, so counts, offsets and products of sizes belong in int64, pixels and ids belong in the smallest type that fits, and a result of exactly 2,147,483,647, 255 or 16,777,216 is a limit rather than a value.
  5. 71Quantisation is rounding with a scale: int8, int4 and the outlier problem10 minQuantisation stores each weight as round(w / scale) with the scale set by the largest value in its group, so the error is half a step for everyone and a single outlier can round an entire tensor to zero, which is why scales are kept per channel or per block of 128.
  6. 72The condition number, and how many digits a problem throws away9 minThe condition number σ_max/σ_min says how many digits a problem throws away, about log10(κ) of them, and the usual source of a large one is unscaled or correlated features, which is why standardising columns fixes both a numerically meaningless fit and a slow gradient descent at once.
  7. 73How variance travels through a layer, and the initialisation that follows9 minBecause a unit's output is a sum of fan_in independent products, its variance is fan_in × σ_w² × σ_x², so a weight spread of √(2/fan_in) keeps activations level through every ReLU layer while 0.05 or 0.01 explodes or vanishes them within twenty.
  8. 74Random numbers that are not, and what a seed does and does not fix9 minA pseudo-random generator is a deterministic recipe started from a seed, so seeding makes shuffles, masks and splits repeat, but it cannot fix a GPU's reduction order, a split that shifts when data grow, or Python's per-process string hashing, each of which needs its own remedy.
  9. 75Checking a gradient with finite differences, and the step size that lies9 minA two-sided finite difference has truncation error of order h² and rounding error of order ε/h, so the best step is about ε^(1/3), which in float32 leaves only five correct digits and makes gradient checks meaningful only in float64, where a relative error above 10⁻³ means the gradient is wrong.
  10. 76NaN, Inf, and the five numbers to print about any tensor9 minNaN arises from 0/0, Inf − Inf, sqrt of a negative or log of a negative, propagates through everything, and is unequal even to itself, so it is found with isnan rather than ==, traced upstream rather than where it appears, and prevented by the stable log, variance and normalisation forms the earlier lessons gave.
Case studyOne channel, ninety times the restAn agri-tech company in Nagpur shipping a cotton-pest identification model to farmers' phones, where two thirds of users have devices with three gigabytes of memory.Read it

The model identified fourteen cotton pests and disorders from a photograph of a leaf or a boll. It had 300 million parameters and worked well: 0.91 accuracy overall on a held-out set of nine thousand field photographs, and 0.81 on the four rare classes that mattered most, because those were the ones an extension officer would not recognise on sight.

In half precision the model is 600 megabytes. The company's user research said 62 per cent of their farmers had phones with three gigabytes of memory, on which the practical budget for an app of this kind is about 350 megabytes. At int8 the model is 300 megabytes and fits; at int4 it is 150 and fits comfortably.

The alternative was to keep the model on a server and send photographs to it. That is the easy engineering and it fails on the ground: the photograph has to be taken at the plant, and 44 per cent of the villages the company works in have no usable data connection in the field. A model that needs the network is a model that works in the office.

So the decision was between shipping a quantised model to the phone and shipping a better model that most users could not reach.

The first int4 attempt was a failure of a specific and instructive kind. Overall accuracy fell from 0.91 to 0.86, which the product manager could live with. Accuracy on the four rare classes fell from 0.81 to 0.42, which she could not, because those four are the reason the app exists.

The engineer looked at the tensors rather than at the accuracy, and found the cause in two channels. Quantisation stores each weight as a rounded multiple of a scale, and the scale is set by the largest value in the group so that the largest value lands on the top integer. Two channels in the later blocks carried activations about ninety times larger than the rest of the tensor. With one scale for the whole tensor, those two channels set a step so coarse that almost every other weight in the tensor rounded to zero or to a single step. One number had flattened a million.

The fix was arithmetic rather than retraining: a separate scale for each block of 128 weights, so that the outlier sets the step only for its own block of 128. That costs sixteen extra bits per block, which is an eighth of a bit per weight, taking the model from 150 to about 155 megabytes. Rare-class accuracy came back to 0.78.

During the calibration pass the engineer also hit a NaN, and the trace is worth recording. A normalisation statistic was computed as the mean of the squares minus the square of the mean, on activations whose mean was around three thousand. Both terms were near nine million, both were known to about seven significant digits, and their difference was supposed to be a variance of about two — smaller than the error in either term. In one batch it came out negative, the square root returned NaN, and the NaN propagated through every later layer of the calibration. Subtracting the mean before squaring, so that the numbers being squared were near one rather than near three thousand, removed it.

That left the last decision, which was not technical. At int4 with block scales the model is 0.78 on the four rare classes against 0.81 for the full-precision model on a server. Three points, on the classes that matter most, in exchange for reaching every farmer rather than 56 per cent of them.

What actually happened

They shipped the int4 model with per-block scales. On the four rare classes the app does not give a confident answer below a threshold measured on field photographs; instead it saves the picture and queues it, and when the phone next has signal the full-precision server model reviews the queue and sends back a corrected answer with a notification. About one identification in nine goes to that queue, and 71 per cent of queued photographs are answered within four hours. The three-point gap on rare classes is therefore paid only by farmers who never regain signal, rather than by the 44 per cent who would have had no app at all. The engineer's two additions to the release checklist are a per-block scale by default and a rule that no variance is ever computed as the mean of squares minus the square of the mean.

Worth arguing about

  1. Why does one activation channel ninety times larger than the rest destroy the whole tensor at int8 or int4?

    One answer

    The scale is chosen so that the largest absolute value in the group lands on the top integer, so the step size is set by that largest value. If one value is ninety times the typical one, the step becomes about ninety times coarser than the rest of the tensor needs, and every ordinary weight rounds to zero or to one step. The error is half a step for everyone, which is fine for the outlier and catastrophic for the values a hundredth its size. Confining the scale to a block of 128 confines the damage to that block.

  2. The variance came out negative and produced a NaN. What was the mechanism, and why did subtracting the mean first fix it?

    One answer

    The mean of the squares and the square of the mean were both about nine million and each was known to about seven significant digits, so each carried an error of roughly a unit. Their difference was supposed to be about two, which is smaller than the error in either term, so the leading digits cancelled and what remained was rounding error, which can come out negative. Subtracting the mean before squaring makes the quantities being squared small, so there is nothing large to cancel and the result is computed from digits that are actually known.

  3. Why did the company measure rare-class accuracy separately rather than trusting the overall figure?

    One answer

    Because the overall figure is dominated by the common classes and hides the classes the product exists for. Quantisation error is not spread evenly: it is larger for small weights, larger in the layers nearest the output, and larger for classes with fewer redundant paths supporting them. Overall accuracy fell five points while rare-class accuracy fell thirty-nine, and a single number would have reported the first and concealed the second. Anyone claiming int4 is free has not measured it on the part of their own task that matters.

Test yourself6 questions on this modulePractice. Nothing is recorded and no score is kept.
  1. 1

    A float32 running total of processed tokens stops changing at 16,777,216. What is happening?

  2. 2

    A variance computed as the mean of the squares minus the square of the mean returns a negative number on data centred near 10,000. Why?

  3. 3

    Training keeps a float32 copy of every weight even though the forward pass runs in bf16. What breaks without it?

  4. 4

    You initialise every weight with a spread of 0.05 in layers of width 1,024 with ReLU between them. What happens over twenty layers?

  5. 5

    A training run produces NaN in the loss at step 900. Where should you look first?

  6. 6

    One feature ranges from 0 to 1 and another from 0 to a million, and a least-squares fit in float32 returns a meaningless coefficient on the small one. What is the fix?

No ads. No data sale. No public scores on people. Ever.

© 2026 Addaly