AAI, Built

Act I · Foundations

Part 3 of 31

Vectors That Mean Things

Undergraduatestarts at this level54 min of film19 chaptersprerequisites: Part 1

How can a list of numbers stand for the meaning of a word?

Part 1's counting model could not tell 'the dog barked' from 'the hound barked', so this part gives words a place in a space. It opens on 102 words where GPT-2 puts them and builds the linear algebra needed to read that picture: the dot product and Cauchy-Schwarz, einsum, matrices as maps, projection and least squares, eigenvectors and the spectral theorem, and power iteration run live. The centre is the singular value decomposition, every matrix as turn, stretch, turn, and the Eckart-Young theorem: the best rank-k copy keeps the top k singular values. Norms and the condition number measure a matrix; random matrices give the Marchenko-Pastur bulk that training's outliers escape, and gradients turn out to be low rank. Word vectors then come from counting (PPMI and a truncated SVD), and word2vec is shown to factor the same shifted table. The part turns to high dimensions, where random directions are nearly perpendicular and Johnson-Lindenstrauss is proved, and ends with GPT-2's lopsided embedding space and low rank in recommendation and retrieval.

What you need. School algebra and coordinates in the plane. The letter tables of Part 1 are reused.

Mathematics and history
inner products, eigenvalues, SVD and Eckart–Young, norms, random matrices, high-dimensional geometry, Johnson–Lindenstrauss, matrix factorization
Models, data
word2vec, GPT-2's embeddings, the Netflix Prize

What you will be able to do

Undergraduate

  • Compute a dot product and a cosine similarity, and say what each tells about two word vectors.
  • Describe what a matrix does to the plane from its columns, and what its singular values measure.
  • Explain why two random directions in 768 dimensions are almost always nearly perpendicular.

Master's

  • Derive the projection onto a column space and the SVD from the spectral theorem applied to the Gram matrix.
  • Prove the Eckart-Young theorem from Weyl's inequality, and derive power iteration's convergence rate.
  • Derive the shifted-PMI target that skip-gram with negative sampling factorizes.

Research

  • Prove the Johnson-Lindenstrauss lemma by a Gaussian projection, a chi-squared Chernoff bound and a union bound, and state the matching lower bound.
  • Compare a trained layer's spectrum with the Marchenko-Pastur law, and say what a fitted power-law tail does and does not show.

Engineering

  • Write a contraction in einsum and count its cost, and pick the cheaper order of a matrix chain.
  • Fit a matrix factorization to ratings with a penalty, and report held-out error against baselines fitted on the same data.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 21 min · Master's 46 min · Research 54 min · Engineering 28 min.

  1. 0Where words liveUndergraduate2 min
  2. 1Vectors and the inner productUndergraduate3 min
  3. 2Tensors and einsumMaster's3 min
  4. 3Matrices move spaceUndergraduate2 min
  5. 4Projection and least squaresUndergraduate3 min
  6. 5Directions that stay putMaster's3 min
  7. 6Power iteration, run liveMaster's2 min
  8. 7Every matrix: turn, stretch, turnUndergraduate2 min
  9. 8The best low-rank copyMaster's3 min
  10. 9How big is a matrix?Master's3 min
  11. 10Random matrices and trained weightsResearch2 min
  12. 11Gradients are low rankEngineering3 min
  13. 12Word vectors from countingUndergraduate3 min
  14. 13word2vec is counting in disguiseMaster's4 min
  15. 14Life in 768 dimensionsUndergraduate2 min
  16. 15Johnson-Lindenstrauss, provedResearch3 min
  17. 16GPT-2's lopsided spaceResearch3 min
  18. 17Low rank in the wildEngineering4 min
  19. Recap, problems, and what comes nextAll tracks2 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Where words liveUndergraduate2 min

In part one, a model learned to guess the next letter by counting, and it hit a wall. It could share exact letter patterns, but each context was an island of counts. Reading the dog barked a hundred times did not teach it that dog and hound have related meanings.

Every modern model fixes this the same way. It gives each word a place, a point in a space, chosen so that words used alike end up close together. Here are 102 words, where GPT-2 puts them: animals in one region, colors in another, then numbers, places, family, the body, and verbs.

The picture is a shadow. GPT-2 really gives each of its 50,257 tokens a list of 768 numbers, and we've flattened them down to three, keeping the three directions along which these words spread out the most. Up close, dog sits with the other animals.

Here is dog, all 768 numbers. Here is puppy. And here is tobacco. Two of these belong together, and in chapter one we'll learn to measure how much.

The mathematics is older than the machines. In 1844 Hermann Grassmann described quantities that add and stretch, in any number of dimensions. In 1858 Arthur Cayley wrote down the algebra of matrices. Beltrami and Jordan found the singular value decomposition, and Hilbert named eigenvalues. Eckart and Young proved how to keep only what matters. Then meaning: John Firth's 'you shall know a word by the company it keeps'. Johnson and Lindenstrauss squeezed dimensions. Latent semantic analysis put words in a space, and Netflix offered a million dollars for filling in a mostly empty matrix. Then word2vec, and LoRA, GaLore and Muon, the same linear algebra inside today's training.

This is Part 3 of AI, Built. In it: vectors, the dot product and einsum; projections, eigenvectors and the singular value decomposition, each derived; norms, random matrices and what training writes into weights; word vectors; the geometry of high dimensions; and low rank at work. Every number computed, small enough for a laptop.

1Vectors and the inner productUndergraduate3 min

How alike are two vectors?

A vector is an arrow from the origin, or, just as well, a list of numbers: how far to go along each axis. Two numbers in the plane, three in space, and 768 for a word in GPT-2. Grassmann saw in 1844 that the algebra doesn't care how many numbers there are. Almost nobody read him for forty years.

Two moves make all of linear algebra. Add two vectors: walk along one, then the other. And scale them: stretch, shrink or flip. Mix the two, a times u plus b times v, and the tip sweeps out the whole plane: u and v are a basis, and every vector has exactly one pair of coordinates in it.

How alike are two vectors? Multiply them coordinate by coordinate and add: the dot product, or inner product. It is symmetric, linear in each slot, and a vector dotted with itself is its length squared. Draw the triangle with sides a, b and a minus b. Its third side squared is a dot product. Expand it. Euclid's law of cosines gives the same side another way. Compare: the dot product is the two lengths times the cosine of the angle between them.

Is that cosine always between minus one and one, even in 768 dimensions? That's the Cauchy-Schwarz inequality. For any number t, the length of a minus t b, squared, can't be negative. If b is zero, the inequality is immediate. Otherwise, expand it: a parabola in t. A parabola that never dips below zero has at most one root, so its discriminant can't be positive. Rearranged: the absolute dot product is at most the product of the lengths. Turn b and watch: the parabola touches zero when b lies on a's line, in either direction. So an angle between two words makes sense.

Divide by the two lengths and you get the cosine similarity, which runs from minus one to one. For GPT-2's words: dog and puppy, 0.62. Dog and cat, 0.55. Dog and tobacco, 0.23. In 768 dimensions you can't draw the angle, but you can compute it: multiply the two lists number by number, and add.

Here is why this matters. In Part 1, a network ended with a score for every possible next token, and the softmax turned scores into probabilities. In GPT-2, each score is a dot product: the model's final state with each token's vector, the very vectors the tokens started out as. After the Eiffel Tower is located in the city of, the biggest dot products belong to Paris, London, Amsterdam. The softmax gives Paris 6.4 percent.

2Tensors and einsumMaster's3 min

How do we write products of arrays with many axes?

A number, a vector, a matrix: zero, one and two axes. A batch of text is a list of sentences, each a list of tokens, each a list of numbers: three axes, what machine learning calls a tensor. Attention splits the numbers among 12 heads: four. Products of such arrays need a notation that names the axes.

Multiplying two matrices: entry i k is row i of A against column k of B, summed over j. In 1916, writing general relativity, Einstein tired of summation signs and dropped them: an index that appears twice is summed. Programs adopted the idea as einsum, with a letter for each axis. A letter in the output is kept; a letter only in the inputs is summed away. And the cost is one multiply-add for every combination of the letters: i times j times k.

One function does all of these. The dot product: multiply, and sum everything. The outer product: nothing summed, a matrix of rank at most one. Matrix times vector. The transpose, which only reorders. The trace. And a batch of matrix products, the letter b carried along.

Here is attention, Part 13's subject, in this notation. Each token's vector is projected into queries, keys and values, split among heads. Every query is dotted with every key: e is summed away. A softmax turns scores into weights, which average the values. The heads are merged back. Read the costs off the letters. For 1,024 tokens, the scores take about 805 million multiply-adds per layer, and the projections 2,416 million. The scores grow with the square of the length: that is why long contexts are expensive.

The letters also show that order matters. A is 1,000 by 20, B is 20 by 1,000, C is 1,000 by 20. Multiply A and B first, and you build a 1,000 by 1,000 matrix on the way: 40,000,000 multiply-adds. B and C first: 800,000. The same answer, 50 times cheaper. einsum can find the cheap order itself; here it multiplies B and C first.

3Matrices move spaceUndergraduate2 min

What does a matrix do?

A matrix moves every vector at once. It keeps the origin where it is, and keeps grid lines straight, parallel, and evenly spaced: it's a linear map. Watch the whole plane move.

Where does each vector go? Only two arrows decide it: where the two basis arrows land. Those landing spots are the columns of the matrix. A vector with coordinates one and two lands at one times the first column, plus two times the second. That's what multiplying a matrix by a vector means.

One map after another is again a map, and its matrix is the product of the two. But the order matters: turning, then shearing, is not shearing, then turning. Arthur Cayley made matrices objects in their own right in 1858, with exactly this rule; his friend James Joseph Sylvester had named them eight years before.

One number says how much a map stretches area: the determinant. The unit square becomes a parallelogram: its area is the absolute determinant, and the sign records orientation. When the determinant reaches zero, the whole plane is squashed onto a line, and information is lost for good. Below zero, the plane has been flipped over, like a page turned face down.

That squashing has a name, and it will matter for the rest of this part. This matrix sends the whole plane onto one line: its columns point the same way. The line where everything lands is the column space, and its dimension is the rank, here one. A whole line of vectors lands on zero: the null space. The dimensions always add up: rank plus the null space's dimension is the number of columns. A matrix of low rank is a big table that carries few independent directions.

4Projection and least squaresUndergraduate3 min

What is the closest point in a subspace?

The dot product measured a shadow; here is the shadow made exact. Which point on the line through a is closest to b? Some multiple of a, the one whose error, b minus that point, is perpendicular to the line: any other point is farther, by Pythagoras. Solve for the multiple. The projection is a matrix times b: a times a transpose, over a dot a. A matrix of rank one, that finds shadows.

Now project onto a subspace: everything you can reach by combining the columns of a matrix A. The closest point is A times some x hat, and the error is perpendicular to every column at once. Multiply out: the normal equations. If the columns are independent, A transpose A can be inverted. The projection matrix: A, A transpose A inverse, A transpose. Project twice and nothing more happens; and P is symmetric. Legendre published this in 1805 as least squares, and Gauss in 1809, who had used it to find the lost asteroid Ceres.

This is the most used calculation in statistics. Fourteen points and a line. The columns of A are ones and the x values; the best line is the projection of the y values onto their span. The errors are perpendicular to both columns: they sum to zero, and so do the errors times x. Regression, a linear probe reading a concept out of a network, a last layer trained with squared error: all this projection.

Projections are easiest with an orthonormal basis, perpendicular arrows of length one: then the projection is Q times Q transpose. Gram and Schmidt's recipe makes one from any basis. Scale the first vector to length one. From the second, remove its shadow on the first; what is left is perpendicular. Scale it, and repeat. Keeping the coefficients writes A as Q times a triangular R: the QR factorization.

On a computer every step rounds, and rounding can pile up. We tested on Hilbert matrices, whose columns become nearly dependent. The classical recipe loses orthogonality as the square of the condition number: at a condition number of ten to the , its Q is off by about ten to the minus . The modified recipe, which takes each shadow from the updated vector, loses only in proportion. Alston Householder's reflections, from 1958, stay perpendicular to about ten to the minus , the machine's precision. The normal equations share the classical flaw: forming A transpose A squares the condition number. At the hardest case QR's answer is off by ten to the minus , That is why libraries solve least squares with QR.

5Directions that stay putMaster's3 min

What does a matrix do to a direction?

Most vectors are knocked off their line by a matrix. Some aren't: they stay on their line, only stretched, shrunk or flipped. Those are the eigenvectors, and the scale is the eigenvalue. A minus lambda I must then squash a direction to zero, so its determinant vanishes: a polynomial equation for lambda.

Symmetric matrices, equal to their mirror image across the diagonal, behave best. Their eigenvalues are real, and we can choose an orthonormal eigenvector basis. So the map is: turn the eigenvectors onto the axes, stretch each axis by its eigenvalue, and turn back. A equals Q, Lambda, Q transpose; for a turn like Q, the transpose is the same turn, undone. That's the spectral theorem.

Why does it always work? The proof has three steps. First, the eigenvalues are real: sandwich A between an eigenvector and its complex conjugate. Since A is real and symmetric, the middle number equals its own conjugate, so lambda equals lambda bar. Second, eigenvectors with different eigenvalues are perpendicular: move A across the dot product, and the eigenvalues must agree unless the dot product is zero. Third, A maps the space perpendicular to an eigenvector into itself, so repeat inside it: by induction, a full set. Cauchy proved the first part in 1829; Hilbert took it to infinite dimensions.

One number connects eigenvalues to what follows: the Rayleigh quotient, x transpose A x over x transpose x. In the eigenvector basis it is a weighted average of the eigenvalues. So as x turns, it stays between the smallest and the largest eigenvalue, reaching them along the eigenvectors. The top eigenvector answers a question: which direction does A favour most? It returns as principal components, power iteration and the SVD.

Covariance matrices describe how data spreads: how much each coordinate varies, on the diagonal, and how much pairs vary together, off it. The spread along a unit direction is the covariance's Rayleigh quotient, so the direction of greatest spread is the top eigenvector. These are the principal components, Pearson's in 1901 and Hotelling's in 1933. Keeping the top few is how we drew GPT-2's words in three dimensions.

6Power iteration, run liveMaster's2 min

How does a computer find an eigenvector?

Eigenvalues are roots of a polynomial, of degree 768 for a 768 by 768 matrix. Abel proved there is no general formula using radicals beyond degree four, so computers use numerical methods. For this symmetric matrix, start with a nonzero component along its dominant eigenvector, multiply by A, rescale to length one, repeat. Here, each multiplication favours the direction A stretches most, and the arrow swings onto the top eigenvector.

Why it works takes four lines. Take a symmetric matrix and a start with a nonzero component along its dominant eigenvector. Write the start in the orthonormal eigenvector basis. k multiplications stretch each part by its eigenvalue to the k. Pull out the largest: every other part is multiplied by a ratio below one, to the k. So the angle shrinks like lambda two over lambda one, to the k: a straight line on a log scale. The eigenvalue estimate does twice as well, because the Rayleigh quotient sits at a stationary point, where small errors in direction barely move it.

Now real matrices. The covariance of GPT-2's 50,257 token vectors, 768 by 768: its top two eigenvalues have a ratio of , and the error falls by per step, down to the machine's rounding. The random start was almost perpendicular to the answer, a sine of ; chapter fourteen explains why. Part 1's letter table: a ratio of , and measured, . Dashed, the prediction: .

The method is from 1929, by Richard von Mises and Hilda Pollaczek-Geiringer. In 1998 it ranked the web: PageRank is the top eigenvector of a matrix of links. In 2018, spectral normalization ran one power step per training step to keep layers from stretching too much. And today's library routines are its refinement: Krylov methods, after Cornelius Lanczos in 1950.

7Every matrix: turn, stretch, turnUndergraduate2 min

What does any matrix do?

Not every matrix is symmetric. Many aren't even square. But every matrix, without exception, has three factors: an orthogonal change of coordinates, a stretch or projection along the axes, and another orthogonal change. Those coordinate changes may rotate or reflect. Our example uses two rotations. That's the singular value decomposition: A equals U, Sigma, V transpose.

Where do the turns and stretches come from? A transpose A is symmetric, and never negative: x transpose A transpose A x is a length squared. So the spectral theorem gives it perpendicular eigenvectors v, with eigenvalues sigma squared. Send each v through A and divide by sigma, for nonzero sigma. Complete the orthonormal bases for any zero singular values. These u's are perpendicular too, and of length one. So A sends perpendicular v's to perpendicular u's, stretched by the sigmas: the decomposition. Beltrami and Jordan found it in 1873 and 1874; Gene Golub and William Kahan's algorithm of 1965 is what computers still use.

The stretches are the singular values. The unit circle always becomes an ellipse, and the singular values are its half-axes. Sweep a unit vector all the way around, and watch how long its image is. The longest it ever gets is sigma one: the most the matrix can stretch any vector. It's called the spectral norm.

8The best low-rank copyMaster's3 min

What is the best simple version of a matrix?

Written out, the decomposition makes any matrix a sum of simple pieces, each a column times a row, weighted by a singular value. The number of pieces is the rank; a low-rank table is one a few pieces build. Keep the k biggest and you get the closest matrix of rank k. Nothing else comes closer: the Eckart-Young theorem, from 1936.

Why can't anything beat them? Weyl's inequality, from 1912: A's singular values, shifted by k, are at most those of A minus B plus the k plus first of B. If B has rank k, that last term is zero. A matrix's squared size equals the sum of its squared singular values, as chapter nine shows, so B's error is at least the tail of A's. Keeping the top k achieves exactly that tail.

A picture is a matrix too: rows of grey levels. Its best rank-one copy is a column times a row: stripes, the sky and the horizon. Rank two, four, eight: the mountains appear. Rank keeps percent of the squared size with percent of the numbers. Then the trees; by rank it is hard to tell from the original. And each Frobenius error is exactly the Euclidean norm of the singular values left out.

Part 1's table of letter pairs, 26 by 26, with square-root probabilities. Its first piece is a separable approximation: after squaring and normalizing, the two letters are independent. Add the second, third, fifth, tenth, and the Frobenius error equals the Euclidean norm of the singular values left out: of the whole after one piece, after two.

The pieces mean something. Take the table's departure from independence: each count against what you'd expect if letters ignored their neighbours. Spread the letters along its strongest direction. At one end: , .

Low rank is everywhere in machine learning. In 1990, latent semantic analysis searched documents by meaning with a truncated SVD. In 2021, LoRA fine-tuned huge models by learning a low-rank change to each weight: for GPT-3, ten thousand times fewer numbers to train. In 2024, DeepSeek squeezed attention's keys and values through a low-rank bottleneck. Parts 15 and 27 build these.

9How big is a matrix?Master's3 min

Which size matters, and when does a matrix lose precision?

A matrix has two natural sizes. The Frobenius norm treats it as a list of numbers: the root of the sum of squares. The spectral norm treats it as a map: the most it stretches any vector, the top singular value. The squared Frobenius norm is the trace of A transpose A, and the trace is the sum of the eigenvalues, the squared singular values: chapter eight's missing step. So the spectral norm is at most the Frobenius norm, which is at most root r times it. Their squared ratio, the stable rank, counts how many directions carry the size.

Here are the stable ranks of GPT-2's 48 block matrices; each could reach . A random matrix of the MLP's shape has ; theory predicts . The trained ones run from to : . A smaller stable rank means the matrix's size is concentrated in fewer directions.

Norms multiply through a network. Stretching by A then B stretches by at most the product. Push a vector through 40 random layers. At a stretch of 1.2 per layer, its length grows 2,116 times. At 0.8, it shrinks to 0.00015. Only near one does the signal survive: Part 9's subject.

The largest stretch over the smallest is the condition number: how much a matrix can amplify errors. Solve A x equals b with a small error in b. The error in x is at most that error over the smallest singular value, and b is at most the largest times x. Divide: relative errors grow by at most kappa. A computer's rounding plays the error in b. At a condition number of a million, 64-bit arithmetic loses about ten to the minus of the answer; 32-bit, ten to the minus . GPT-2's worst-conditioned matrix reaches about ten to the .

The spectral norm has become an optimizer. Which step of spectral size one changes the loss most along a gradient G? Write G with its SVD. Each diagonal entry is at most one, so the best is U V transpose: the gradient with every stretch set to one. That is Muon's normalized direction; take its negative for descent. It is computed with five Newton-Schulz iterations, matrix products that push singular values towards one. On a real gradient, percent of the singular values are below a hundredth of its largest. We first divide the gradient by its Frobenius norm. After five steps, percent lie between 0.6 and 1.3. Part 11 builds the optimizer.

10Random matrices and trained weightsResearch2 min

What does training write into a matrix?

What does pure noise look like, through its eigenvalues? In 1955 Eugene Wigner modelled heavy nuclei's energy levels with a random matrix's eigenvalues, and found a law. In 1967 Marchenko and Pastur found it for rectangular matrices: the eigenvalues of W W transpose over M approach a fixed interval and shape, set by the aspect ratio in the large-matrix limit. We'll check it rather than prove it. A random 768 by 3,072 matrix, GPT-2's MLP shape: eigenvalues, and the law on top.

Now a trained matrix: GPT-2's layer , the first matrix of its MLP, scaled the same way. Most eigenvalues sit in a bulk much like the law. But lie strictly beyond the plotted edge, with no two-percent margin; the largest is times the edge. This is a finite-sample comparison, not a hard support guarantee. Just unusual values? Shuffle the same numbers into random places. The information is in the arrangement: a few strong directions, learned.

We can summarize a spectral tail with a fitted power-law density, falling as lambda to the minus alpha. In 2019 Charles Martin and Michael Mahoney used random matrix theory to study heavy-tailed structure in trained networks. Here the shaded band from 1.5 to 5 is only a descriptive comparison, not a universal accuracy criterion. Of GPT-2's 48 matrices, fits fall in that band. A fitted exponent alone does not establish a power-law model. The independent Gaussian reference has a compact limiting bulk, rather than a power-law tail.

The same in this series' small novels model. At initialization its matrices are random: eigenvalues strictly above their limiting edges in all. After training, between and strictly beyond the edge, using the same threshold with no two-percent margin. Training writes a little structure into a sea of noise.

11Gradients are low rankEngineering3 min

How much of a gradient matters?

A gradient is a matrix too, with its own singular values. A layer turns each token's vector x into W x. By the chain rule, Part 4's subject, the gradient for one weight sums, over tokens, the error at that output times the input. So the gradient is a sum of outer products, each of rank at most one per token. Its rank is at most the number of tokens. In practice it is often approximately low rank: errors and inputs concentrate in a few directions.

Here is a real gradient, from a small transformer trained on the novels: one by matrix. Its singular values, largest first, on a log scale. At step , the top eight carry percent of squared gradient energy. The largest measured top-eight share is at step : percent. At the final step, , it is percent, of possible directions. The cursor aligns each spectrum with its position on the full energy-share trajectory.

That is GaLore's idea, from Jiawei Zhao, Anima Anandkumar, Yuandong Tian and colleagues in 2024. Adam keeps two running averages per weight: fourteen billion extra numbers for a seven-billion-parameter model. GaLore projects each gradient onto its top r singular directions and runs Adam there, refreshing the directions now and then. For our model: numbers with Adam, at rank 32, at rank 8. At scale the paper reports up to 65 percent less optimizer memory, and demonstrates that seven-billion-parameter pretraining can fit within 24 gigabytes, with 8-bit states, per-layer updates, and a small token batch. This is a memory-feasibility result.

Does a narrow window cost anything? We trained the model with Adam and with GaLore at ranks 32 and 8, each at its best of three learning rates chosen using seed zero's validation result. We then run that rate on seeds zero, one and two; the reported three include the tuning seed. Training curves show the mean and minimum-to-maximum band after an eight-sample moving average, with no hard loss clipping. The held-out loss: Adam , rank 32 , rank 8 .

Compare LoRA, Part 27's tool. LoRA keeps the change to the weights at rank at most r for good. GaLore keeps each step at rank at most r, but the window moves. After 600 steps, the total change to one matrix has an effective rank of with the rank-8 window, against for Adam:

12Word vectors from countingUndergraduate3 min

Can a computer learn what words mean by counting?

Part 1 began with counts of distinct letter symbols. Now we connect words by counting the contexts they share. The idea comes from linguistics. In 1954 Zellig Harris argued that words in the same contexts tend to mean similar things. In 1957 John Firth: you shall know a word by the company it keeps. In 1990 Scott Deerwester, Susan Dumais and colleagues made it an algorithm: count words in documents, take the SVD, and search by meaning rather than spelling.

We'll do it with the thirty novels. Take the ten thousand commonest words and count how often each pair turns up within four words: a hundred million cells, from 4.35 million words of text. Then turn counts into surprise, Part 1's way: the log of how many times more often two words meet than by chance, the pointwise mutual information. Keep its positive part. Monday and morning: 4.16. The and of meet 85,086 times, but they meet everything: 0.69. For the SVD table, we smooth the context distribution with the three-quarters power, then keep positive values.

Keep the table's hundred strongest directions, with the SVD. Every word gets a hundred numbers. Words that keep the same company end up close. Monday: . Three: . Dog: . Ship: . Nobody gave it a dictionary.

How many directions does meaning need? Keep only the strongest few. With , only of these twenty neighbours are final ones. With , , , and all . Our threshold is three of five neighbours among the final top ten. first crosses it at tested directions; at . This is a first crossing, not a claim that every later neighbour stays fixed. The strongest directions carry the broad patterns; finer meanings live further down.

Directions mean something too. Step from France to Paris, then take the same step from England. Man is to king as woman is to: , then . On such questions built from the books, man and woman, dog and dogs, walk and walked, the nearest word is right percent of the time, out of ten thousand candidates. Separately, searching only among categorized words, of each category word's five nearest neighbours, animals, colours, numbers and so on, percent share its category, against percent by chance.

13word2vec is counting in disguiseMaster's4 min

What does a guessing game learn?

In 2013 Tomas Mikolov and colleagues at Google learned word vectors with a guessing game. Each word gets two vectors, one as the word and one as a neighbour. Training raises a word's dot product with its real neighbours, through the logistic function, and lowers it with 5 random words. That is skip-gram with negative sampling, the heart of word2vec: cheap enough for billions of words in hours.

We trained it on the novels, with the same vocabulary and nominal window as the counting. Subsampling frequent words changes the actual context sequences. Four words and their nearest neighbours, with the loss below. At the start, random. After steps, the lists are still mixed; some favour common function words. By step , meaning appears: three sits with . By the end, Monday sits with , and father with . Nothing told it what a day or a relative is.

Why do guessing and counting agree? In 2014 Omer Levy and Yoav Goldberg showed why. Collect the log objective for one word and one context: the pair appears as a real neighbour some number of times, and as a negative about k times the word's count times the context's sampling probability. Treat their dot product x as free; set the derivative to zero. The ratio of the two logistic terms is e to the x. Take logs: this maximizes the log objective. If negatives follow the empirical context distribution, the best dot product is PMI minus log k. With smoothed negatives, as in our run, use their sampling probability in the same log-count ratio: a generalized shifted PMI.

Let's check it on the commonest words, after three thousand Adam steps. We measure observed pairs seen at least five times. With numbers per vector, all dot products can be free in principle, but finite training is not a convergence certificate: the measured median error from generalized shifted PMI is . With , the points spread: . With , . A short vector holds only a low-rank version of the table.

And the real run, ten thousand words with a hundred numbers each? For the pairs it saw at least times: trained dot product against the shifted PMI of its own training pairs. Correlation , slope .

Which is better? On our analogy questions, counting gets percent and word2vec . On category neighbours, against . Levy, Goldberg and Dagan found in 2015 that, tuned with equal care, the two families are close. GloVe, in 2014, fitted the log counts directly. All of these give one vector per word: bank by a river and bank with money share one. Parts 13 and 14 make vectors depend on context.

14Life in 768 dimensionsUndergraduate2 min

What is a space with hundreds of dimensions like?

Our intuition comes from three dimensions, and in 768 it misleads us. Two random directions: in two dimensions, any angle. In three, right angles are already the most common. In ten, the spread is degrees. In a hundred, the angle's standard deviation around ninety degrees is degrees, and in 768, .

Why? The cosine is the dot product over the lengths, each close to root d, as we'll see. The dot product is a sum of d independent products of mean zero and variance one: variance d. Divide by d squared: the cosine's variance is one over d. Measured from d of 2 to 4096, the points sit on the line; at 768, 0.00128 against 0.00130.

So high-dimensional space is roomy. Ten thousand random directions in 768 dimensions: every pair between 79 and 101 degrees apart. A model stores an idea, a feature, as a direction, and can keep far more features than dimensions if they need only be nearly perpendicular: superposition, how Part 30 reads a model.

Now lengths. As d grows, a random vector's length piles up around root d. Its square is a sum of d squares, with mean d and variance 2 d. The square root changes by one over two root d per unit, so the length's spread is about one over root two for large d: the absolute length grows, its absolute spread approaches a constant. The histogram divides length by root d, so its relative spread narrows. Measured at 768, .

Volume is stranger. It grows like the radius to the d, so the inner ball with 99 percent of the radius holds 0.99 to the d of the volume. In three dimensions, the outer one percent holds 3.0 percent. In a hundred, 63.4. In 768, 99.96 percent: a high-dimensional ball is nearly all skin.

15Johnson-Lindenstrauss, provedResearch3 min

How few numbers can keep the distances?

A consequence that sounds impossible. Multiply a thousand of GPT-2's vectors by one random matrix, crushing 768 numbers to a few. These are sampled ordinary-distance pairs, with one map per target dimension. Down to , distances are scrambled; , : better. At , percent of the distances move by less than ten percent; at , percent.

The Johnson-Lindenstrauss lemma, from 1984, in Dasgupta and Gupta's form of 2003. To keep every squared distance among n points within one plus or minus epsilon, a random projection to about log n over epsilon squared dimensions, up to a constant, suffices. For our thousand points at ten percent: 5,921. The starting dimension doesn't appear at all. Let's prove it.

Fix one pair, and let x be their difference, of length one. Each coordinate of R x is a sum of independent normals: normal, with variance one. The squared length is a sum of k such squares: chi-squared, mean k. The Chernoff trick: Markov's inequality on e to the t times it, whose average we know. The best t, and a bound on the logarithm: the chance of stretching past epsilon falls exponentially in k, and shrinking likewise. The union bound over all pairs: once k reaches four log n over that small quantity, the chance of any failure is below one. A good projection exists, and a random one works with probability at least one over n.

Now the data. For one pair, the chance of moving more than percent is exactly a chi-squared tail, in yellow. These are squared-distance errors. The mean measured fraction over five maps differs from that probability by at most ; the bars show the range. Pairs sharing a map are dependent. The dashed Chernoff bound lies above the exact probability: at , against .

The lemma promises every pair at once. The worst pair of all, five random matrices per k. Bars show the minimum to maximum, with a mean dot. This confidence comparison is separate from the classic existence statement we proved. In the worst case no map can do much better: in 2017 Kasper Green Larsen and Jelani Nelson proved log n over epsilon squared optimal, up to a constant.

16GPT-2's lopsided spaceResearch3 min

Are a trained model's vectors spread evenly?

Random directions in 768 dimensions are nearly perpendicular, cosines of zero give or take . Trained vectors are not random. We sample two thousand token IDs from one thousand through nineteen thousand nine hundred ninety-nine, not the whole vocabulary. Between two of those token vectors the average cosine is : they all lean one way, the space is anisotropic. Each makes a cosine of , on average, with the full vocabulary mean. Subtract that mean, and the average cosine falls to .

Even centred, the spread is uneven. The top principal direction carries percent of it, against for an even share. Colour each token by its number in GPT-2's vocabulary, a rough merge-order proxy rather than a measured frequency rank: the first direction tracks it, a rank correlation of . Jun Gao and colleagues explained this in 2019: training mostly pushes a rare token's vector away from contexts, so rare tokens drift together. Removing the top direction too, Mu and Viswanath's all-but-the-top of 2018, brings the average cosine from to .

Inside the network it is stronger. GPT-2 reading the scoreboard's passage, layer by layer: the average cosine between positions is at the input, about in the middle, and after final normalization. The maximum among non-input layers is at layer . This illustrates the narrow-cone effect Kawin Ethayarajh measured in 2019. In layer , three of 768 dimensions carry percent of the average cosine as a signed contribution, not a share of squared variance: rogue dimensions, in Timkey and van Schijndel's phrase. Centre each layer and the cosines fall to about zero. Raw cosines measure this common lean as much as meaning.

Lopsided or not, directions carry meaning: our counted vectors sent England to london. In 2013 Mikolov, Yih and Zweig found such regularities in neural word vectors. In 2022 Nelson Elhage and colleagues showed toy networks storing more features than dimensions, as nearly perpendicular directions. In 2024 Kiho Park, Yo Joong Choe and Victor Veitch made it precise: concepts as directions, under the right inner product, not always the plain dot product. Reading and steering along such directions is Part 30's subject.

17Low rank in the wildEngineering4 min

Can a mostly empty table be filled in?

Low rank's most famous test came from a DVD rental company. In October 2006 Netflix released a hundred million ratings, from 480,189 customers on 17,770 films, and offered a million dollars to predict held-out ratings ten percent better than its own system. The table was mostly empty: about two hundred ratings per customer. In December, a programmer writing as Simon Funk posted a short program that factorized it by gradient descent, and leapt up the leaderboard. In 2009 BellKor's Pragmatic Chaos won with a blend of hundreds of models, many of them refinements of that factorization.

The model is a sum. An average, plus the user's generosity, plus the film's quality, plus a dot product of k numbers of taste each. Fit it to the ratings we have, keeping the vectors small, with a separate fixed penalty on user and film biases. Chapter eight solves the unregularized least-squares rank-k approximation of a full matrix. Here, we optimize the observed ratings with the vector and bias penalties. We built a small world to test on: users, films, ratings, from six hidden genres the method never sees.

Training replayed, at rank . The error falls on the ratings it trains on, and on held-out ones: from stars to . On the right, each film's vector, on its two strongest directions, coloured by the hidden genre, with each genre's average. Of each film's ten nearest films, percent share its genre, against percent by chance.

How much taste does it take? All methods are refitted on the same training plus validation ratings, then measured on the same untouched test ratings. The average rating misses by stars. Adding generosity and quality: . Then the taste vectors, rank one to thirty-two, three seeds each. The error is lowest at rank ,

Factorization has a weakness: a new user has no vector. Today's recommenders use two towers. One network turns a user's history into a vector, another a film's details; the score is their dot product. Trained so each user's real films outscore the batch, corrected for the negative sampling distribution. In the ideal candidate-classification calculation, the corrected logit carries a density ratio, while the raw score models the conditional log probability, up to a user constant. We rank by the raw score; adding a popularity prior again is a separate ablation, not a recovery step. Finite training need not reach that ideal. Macro recall averages each user's fraction of all eligible held-out favourites recovered in the top ten. New users start from five films each. Separately,

Retrieval is, at heart, one matrix product, and the art is not computing most of it. In 2016 YouTube described recommending as a nearest-neighbour search among video vectors. In 2017 Facebook's FAISS searched a billion vectors, on GPUs. In 2020 dense passage retrieval put questions and passages in one space, the way assistants now find what to read before answering. Part 29 puts it to work.

Recap, problems, and what comes nextAll tracks2 min

Let's take stock. Vectors are lists of numbers with geometry; the dot product, kept honest by Cauchy-Schwarz, measures likeness. Einsum names the axes and counts the cost. Projections find the closest point, and arithmetic's order matters. Symmetric matrices stretch along perpendicular directions, which power iteration finds; every matrix is turn, stretch, turn, and its biggest pieces are its best low-rank copy, with reflections allowed and rectangular singular-value blocks. Some trained weights and gradients concentrate in strong directions. Counting and guessing connect through related cooccurrence statistics; smoothed negative sampling gives a generalized shifted PMI. And in high dimensions, independent random directions are nearly perpendicular. Random projections can preserve squared distances with stated probability, and low rank helps fill empty tables.

All of it comes back. Part 4 builds the chain rule that computes every gradient. Part 9 keeps each layer's stretch near one, so that deep networks train at all. Part 11 builds Muon, steepest descent in the spectral norm. Part 13 writes attention as dot products, in einsum. Part 15 squeezes a long context's memory through low rank, Part 27 fine-tunes through it, and Part 30 reads and steers the directions inside a model.

Here are eight problems to try, from the triangle inequality to the Johnson-Lindenstrauss proof. Pause here, and work through them; full solutions are in this part's notes.

Next time: change. Everything in this part stood still, except in the chapters that trained something, where we took gradients on trust. Part 4 builds derivatives, the chain rule, and the machine that runs it backwards through billions of numbers at once.

For more, Gilbert Strang's Linear Algebra and Learning from Data is a friendly companion, Trefethen and Bau explain why the order of arithmetic matters, and Roman Vershynin's High-Dimensional Probability explains why big spaces behave the way they do. Thanks for watching, and see you in Part 4.

Where it goes next. Part 4 builds the chain rule that computes every gradient. Part 9 keeps each layer's stretch near one, Part 11 builds Muon as steepest descent in the spectral norm, Part 13 writes attention in einsum, Part 15 squeezes memory through low rank, Part 27 fine-tunes through it (LoRA), and Part 30 reads and steers the directions inside a model.

Key results

The part's results in one place, for revision.

The dot product\(\displaystyle \mathbf a\cdot\mathbf b=|\mathbf a|\,|\mathbf b|\cos\theta,\qquad\allowbreak |\mathbf a\cdot\mathbf b|\le|\mathbf a|\,|\mathbf b|\)
Projection\(\displaystyle P=A(A^\top A)^{-1}A^\top,\qquad\allowbreak P^2=P=P^\top\)
Singular values\(\displaystyle A=U\Sigma V^\top,\qquad\allowbreak \|A\|_2=\sigma_1,\qquad\allowbreak \|A\|_F^2=\sum_i\sigma_i^2\)
Eckart-Young\(\displaystyle \min_{\operatorname{rank}B\le k}\|A-B\|_F^2=\sum_{i>k}\sigma_i^2,\qquad\allowbreak \text{attained }\allowbreak \text{by } A_k=\sum_{i\le k}\sigma_i\,\mathbf u_i\mathbf v_i^\top\)
Power iteration\(\displaystyle \mathbf x_{t+1}=\frac{A\mathbf x_t}{|A\mathbf x_t|}:\qquad\allowbreak \text{the }\allowbreak \text{error }\allowbreak \text{shrinks }\allowbreak \text{by } |\lambda_2/\lambda_1| \text{ per }\allowbreak \text{step}\)
High dimensions\(\displaystyle \operatorname{Var}(\cos\theta)=\frac1d;\qquad\allowbreak k\ge\frac{4\ln n}{\varepsilon^2/2-\varepsilon^3/3}\ \text{dimensions }\allowbreak \text{keep } n\text{ points' }\allowbreak \text{squared }\allowbreak \text{distances }\allowbreak \text{within } 1\pm\varepsilon\)

Try it

Lab 3 · Power iteration and the best low-rank copy

Build a 60 x 80 matrix with six strong directions under noise. Run power iteration on its Gram matrix and compare the measured convergence rate with the eigenvalue ratio; then check that the rank-k truncation of the SVD has error equal to the dropped singular values and beats 400 other rank-k matrices.

Figure produced by Lab 3: Power iteration and the best low-rank copy
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.ai.labs 3 needs numpy, scipy, matplotlib · download lab03.py · source on GitHub
largest singular values                    9.951, 7.997   (eigenvalue ratio of the Gram matrix 0.6457)
power iteration: error factor per step     0.6458   (predicted 0.6457)
Rayleigh quotient: error factor per step   0.4170   (predicted 0.4170, the square)
singular value from the Rayleigh quotient  9.9514675544   (SVD 9.9514675544)
rank 6: squared error / total              0.01884   (dropped singular values 0.01884)
rank 6: best of 200 nudged rivals          0.02291;   random subspaces average 0.902

Multiplying by the matrix over and over finds its top direction at the rate set by the ratio of the top two eigenvalues, and cutting the SVD at rank k leaves exactly the dropped singular values as error, which no other rank-k matrix improves on.
The code (98 lines; it asserts its own result)
"""Lab 3: find the top singular direction by power iteration, and test Eckart-Young against random competitors."""

import numpy as np

from videos.coursekit import labs

TITLE = "Power iteration and the best low-rank copy"
GOAL = ("Build a 60 x 80 matrix with six strong directions under noise. Run power iteration on its Gram matrix and "
        "compare the measured convergence rate with the eigenvalue ratio; then check that the rank-k truncation of "
        "the SVD has error equal to the dropped singular values and beats 400 other rank-k matrices.")
TASKS = [
    "Set the two largest singular values to 10 and 9.9. How many steps does power iteration now need, and what "
    "does the Rayleigh quotient still get right?",
    "Raise the noise from 0.3 to 3. At what rank does the error curve stop falling quickly, and why?",
    "Replace the Frobenius norm by the spectral norm (np.linalg.norm(X, 2)) and check that the rank-k error is "
    "the next singular value.",
]
STRONG = np.array([10.0, 8.0, 6.0, 4.5, 3.0, 2.0])


def orthonormal(rng, n, k):
    return np.linalg.qr(rng.standard_normal((n, k)))[0]


def run(seed=0):
    rng = np.random.default_rng(seed)
    m, n, steps = 60, 80, 45
    A = orthonormal(rng, m, 6) @ np.diag(STRONG) @ orthonormal(rng, n, 6).T + 0.3 * rng.standard_normal((m, n)) / np.sqrt(n)
    U, sig, Vt = np.linalg.svd(A, full_matrices=False)  # the reference: LAPACK's SVD
    lab = labs.Lab()

    # Power iteration on G = A^T A, whose eigenvalues are the squared singular values.
    G, x = A.T @ A, rng.standard_normal(n)
    x /= np.linalg.norm(x)
    angle, gap = [], []
    for _ in range(steps):
        x = G @ x
        x /= np.linalg.norm(x)
        angle.append(np.linalg.norm(x - (x @ Vt[0]) * Vt[0]))  # the sine of the angle to the true direction
        gap.append(sig[0] ** 2 - x @ G @ x)  # the Rayleigh quotient, from below
    angle, gap, t = np.array(angle), np.array(gap), np.arange(1, steps + 1)
    window = slice(8, 28)  # after the transient, before round-off
    rate = np.exp(np.polyfit(t[window], np.log(angle[window]), 1)[0])
    rate_rq = np.exp(np.polyfit(t[window], np.log(gap[window]), 1)[0])
    ratio = (sig[1] / sig[0]) ** 2
    lab.row("largest singular values", f"{sig[0]:.3f}, {sig[1]:.3f}   (eigenvalue ratio of the Gram matrix {ratio:.4f})")
    lab.row("power iteration: error factor per step", f"{rate:.4f}   (predicted {ratio:.4f})")
    lab.row("Rayleigh quotient: error factor per step", f"{rate_rq:.4f}   (predicted {ratio ** 2:.4f}, the square)")
    lab.row("singular value from the Rayleigh quotient", f"{np.sqrt(x @ G @ x):.10f}   (SVD {sig[0]:.10f})")
    assert abs(rate / ratio - 1) < 0.03, "the direction converges at lambda_2 / lambda_1"
    assert abs(rate_rq / ratio ** 2 - 1) < 0.05, "the Rayleigh quotient converges at the squared rate"
    assert abs(np.sqrt(x @ G @ x) - sig[0]) < 1e-8

    # Eckart-Young: the truncated SVD against other rank-k matrices.
    total = (sig ** 2).sum()
    ranks = np.arange(0, 13)
    svd_err, random_err, near_err = [], [], []
    for k in ranks:
        Ak = (U[:, :k] * sig[:k]) @ Vt[:k]
        err = np.linalg.norm(A - Ak, "fro") ** 2
        assert abs(err - (sig[k:] ** 2).sum()) < 1e-9 * total, "the error is the tail of the singular values"
        svd_err.append(err)
        if k == 0:
            random_err.append(err)
            near_err.append(err)
            continue
        rivals, near = [], []
        for _ in range(200):
            Q = orthonormal(rng, m, k)  # the best copy of A whose columns lie in a random k-dimensional subspace
            rivals.append(np.linalg.norm(A - Q @ (Q.T @ A), "fro") ** 2)
            Q = np.linalg.qr(U[:, :k] + 0.01 * rng.standard_normal((m, k)))[0]  # ... and in a nudged optimal one
            near.append(np.linalg.norm(A - Q @ (Q.T @ A), "fro") ** 2)
        assert min(rivals) > err and min(near) > err, "no rank-k competitor beats the truncated SVD"
        random_err.append(np.mean(rivals))
        near_err.append(np.min(near))
    svd_err, random_err, near_err = (np.array(v) / total for v in (svd_err, random_err, near_err))
    lab.row("rank 6: squared error / total", f"{svd_err[6]:.5f}   (dropped singular values {(sig[6:] ** 2).sum() / total:.5f})")
    lab.row("rank 6: best of 200 nudged rivals", f"{near_err[6]:.5f};   random subspaces average {random_err[6]:.3f}")
    assert svd_err[6] < 0.02 < svd_err[3], "six directions carry the matrix; three do not"
    lab.note = ("Multiplying by the matrix over and over finds its top direction at the rate set by the ratio of the "
                "top two eigenvalues, and cutting the SVD at rank k leaves exactly the dropped singular values as "
                "error, which no other rank-k matrix improves on.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    ax[0].semilogy(t, angle, color=labs.BLUE, label="angle to the top direction (sine)")
    ax[0].semilogy(t, np.maximum(gap, 1e-15) / sig[0] ** 2, color=labs.GOLD, label="Rayleigh quotient's relative gap")
    ax[0].semilogy(t, angle[8] * ratio ** (t - 9.0), "--", color=labs.MUTED, lw=1, label=r"slopes $\lambda_2/\lambda_1$ and its square")
    ax[0].semilogy(t, gap[8] / sig[0] ** 2 * ratio ** (2 * (t - 9.0)), "--", color=labs.MUTED, lw=1)
    ax[0].set(title="Power iteration on the Gram matrix", xlabel="step", ylabel="error", ylim=(1e-17, 3))
    ax[0].legend(loc="upper right")
    ax[1].plot(ranks, random_err, "o-", ms=4, color=labs.RED, label="random k-dimensional subspace (mean of 200)")
    ax[1].plot(ranks, near_err, "o-", ms=4, color=labs.BLUE, label="nudged optimal subspace (best of 200)")
    ax[1].plot(ranks, svd_err, "o-", ms=4, color=labs.GREEN, label="truncated SVD = dropped singular values")
    ax[1].set(title="Squared error of rank-k copies, as a share of the whole", xlabel="rank k", ylabel="relative squared error",
              yscale="log")
    ax[1].legend(loc="center right")
    lab.fig = fig
    return lab

Now change it

  1. Set the two largest singular values to 10 and 9.9. How many steps does power iteration now need, and what does the Rayleigh quotient still get right?
  2. Raise the noise from 0.3 to 3. At what rank does the error curve stop falling quickly, and why?
  3. Replace the Frobenius norm by the spectral norm (np.linalg.norm(X, 2)) and check that the rank-k error is the next singular value.

Problems, with solutions

Try each problem before opening its solution.

  1. Triangle inequality. Use Cauchy–Schwarz to prove the triangle inequality \(|\mathbf{a} + \mathbf{b}| \le |\mathbf{a}| + |\mathbf{b}|\), and find when it is an equality.

    Solution

    |a + b|² = |a|² + 2a·b + |b|² ≤ |a|² + 2|a||b| + |b|² = (|a| + |b|)², by Cauchy–Schwarz. Equality needs a·b = |a||b|: one vector a non-negative multiple of the other.

  2. Projections. For \(A\) with full column rank, show that \(P = A(A^{\top}A)^{-1}A^{\top}\) satisfies \(P^2 = P = P^{\top}\), and that \(I - P\) projects onto the vectors perpendicular to every column of \(A\).

    Solution

    For A with full column rank, P² = A(AᵀA)⁻¹AᵀA(AᵀA)⁻¹Aᵀ = A(AᵀA)⁻¹Aᵀ = P, and Pᵀ = A((AᵀA)⁻¹)ᵀAᵀ = P because AᵀA is symmetric. For any y, Aᵀ(I − P)y = Aᵀy − AᵀA(AᵀA)⁻¹Aᵀy = 0, so (I − P)y is perpendicular to every column; and (I − P)² = I − 2P + P² = I − P.

  3. Rayleigh quotient near an eigenvector. For symmetric \(A\) with \(\lambda_1 > \lambda_2\), show that \(R(\mathbf{v}_1 + \varepsilon\mathbf{v}_2) = \lambda_1 - (\lambda_1 - \lambda_2)\varepsilon^2 + O(\varepsilon^4)\) for unit eigenvectors: why the eigenvalue converges twice as fast as the vector.

    Solution

    With unit v₁ ⊥ v₂ and x = v₁ + εv₂: xᵀAx = λ₁ + ε²λ₂ and xᵀx = 1 + ε², so R = (λ₁ + ε²λ₂)/(1 + ε²) = λ₁ − (λ₁ − λ₂)ε²/(1 + ε²) = λ₁ − (λ₁ − λ₂)ε² + O(ε⁴). An error ε in direction moves R by ε²; power iteration's direction error shrinks like (λ₂/λ₁)ᵏ, so the eigenvalue's shrinks like (λ₂/λ₁)²ᵏ.

  4. Norms. Prove \(\|A\|_F^2 = \sum_i \sigma_i^2\) and \(\|A\|_2 \le \|A\|_F \le \sqrt{r}\,\|A\|_2\), and find matrices that attain each bound.

    Solution

    ‖A‖_F² = Σᵢⱼ aᵢⱼ² = tr(AᵀA) = tr(VΣ²Vᵀ) = tr(Σ²) = Σσᵢ². Then σ₁² ≤ Σσᵢ² ≤ rσ₁². The first bound is attained by rank-one matrices (uvᵀ), the second by matrices with r equal singular values (any multiple of an orthogonal matrix, or of a partial isometry).

  5. SGNS optimum. Maximize \(\ell(x) = a\log\sigma(x) + b\log\sigma(-x)\) over \(x\) for \(a, b > 0\). For \(P_n(c)=P(c)\), recover Levy and Goldberg's \(\mathbf{w}\cdot\mathbf{c} = \mathrm{PMI}(w, c) - \log k\).

    Solution

    For a, b > 0 and a free scalar x, ℓ(x) = a log σ(x) + b log σ(−x) has ℓ′(x) = a(1 − σ(x)) − bσ(x) = aσ(−x) − bσ(x), zero when σ(x)/σ(−x) = eˣ = a/b, and ℓ″ < 0 there (it is the maximum of the log-likelihood; the loss −ℓ is minimized). With a = #(w,c) and b = k·#(w)·P_n(c): w·c = log(#(w,c)/(#(w)P_n(c))) − log k, the PMI with the negative distribution as P(c), shifted by log k.

  6. Random directions. For \(\mathbf{x}, \mathbf{y}\) independent and uniform on the unit sphere in \(\mathbb{R}^d\), show \(\mathbb{E}[x_1^2] = 1/d\) and \(\operatorname{Var}(\mathbf{x}\cdot\mathbf{y}) = 1/d\).

    Solution

    By symmetry E[x₁²] = … = E[x_d²] and they sum to E|x|² = 1, so each is 1/d. For independent uniform x, y: E[x·y] = 0 and E[(x·y)²] = E[yᵀ E[xxᵀ] y] = E[yᵀ (I/d) y] = 1/d.

  7. χ² moment generating function. If \(X \sim \chi^2_k\), show \(\mathbb{E}\,e^{tX} = (1 - 2t)^{-k/2}\) for \(t < 1/2\), and finish the optimization over \(t\) in the Johnson–Lindenstrauss proof.

    Solution

    For Z ~ N(0,1), E[e^{tZ²}] = ∫ e^{tz²} e^{−z²/2}/√(2π) dz = (1 − 2t)^{−1/2} for t < 1/2, and the k squares are independent: (1 − 2t)^{−k/2}. Markov gives P(X ≥ (1+ε)k) ≤ e^{−tk(1+ε)}(1 − 2t)^{−k/2}; minimizing over t gives 1 − 2t = 1/(1 + ε), i.e. t = ε/(2(1 + ε)), and the bound ((1 + ε)e^{−ε})^{k/2}. With ln(1 + ε) ≤ ε − ε²/2 + ε³/3: ≤ exp(−k(ε²/2 − ε³/3)/2).

  8. A rank-k picture. A rank-\(k\) copy of an \(m \times n\) picture stores \(k(m + n + 1)\) numbers. For \(180 \times 288\), up to what \(k\) does it save space, and what does Eckart–Young say its error is?

    Solution

    k(m + n + 1) < mn means k < 51,840/469 ≈ 110.5: up to k = 110 it saves space. Its error is (σ²_{k+1} + … + σ²_r)^{1/2}, the singular values left out, exactly, and no other rank-k matrix does better.

Notes and sources

Sources

Books: G. Strang, Linear Algebra and Learning from Data (2019); S. Axler, Linear Algebra Done Right, 4th ed. (2024); L. N. Trefethen and D. Bau, Numerical Linear Algebra (1997); R. Vershynin, High-Dimensional Probability (2018).

History: H. Grassmann, Die lineale Ausdehnungslehre (1844); J. J. Sylvester (1850); A. Cayley, A Memoir on the Theory of Matrices (1858); E. Beltrami (1873); C. Jordan (1874); E. Schmidt (1907); H. Weyl (1912); G. W. Stewart, On the Early History of the Singular Value Decomposition, SIAM Review (1993).

Numerical linear algebra: A. M. Legendre (1805), C. F. Gauss (1809) on least squares; J. P. Gram (1883); A. S. Householder, Unitary Triangularization of a Nonsymmetric Matrix (1958); R. von Mises and H. Pollaczek-Geiringer (1929); C. Lanczos (1950); G. Golub and W. Kahan (1965); C. Eckart and G. Young, Psychometrika (1936).

Random matrices and training: E. Wigner (1955); V. Marchenko and L. Pastur (1967); A. Clauset, C. Shalizi and M. Newman, Power-law distributions in empirical data (2009); C. Martin and M. Mahoney, Heavy-Tailed Universality Predicts Trends in Test Accuracies (2019) and Implicit Self-Regularization in Deep Neural Networks, JMLR (2021); T. Miyato et al., Spectral Normalization for GANs (2018); E. Hu et al., LoRA (2021); J. Zhao et al., GaLore (ICML 2024); K. Jordan et al., Muon (2024); J. Bernstein and L. Newhouse, Old Optimizer, New Norm (2024); O. Roy and M. Vetterli, The effective rank (2007).

Words: Z. Harris, Distributional Structure (1954); J. R. Firth (1957); S. Deerwester et al., Indexing by Latent Semantic Analysis (1990); T. Mikolov et al. (2013a, b); T. Mikolov, W. Yih and G. Zweig (2013); J. Pennington, R. Socher and C. Manning, GloVe (2014); O. Levy and Y. Goldberg, Neural Word Embedding as Implicit Matrix Factorization (2014); O. Levy, Y. Goldberg and I. Dagan, Improving Distributional Similarity with Lessons Learned from Word Embeddings (2015).

High dimensions: W. Johnson and J. Lindenstrauss (1984); S. Dasgupta and A. Gupta, An Elementary Proof of a Theorem of Johnson and Lindenstrauss (2003); K. G. Larsen and J. Nelson, Optimality of the Johnson–Lindenstrauss Lemma (2017); N. Elhage et al., Toy Models of Superposition (2022).

GPT-2's geometry: A. Radford et al., Language Models are Unsupervised Multitask Learners (2019); J. Mu and P. Viswanath, All-but-the-Top (2018); J. Gao et al., Representation Degeneration Problem in Training Natural Language Generation Models (2019); K. Ethayarajh, How Contextual are Contextualized Word Representations? (2019); W. Timkey and M. van Schijndel, All Bark and No Bite: Rogue Dimensions in Transformer Language Models (2021); K. Park, Y. J. Choe and V. Veitch, The Linear Representation Hypothesis and the Geometry of Large Language Models (2024).

Recommendation and retrieval: J. Bennett and S. Lanning, The Netflix Prize (2007); Y. Koren, R. Bell and C. Volinsky, Matrix Factorization Techniques for Recommender Systems (2009); A. Feuerverger, Y. He and S. Khatri, Statistical Significance of the Netflix Challenge (2012); P. Covington, J. Adams and E. Sargin, Deep Neural Networks for YouTube Recommendations (2016); J. Johnson, M. Douze and H. Jégou, Billion-scale similarity search with GPUs (2017); X. Yi et al., Sampling-Bias-Corrected Neural Modeling for Large Corpus Item Recommendations (2019); V. Karpukhin et al., Dense Passage Retrieval (2020).

About this partfrom its README

Part 3 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan and the syllabus). Part 1's counting model could not tell the dog barked from the hound barked; this part gives words a place in a space and builds the linear algebra that every later part works in: the dot product, einsum, projections, eigenvectors, the SVD and low rank, norms and conditioning, random matrices and what training writes into weights, word vectors from counting and from guessing, the geometry of high dimensions, and low rank at work in recommendation and retrieval. Every derivation is on screen step by step; every number is computed here (compute.py) on a CPU, small enough for a laptop.

A hook, seventeen chapters and an outro (about 50 minutes; python tools/lecture_length.py ai3).

Chapter notes
  • Hook: where words live. Two contexts as islands; 102 words where GPT-2 puts them (its 50,257 × 768 embedding matrix on the words' top three principal directions), seven categories apart; dog, puppy, tobacco as 768 numbers each. How we got here: Grassmann (1844), Cayley (1858), Beltrami and Jordan (1873–74), Hilbert (1904), Eckart and Young (1936), Firth (1957), Johnson and Lindenstrauss (1984), latent semantic analysis (1990), the Netflix Prize (2006), word2vec (2013), LoRA (2021), GaLore and Muon (2024).
  • 1. Vectors and the inner product. Arrows and lists; addition, scaling, a basis; Grassmann. The dot product, derived as |a||b|cos θ from the law of cosines; the Cauchy–Schwarz inequality proved from a parabola's discriminant, the parabola drawn as one vector turns. Cosine similarity of GPT-2's vectors; GPT-2's logits are dot products with its own (tied) token vectors (after "The Eiffel Tower is located in the city of": Paris first).
  • 2. Tensors and einsum. Arrays with named axes; Einstein's summation convention (1916) as einsum: kept and summed indices, and cost as the product of all index sizes. Six operations in one notation. Attention as four contractions at GPT-2's size, with their multiply-add counts. (AB)C against A(BC): the same answer, fifty times apart in cost.
  • 3. Matrices move space. Linear maps, columns as the images of the basis, composition and order (Cayley 1858, Sylvester's word matrix 1850), the determinant as area, rank, column space and null space, rank–nullity.
  • 4. Projection and least squares. Projection onto a line and onto a column space derived (the normal equations, P = A(AᵀA)⁻¹Aᵀ, P² = P = Pᵀ); Legendre (1805) and Gauss (1809); a line fitted, with the error perpendicular to both columns; Gram–Schmidt and QR. Computed: classical and modified Gram–Schmidt against Householder QR, and the normal equations against QR, on Hilbert matrices as the condition number grows (loss of orthogonality ∝ κ², ∝ κ, and at round-off).
  • 5. Directions that stay put. Eigenvectors and the characteristic polynomial; symmetric matrices as turn, stretch, turn back; the spectral theorem proved in three steps (real eigenvalues, perpendicular eigenvectors, induction on the perpendicular space; Cauchy 1829, Hilbert 1904–10); the Rayleigh quotient as a weighted average of eigenvalues, swept around the circle; principal components (Pearson 1901, Hotelling 1933).
  • 6. Power iteration, run live. Abel–Ruffini: no formula, so iterate; the arrow swinging onto the top eigenvector; the convergence rate (λ₂/λ₁)ᵏ derived, and the Rayleigh quotient's doubled rate. Computed on GPT-2's 768 × 768 token covariance and Part 1's letter table: the measured rates match λ₂/λ₁. Von Mises and Pollaczek-Geiringer (1929), PageRank (1998), spectral normalization (2018), Lanczos (1950).
  • 7. The singular value decomposition. Circle to ellipse in three stages (Vᵀ, Σ, U); the SVD derived from the spectral theorem applied to AᵀA; Beltrami, Jordan, Schmidt, Golub and Kahan; the spectral norm as the longest image of a unit vector, swept.
  • 8. The best low-rank copy. A matrix as a sum of rank-one pieces; the Eckart–Young theorem proved from Weyl's inequality; a landscape drawn by code sharpening rank by rank (the error equals the tail of the singular values, checked); Part 1's letter table, and correspondence analysis putting the vowels at one end; LSA, LoRA and latent attention.
  • 9. How big is a matrix? Frobenius and spectral norms; ‖A‖_F² = Σσᵢ² derived; stable rank. Computed: the stable ranks of all 48 matrices in GPT-2's blocks against a single random 768 × 3072 MLP-shaped reference (stable rank ≈ 345). A vector through 40 random layers (gains 0.8, 1.0, 1.2). The condition number derived as an error amplifier, and measured for 64- and 32-bit arithmetic. Muon as steepest descent in the spectral norm; Newton–Schulz on a real gradient.
  • 10. Random matrices and trained weights. Wigner (1955) and the Marchenko–Pastur law (1967), checked on a random 768 × 3072 matrix; GPT-2's layer-6 MLP matrix: a bulk plus eigenvalues escaping the edge, which vanish when the same numbers are shuffled; power-law tails fitted (Clauset–Shalizi–Newman) for all 48 matrices against Martin and Mahoney's range; the novels model at initialization and after training.
  • 11. Gradients are low rank. A layer's gradient as a sum of outer products, derived; a small transformer trained on the novels, its gradient's singular values replayed through training; GaLore (2024): Adam in a rank-r window, memory counted, trained against Adam at three learning rates and three seeds, with a control (Adam with GaLore's step sizes); LoRA against GaLore: the effective rank of the total change.
  • 12. Word vectors from counting. Harris (1954), Firth (1957), latent semantic analysis (1990); the novels' co-occurrence table (10,000 words, window 4), PPMI, truncated SVD to 100 numbers; neighbours; meaning arriving direction by direction; analogies, and a test of 710 analogy questions built from the books, and category neighbours.
  • 13. word2vec is counting in disguise. Skip-gram with negative sampling (Mikolov et al. 2013) trained on the same books and replayed; Levy and Goldberg's theorem (2014) derived as a generalized shifted-PMI target for the smoothed negative distribution (ordinary PMI − log k when negatives follow the empirical context distribution). Finite optimization fits are measured at full rank on the 300 commonest words, at ranks 30 and 5, and on the real 10,000-word run; full rank does not certify convergence to the target. GloVe (2014); counting against guessing on the same tests.
  • 14. Life in 768 dimensions. Angles between random directions; Var(cos θ) = 1/d derived and measured from d = 2 to 4,096; in the measured 768-dimensional draw, all pairs among 10,000 random directions lie between 78° and 102° (typical angular spread ≈ 2°), and superposition; lengths concentrating at √d with spread 1/√2, derived and measured; the volume in a thin shell.
  • 15. Johnson–Lindenstrauss, proved. A thousand of GPT-2's vectors through one random matrix; the lemma (Dasgupta–Gupta form) and its proof: Gaussian projection, χ² variable, Chernoff bound, union bound. Checked: the per-pair failure rate on all 499,500 pairs against the exact χ² tail; the worst pair against a separate explicit 95%-confidence union bound, with unavailable nontrivial bounds reported honestly; Larsen and Nelson's optimality (2017).
  • 16. GPT-2's lopsided space. Anisotropy (mean cosine of random tokens), the fix by centring, the top principal directions and what the first one tracks (token id, a proxy for frequency); all-but-the-top (Mu and Viswanath 2018); representation degeneration (Gao et al. 2019); layer by layer inside the network (Ethayarajh 2019) and rogue dimensions (Timkey and van Schijndel 2021); the linear representation hypothesis (Mikolov, Yih and Zweig 2013; Elhage et al. 2022; Park, Choe and Veitch 2024); Part 30.
  • 17. Low rank in the wild. The Netflix Prize (2006–09); matrix factorization with biases on a synthetic ratings world (4,000 users, 1,200 films, six hidden genres), trained by gradient descent and replayed: held-out error with and without the vector penalty (both retain the same bias penalty), by rank over three seeds against baselines fitted on the same ratings, and measured genre structure in film vectors whose training never used genre labels. Two-tower retrieval trained with an in-batch softmax and a negative-sampling correction: in the ideal candidate-classification calculation, the corrected training logit models a density ratio and the raw score models conditional log probability up to a user constant. Inference ranks raw scores; adding a popularity prior is a separate ablation. Measured macro recall@10 compares eligible known and brand-new users against popularity, with unavailable cohorts reported explicitly; YouTube (2016), FAISS (2017), dense passage retrieval (2020).
  • Outro. Twelve recap tiles from the part's own results; where it comes back (Parts 4, 9, 11, 13, 15, 27, 30); eight problems; Part 4's teaser; references.
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Vectors, inner products, Cauchy–Schwarz.
  2. Tensors and einsum (the notation attention uses).
  3. Matrices as maps; projection and Gram–Schmidt; P = A(AᵀA)⁻¹Aᵀ.
  4. Eigenvalues; the spectral theorem (proof sketch); the Rayleigh quotient; power iteration, run live.
  5. SVD derived from AᵀA; Eckart–Young.
  6. Spectral vs Frobenius norm; condition number (Muon needs the spectral norm).
  7. Random matrices: Marchenko–Pastur vs the heavy-tailed spectra of trained weights; low-rank gradients (GaLore).
  8. Word vectors from counting; SGNS factorizes shifted PMI (Levy and Goldberg 2014), checked.
  9. High dimensions: shell concentration, near-orthogonality with variance 1/d derived.
  10. Johnson–Lindenstrauss, proved (Gaussian projection, χ² tail, union bound).
  11. GPT-2's embedding geometry and anisotropy.
  12. Low rank in the wild: the Netflix Prize (2006–09), matrix factorization and collaborative filtering; two-tower retrieval.

Visuals: circle → ellipse in three SVD stages; an image mosaic sharpening rank by rank; the MP law vs a trained layer's spectrum.

中文讲义

本讲的中文部分(与英文版对应)。

题目与解答
  1. 三角不等式。 |a + b|² = |a|² + 2a·b + |b|² ≤ |a|² + 2|a||b| + |b|² = (|a| + |b|)²,用的是柯西–施瓦茨不等式。取等号要求 a·b = |a||b|:一个向量是另一个的非负倍数。
  2. 投影。 若 A 列满秩,P² = A(AᵀA)⁻¹AᵀA(AᵀA)⁻¹Aᵀ = P;因为 AᵀA 对称,Pᵀ = P。对任意 y,Aᵀ(I − P)y = Aᵀy − Aᵀy = 0,所以 (I − P)y 与每一列都垂直;并且 (I − P)² = I − 2P + P² = I − P。
  3. 特征向量附近的瑞利商。 取单位向量 v₁ ⊥ v₂,x = v₁ + εv₂:xᵀAx = λ₁ + ε²λ₂,xᵀx = 1 + ε²,所以 R = λ₁ − (λ₁ − λ₂)ε²/(1 + ε²) = λ₁ − (λ₁ − λ₂)ε² + O(ε⁴)。方向误差 ε 只让 R 变化 ε²;幂迭代的方向误差按 (λ₂/λ₁)ᵏ 缩小,特征值的误差就按 (λ₂/λ₁)²ᵏ 缩小。
  4. 范数。 ‖A‖_F² = Σᵢⱼ aᵢⱼ² = tr(AᵀA) = tr(Σ²) = Σσᵢ²,所以 σ₁² ≤ Σσᵢ² ≤ rσ₁²。秩为一的矩阵 uvᵀ 取到左边的等号; r 个奇异值都相等的矩阵(正交矩阵的倍数)取到右边的等号。
  5. SGNS 的最优点。 对 a, b > 0 及自由标量 x,ℓ(x) = a log σ(x) + b log σ(−x),ℓ′(x) = aσ(−x) − bσ(x),在 eˣ = a/b 时为零,且 ℓ″ < 0(这是对数似然的 最大值,损失 −ℓ 的最小值)。代入 a = #(w,c),b = k·#(w)·P_n(c):w·c = log(#(w,c)/(#(w)P_n(c))) − log k,即以负采样分布为 P(c) 的点互信息,平移 log k。
  6. 随机方向。 由对称性,E[x₁²] = … = E[x_d²],它们的和是 E|x|² = 1,所以每个都是 1/d。x、y 独立且均匀时,E[x·y] = 0, E[(x·y)²] = E[yᵀ(I/d)y] = 1/d。
  7. χ² 的矩母函数。 Z ~ N(0,1) 时,E[e^{tZ²}] = (1 − 2t)^{−1/2}(t < 1/2),k 个独立平方相乘得 (1 − 2t)^{−k/2}。马尔可夫不等式 给出 P(X ≥ (1+ε)k) ≤ e^{−tk(1+ε)}(1 − 2t)^{−k/2};对 t 求最小,得 t = ε/(2(1 + ε)),界为 ((1 + ε)e^{−ε})^{k/2};再用 ln(1 + ε) ≤ ε − ε²/2 + ε³/3,得 ≤ exp(−k(ε²/2 − ε³/3)/2)。
  8. 秩为 k 的图片。 k(m + n + 1) < mn,即 k < 51840/469 ≈ 110.5:k 不超过 110 就能省空间。误差恰好是略去的奇异值 (σ²_{k+1} + … + σ²_r)^{1/2},而且没有别的秩为 k 的矩阵比它更好。
术语
English 中文
vector, basis, coordinates 向量,基,坐标
dot product (inner product) 点积(内积)
law of cosines 余弦定理
Cauchy–Schwarz inequality 柯西–施瓦茨不等式
cosine similarity 余弦相似度
tensor, axis, einsum, contraction 张量,轴,einsum,缩并
Einstein summation convention 爱因斯坦求和约定
linear map, column space, null space, rank 线性映射,列空间,零空间,秩
rank–nullity theorem 秩–零化度定理
determinant 行列式
orthogonal projection, projection matrix 正交投影,投影矩阵
least squares, normal equations 最小二乘,正规方程
Gram–Schmidt process, QR factorization, Householder reflection 格拉姆–施密特方法,QR分解,豪斯霍尔德反射
orthonormal basis 标准正交基
eigenvalue, eigenvector, characteristic polynomial 特征值,特征向量,特征多项式
spectral theorem 谱定理
Rayleigh quotient 瑞利商
principal component 主成分
power iteration, Krylov method 幂迭代,克雷洛夫方法
singular value decomposition (SVD), singular value 奇异值分解(SVD),奇异值
Eckart–Young theorem, Weyl's inequality 埃卡特–杨定理,外尔不等式
low rank, rank-one matrix 低秩,秩一矩阵
Frobenius norm, spectral norm, stable rank 弗罗贝尼乌斯范数,谱范数,稳定秩
condition number 条件数
Newton–Schulz iteration 牛顿–舒尔茨迭代
Marchenko–Pastur law, semicircle law 马尔琴科–帕斯图尔定律,半圆律
empirical spectral density, heavy tail, power-law exponent 经验谱密度,重尾,幂律指数
gradient low-rank projection (GaLore) 梯度低秩投影(GaLore)
effective rank 有效秩
distributional hypothesis 分布假说
co-occurrence, pointwise mutual information (PMI), PPMI 共现,点互信息(PMI),正点互信息(PPMI)
latent semantic analysis (LSA) 潜在语义分析(LSA)
skip-gram with negative sampling (SGNS), word2vec, GloVe 带负采样的跳字模型(SGNS),word2vec,GloVe
analogy (3CosAdd) 类比(3CosAdd)
concentration of measure, thin shell 测度集中,薄壳
Johnson–Lindenstrauss lemma, random projection 约翰逊–林登斯特劳斯引理,随机投影
chi-squared distribution, Chernoff bound, union bound 卡方分布,切尔诺夫界,联合界
anisotropy, centring, all-but-the-top 各向异性,中心化,去掉顶部方向
rogue dimension 离群维度
linear representation hypothesis, superposition 线性表示假说,叠加
matrix factorization, collaborative filtering 矩阵分解,协同过滤
regularization 正则化
two-tower model, in-batch softmax, recall@k 双塔模型,批内softmax,前k召回率
maximum inner product search, approximate nearest neighbour 最大内积搜索,近似最近邻
dense retrieval 稠密检索

Build the film

python -m videos.ai.ai3.compute        # the part's numbers, into .cache/ai3
python tools/build.py ai3                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai3 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/ai/ai3. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it

From the repo root:

python tools/make.py ai3                       # everything: compute, then English and Chinese builds
python -m videos.ai.ai3.compute                # just the numbers (.cache/ai3), about 1-2 CPU-hours
python -m videos.ai.ai3.compute galore sgns    # specific items; --force to recompute
python tools/build.py ai3                      # English
python tools/build.py ai3 --lang zh            # Chinese

The computation reads GPT-2 small from Hugging Face (openai-community/gpt2, about 500 MB, downloaded once into the Hugging Face cache), Part 1's thirty novels (.cache/ai1, built by Part 1's compute on first use) and the series' novels model (python -m explainer.ai.novels, which make.py runs first if it is missing). Every random choice is seeded; the long items (galore, galorectl, mf) save each finished training run as they go, so an interrupted run resumes. Torch runs with one or two threads, set inside the training functions.