Discover: a puzzle from two thousand years ago
About two thousand years ago, Chinese scholars compiled The Nine Chapters on the Mathematical Art, a handbook of practical problems. Its eighth chapter opens with one about grain. In modern words:
Three bundles of top-grade grain, two of medium grade and one of low grade yield 39 dou of grain. Two top, three medium and one low yield 34 dou. One top, two medium and three low yield 26 dou. How much does one bundle of each grade yield?
Call the yields of one bundle (top), (medium) and (low). The problem becomes three equations in three unknowns:
The scribes laid the numbers out on a counting board, one equation per column of rods, and called the grid a fangcheng, a “rectangular array”. Then they combined columns to wipe out one unknown after another. It is, step for step, the method of this chamber, written down more than fifteen centuries before Gauss was born.
You can try the key move right now.
In the grain problem, subtract the second equation from the first. Which equation do you get?
One subtraction and has vanished. Do that systematically and you can solve any system. This chamber turns the trick into an algorithm, then asks the deeper questions behind it: when does a system have exactly one answer, when can a matrix be undone, and how much does it stretch space? That last question turns out to be the engine of a family of generative models, the normalising flows, which you'll meet at the end.
Learn: two pictures of Ax = b
Stack the coefficients into a matrix and the grain problem becomes one equation, , read “A x equals b”:
There are two ways to see what this equation asks, and you need both.
The row picture. Each equation on its own is a flat shape. In two unknowns, is a line in the plane; in three unknowns, each equation is a plane in space. A solution must lie on all of them at once, so solving means finding where they meet. The lines and cross at the single point .
The column picture. In Chamber 4 you read as a combination of the columns of , weighted by the entries of . So the same system asks: which combination of the columns makes ?
The weights and are the solution again, seen from the other side. The column picture also tells you when a solution exists at all: exactly when lies in the span of the columns (Chamber 3). Chamber 6 gives that span a name.
In the row picture you can see every possible outcome with two lines. They cross once (one solution), they are parallel (no solution), or they are the same line (infinitely many). Three planes in space behave the same way: there are never exactly two solutions, or exactly five.
A system has two different solutions, and . What can you conclude?
Learn: Gaussian elimination
Elimination works on the augmented matrix (“A augmented with b”): the coefficients with the right-hand side attached as an extra column. It never touches the unknowns directly. It only changes rows, and it uses just three row operations:
- “A augmented with b”The augmented matrix: the coefficients of with the right-hand side attached as an extra column. The bar marks where the equals signs were.
- “row i”The -th row of the matrix you're working on. Row operations are written in terms of these.
- “swap rows i and j”Exchange two rows. You need it when a pivot position holds a zero.
- “row i gets c times row i”Scale a row by a non-zero number , usually to make a pivot equal to 1.
- “row i gets row i plus c times row j”Add a multiple of another row. The workhorse of elimination: it creates the zeros below (and above) each pivot, and it never changes the determinant.
- “r r e f of A”The reduced row echelon form of : every pivot is 1, with zeros above and below it. Every matrix has exactly one.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “A augmented with b” | The augmented matrix: the coefficients of with the right-hand side attached as an extra column. The bar marks where the equals signs were. | ||
| “row i” | The -th row of the matrix you're working on. Row operations are written in terms of these. | ||
| “swap rows i and j” | Exchange two rows. You need it when a pivot position holds a zero. | ||
| “row i gets c times row i” | Scale a row by a non-zero number , usually to make a pivot equal to 1. | ||
| “row i gets row i plus c times row j” | Add a multiple of another row. The workhorse of elimination: it creates the zeros below (and above) each pivot, and it never changes the determinant. | ||
| “r r e f of A” | The reduced row echelon form of : every pivot is 1, with zeros above and below it. Every matrix has exactly one. |
Why is this allowed? Because every row operation can be undone by another one: a swap by the same swap, by (which is why is banned), and by . Any solution of the old system also solves the new one, and since the step can be reversed, any solution of the new one solves the old. The set of solutions never changes; only the equations get simpler.
The plan: go column by column, left to right. In each column choose a non-zero pivot, then subtract multiples of the pivot's row to create zeros below it. Here is the grain problem.
- 1
Put a convenient pivot on top
The first pivot could be the , but a keeps the arithmetic clean. Swap rows 1 and 3:
- 2
Clear the first column below the pivot
The multipliers are the entry to be cleared divided by the pivot: and .
- 3
Move to the second column
The second pivot is the . The multiplier for row 3 is :
The matrix is now upper triangular: zeros below the diagonal. The pivots are , and .
- 4
Back substitution, from the bottom up
The last row says , so . The middle row says , so . The top row says , so .
One bundle yields , and dou: the answer printed in the Nine Chapters. Check it in the first equation: .
A pivot must be non-zero, since you divide by it. When the pivot position holds a zero, swap in a row from below that has a non-zero entry there. When there is no such row, that column simply gets no pivot, and as you'll see next, that is where infinitely many solutions (or none) come from.
Learn: echelon forms and the three outcomes
Elimination aims for a staircase shape called row echelon form. A matrix is in row echelon form when
- any all-zero rows sit at the bottom, and
- each row's first non-zero entry, its pivot, is strictly to the right of the pivot in the row above.
It follows that every entry below a pivot is zero. Stopping here and back-substituting is Gaussian elimination. Keep going and you reach the reduced row echelon form, : in addition, every pivot equals and is the only non-zero entry in its column. Clearing upwards as well as downwards like this is called Gauss–Jordan elimination. Every matrix has exactly one reduced row echelon form, however you get there, so it's a fingerprint of the system.
Once is in reduced form, you can read the outcome straight off it:
- Left: a pivot in every column of . Exactly one solution, and the last column is it: .
- Middle: a column without a pivot. Column 2 has no pivot, so is a free variable: choose it freely, say , and the pivot rows fix the rest, and . Infinitely many solutions, : a line. The zero row, , is harmless.
- Right: a pivot in the last column. The bottom row says , that is, . No solution: the system is inconsistent.
That's the whole story, for any number of equations and unknowns. A pivot in the column means none; otherwise, every free column means infinitely many; no free columns means exactly one.
Now do it yourself. The workbench records each operation in the notation above, and it recognises both echelon forms. One of the three systems has a single solution, one has infinitely many and one has none. Reduce all three to find out which is which. If you're stuck, the Hint button loads the next Gauss–Jordan step.
Interactive lab
Row reduction workbench
x₂ + 2x₃ = 7
x₁ + x₂ + x₃ = 6
2x₁ + x₂ − x₃ = 3
Not in echelon form yet
Work column by column, left to right: get a non-zero pivot at the top, then zeros below it.
Operations so far (0)
None yet. Every operation you apply is recorded here in row notation.
A system in three unknowns reduces to What are its solutions?
Learn: undoing a matrix
In Chamber 4, a matrix was a transformation of space. Some transformations can be reversed: rotate by and you can rotate back. Others can't: a projection squashes the plane onto a line, and once two different points land in the same place, no transformation can tell them apart again.
A square matrix is invertible if there is a matrix , read “A inverse”, with
Then every system has exactly one solution, . (You'll put the proof of that together in the last part of this chamber.) A square matrix without an inverse is called singular.
- “A inverse”The matrix that undoes : . Only square matrices can have one, and not all do. It is not the matrix of reciprocals .
- “the n by n identity”Ones on the diagonal, zeros elsewhere: the matrix that changes nothing, . Written just when the size is clear.
- “det A”The determinant of a square matrix: the signed factor by which scales areas (in 2D) or volumes (in 3D and beyond). It is zero exactly when is singular.
- “the determinant of A, written with bars”Another way to write . Careful: in the bars mean absolute value, applied to the number .
- “the Jacobian of f at x”The matrix of partial derivatives , in the notation of the Real NVP paper. Near , behaves like this matrix, so its determinant is 's local volume scale.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “A inverse” | The matrix that undoes : . Only square matrices can have one, and not all do. It is not the matrix of reciprocals . | ||
| “the n by n identity” | Ones on the diagonal, zeros elsewhere: the matrix that changes nothing, . Written just when the size is clear. | ||
| “det A” | The determinant of a square matrix: the signed factor by which scales areas (in 2D) or volumes (in 3D and beyond). It is zero exactly when is singular. | ||
| “the determinant of A, written with bars” | Another way to write . Careful: in the bars mean absolute value, applied to the number . | ||
| “the Jacobian of f at x” | The matrix of partial derivatives , in the notation of the Real NVP paper. Near , behaves like this matrix, so its determinant is 's local volume scale. |
Computing an inverse. The -th column of is the solution of , where is the -th standard basis vector. You could solve systems one at a time, but they share the same , so do them all at once: reduce the wide augmented matrix . If is invertible, the left half becomes and the right half becomes . If elimination runs out of pivots first, is singular.
Let's run that on a general matrix and watch the famous formula appear. (Here is just the top-right entry of the matrix, not a right-hand side.)
- 1
Set up, assuming a ≠ 0 for now
- 2
Clear below the first pivot
Use . The new entry is :
The second pivot is . If there is no second pivot, and has no inverse. From here on, assume .
- 3
Make the second pivot 1
Scale by its reciprocal, :
- 4
Clear above the second pivot
. The new top-left entry on the right is :
- 5
Make the first pivot 1 and read off the inverse
turns the left half into , and the right half is the inverse:
Swap the diagonal, negate the off-diagonal, divide by . (If , swap the rows first; the formula comes out the same.) Always check by multiplying:
That number decides everything: non-zero, the inverse exists; zero, it doesn't. It has a name, and a meaning, which is the subject of the next section.
Inverting a product. Here is a complete proof of a rule you'll use constantly.
Claim. If and are invertible matrices, then is invertible and .
Proof. To show that a matrix is the inverse of , it is enough to check that and : that's the definition. Take . Using associativity (Chamber 4) to regroup,
Both products are , so is the inverse of .
The order reverses for the reason your shoes come off before your socks: means “first , then ”, so undoing it means “first undo , then undo ”. Notice the proof's shape. It didn't derive the answer. It guessed a candidate and verified the definition, a pattern you'll see again and again.
Learn: the determinant as a volume scale
A matrix sends the unit square to the parallelogram spanned by its columns (Chamber 4's picture: the columns are where and land). The determinant, (read “det A”), is the area of that parallelogram, with a sign:
Since the transformation is linear, every region is scaled by the same factor, so is the factor by which scales all areas. For example, sends the unit square to a parallelogram of area , and a circle of area to an ellipse of area . A negative determinant means the transformation also flips orientation, like a mirror. A zero determinant means the parallelogram is flat: the plane has been squashed onto a line, which is exactly the singular case you met in the inverse.
For a matrix the determinant is the signed volume of the box (a parallelepiped) spanned by its three columns. One formula expands along the first row, each entry times the determinant left when you delete its row and column, with alternating signs:
For the grain matrix: .
Expanding like this takes roughly multiplications for an matrix, which is hopeless beyond tiny sizes. Four rules give a far better way:
- Products multiply: . Doing one transformation after another multiplies their scale factors.
- Triangular matrices are easy: the determinant is the product of the diagonal entries.
- Row operations have simple effects: a swap flips the sign, scaling a row by scales the determinant by , and adding a multiple of one row to another changes nothing.
- The identity has determinant .
Put together, elimination computes determinants. It turns into a triangular matrix using only swaps and replacements, so
For the grain problem: one swap and pivots , , give , just as the expansion said. It also explains the central fact of this chamber. exactly when a pivot is missing, which is exactly when elimination can't reach , which is exactly when there is no inverse:
A matrix has . It transforms a triangle of area . What is the area of the transformed triangle?
Why machine learning cares. A normalising flow is a generative model that turns simple noise into data, such as images, through an invertible function. Training it needs the exact probability of each training image, and when an invertible function maps data to noise , probabilities get rescaled by exactly how much stretches volume near :
Spotted in the wild
The matrix inside the determinant is the Jacobian of , its matrix of partial derivatives (Mathematics for Machine Learning, Chamber 7). Near , behaves like that matrix, so its determinant is 's local volume scale. The problem is cost. A small colour image has numbers, so the Jacobian is , and a general determinant of that size costs around twenty billion arithmetic operations, even by elimination. For every image. At every training step.
Real NVP's answer is to design each layer so that its Jacobian is triangular. A coupling layer copies the first inputs unchanged and scales and shifts the rest, using amounts computed from the first . The paper writes out the Jacobian:
Spotted in the wild
Zeros above the diagonal, the identity and a diagonal matrix on it. The complicated bottom-left block, which depends on neural networks, doesn't matter at all: the determinant is the product of the diagonal, , and its logarithm is a plain sum. And because (the paper's Equation 11), a whole stack of layers just adds up their log-determinants. A few facts from this section turn an impossible computation into a cheap one.
Read beyond the course
Each of these covers this chamber's ideas from a different angle. Pick at least one, and mark it read when you're done.
Book · free online · ~45 min
Mathematics for Machine LearningMarc Peter Deisenroth, A. Aldo Faisal & Cheng Soon Ong · Section 2.3, Solving Systems of Linear Equations; Section 4.1, Determinant and Trace
The same material with more formality and more examples, including the “minus-1 trick” for writing down every solution of a system at once. Section 4.1 lists the determinant's properties with the notation machine learning papers use.
Interactive · free online · ~40 min
Immersive Linear AlgebraJacob Ström, Kalle Åström & Tomas Akenine-Möller · Chapter 5, Gaussian Elimination; then Chapter 7, Determinants
A free textbook with interactive figures. In Chapter 7 you can drag the columns of a matrix and watch the area of the parallelogram, and the determinant, change sign as it flips.
Article · free online · ~20 min
Matrices and determinantsJ J O'Connor & E F Robertson, MacTutor History of Mathematics
The story of this chamber's ideas, from the grain problem on a Chinese counting board, through Seki and Leibniz inventing determinants independently, to Gauss's asteroid and Cayley's first abstract definition of a matrix. It's a reminder that notation evolves: the matrices came long after the methods.
Article · free online · ~25 min
Flow-based Deep Generative ModelsLilian Weng · Sections “Linear Algebra Basics Recap” and “RealNVP”
A clear tour of normalising flows that starts from Jacobians and determinants and builds up to Real NVP's coupling layers. Read it right after this chamber, while triangular determinants are fresh.
Papers and lectures
Real NVP is a good first paper about generative models because its central idea is pure linear algebra. You can read the core today. Start with Section 3.1, the change of variable formula (Equations 2 and 3, which you've now seen). Then read Section 3.2 on coupling layers, which defines the layer in Equations 4 and 5, and Section 3.3, where Equation 6 is the triangular Jacobian and Equations 7–8 invert the layer. Finish with the short Section 3.5, whose Equations 11 and 12 are and the socks-and-shoes rule. Skip the masking scheme, the multi-scale architecture, batch normalisation and the experiments for now, but do look at the generated faces and bedrooms in the figures: every one came from inverting a stack of these layers.
Density estimation using Real NVPLaurent Dinh, Jascha Sohl-Dickstein, Samy Bengio · ICLR, 2017The paper that made normalising flows practical for images, by making every layer's Jacobian triangular. Its descendants include Glow and many modern flow-based models.
Decode the paper · Eq. (3), Section 3.1
Density estimation using Real NVPLaurent Dinh, Jascha Sohl-Dickstein, Samy Bengio · ICLR, 2017
Real NVP learns an invertible map from data (an image, say) to a latent code that should look like simple Gaussian noise. This equation, from the paper's section on the change of variable formula, gives the exact log-likelihood of a data point: the number the model maximises during training. Match each symbol to its meaning.
Options
Watch
The best visual explanation of the determinant there is. Watch for the moment a region's area is scaled by the same factor everywhere, and for why a flipped grid gives a negative sign.
Gilbert Strang's second lecture from MIT's 18.06. He runs elimination on a system, then shows that each step is itself a matrix multiplication, an idea that leads to the LU factorisation used inside np.linalg.solve.
Your turn
First, translate between notation, code and the rules of determinants.
Match · Maths ↔ NumPy
From notation to NumPy
Match each piece of notation to the NumPy that computes or performs it. M is an augmented matrix stored as a float array. Remember that NumPy counts rows from 0, so the paper's is M[0].
Options
Match · Operation ↔ Determinant
What happens to the determinant?
Match each operation or matrix to what it does to the determinant (or what its determinant is). All matrices are square.
Options
Proofs
The first proof comes in pieces: put the lines in order and leave out the ones that don't belong. The second you write yourself, and it's short.
Proof puzzle
An invertible matrix gives exactly one solution
Claim
If is an invertible matrix, then for every the system has exactly one solution, namely .
Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.
Your proof
- Pick the first line below.
Available lines
Prove it yourself
A matrix has at most one inverse
Claim
Let be an matrix. If and are both inverses of , that is and , then . (This is why we may speak of the inverse .)
Your typeset proof appears here.
Code it up
Three problems: count the singular weight matrices, beat floating point with exact elimination, and evaluate a Real NVP likelihood the way the paper does.
Problem 13·Warm-up
How many layers lose information?
A tiny linear layer maps with the weight matrix
If is singular, the layer squashes the plane onto a line (or a point), and no later layer can recover what it threw away.
Suppose every entry is an integer from to inclusive, so there are possible matrices. How many of them are singular, that is, have ?
Problem 14·Standard
Exact elimination beats floating point
The Hilbert matrix has entries
It looks harmless, but it is famously ill-conditioned: tiny rounding errors are magnified enormously when you solve systems with it.
Take and let . The solution of has integer entries. Find it exactly, by Gaussian elimination with fractions, and give
Problem 15·Challenge
Apply the paper: a tiny Real NVP
Real NVP builds an invertible map from affine coupling layers. Each layer keeps one half of its input unchanged and transforms the other half (the paper's Eqs. 4–5):
where and act entry by entry. The model's log-density then comes from Eq. 3:
Here and . The map is three coupling layers, each applied to the output of the one before:
- Layer 1: and , using . - Layer 2: and , using . - Layer 3: and , using .
Here always mean the current four numbers, and goes back into the positions came from. In layer , (entry by entry) and , with
The prior is the standard normal density on , so , with natural logarithms.
Compute , rounded to 4 decimal places.
Key takeaways
- Two pictures of : rows are lines or planes that must meet; columns are vectors whose combination must make .
- Elimination uses three reversible row operations on to reach row echelon form, then back substitution; Gauss–Jordan continues to the unique reduced form.
- Three outcomes: a pivot in the column means no solution; a column of without a pivot means infinitely many; otherwise exactly one.
- The inverse undoes , can be found by reducing , exists only for nonsingular square matrices, and reverses products: .
- The determinant is the signed volume scale: , triangular means product of the diagonal, and exactly when is singular.
- Triangular Jacobians make a normalising flow's log-determinant a cheap sum, which is how Real NVP computes exact likelihoods.
Checkpoint
Prove it to the labyrinth
Answer every question to clear this chamber. First-try answers earn the most XP.
Which row operation undoes ?
What is ?
What is the inverse of ?
and are invertible matrices. What is ?
and are matrices with and . What is ?
Which of these matrices is singular?
Why does Real NVP design its coupling layers so that their Jacobians are triangular?
End of the chamber
Clear this chamber
- Questions in this chamber (0/11 solved)Next unsolved
- Bonus: Row reducer (+50 XP)
- Bonus: Problem 13: How many layers lose information? (+20 XP)
- Bonus: Problem 14: Exact elimination beats floating point (+35 XP)
- Bonus: Problem 15: Apply the paper: a tiny Real NVP (+50 XP)
- Bonus: Proof: An invertible matrix gives exactly one solution (+25 XP)
- Bonus: Proof: A matrix has at most one inverse (+40 XP)
- Bonus: Decode the paper (+30 XP)
- Bonus: Match: From notation to NumPy (+25 XP)
- Bonus: Match: What happens to the determinant? (+25 XP)