Lesson 3 · Tensors and linear algebra
Linear algebra in PyTorch
The problem
In the transformations chapter, you found the delivery weights by hand. Delivery A took 8 minutes and B took 26:
By hand, a 2×2 system takes a minute. A model might need a 1000×1000 one. This chapter shows the PyTorch call for each tool from Section 1, and the trap in each.
Lengths, determinants and inverses
PyTorch's linear algebra lives in torch.linalg. Here are the basics, on the matrix from matrices as transformations:
A = torch.tensor([[2.0, 1.0],
[0.0, 1.0]]) # from 1.4: columns (2, 0) and (1, 1)
print(torch.linalg.vector_norm(torch.tensor([3.0, 4.0]))) # tensor(5.): the length ‖(3, 4)‖
print(torch.eye(2)) # tensor([[1., 0.], [0., 1.]]): the identity
print(torch.linalg.det(A)) # tensor(2.): A doubles areas
print(torch.linalg.det(torch.tensor([[1.0, 2.0],
[0.5, 1.0]]))) # tensor(-0.) or tensor(0.): zero either way
print(torch.linalg.inv(A)) # tensor([[ 0.5000, -0.5000], [ 0.0000, 1.0000]])
print(torch.linalg.inv(A) @ A) # the identity: inv(A) undoes Atorch.linalg.vector_norm(v)is the length . For it's 5.torch.eye(n)is the identity matrix.torch.linalg.det(A)is the determinant. doubles areas, so it's 2.torch.linalg.inv(A)is the inverse.inv(A) @ Agives the identity back.
The squash matrix's determinant may print as tensor(-0.) or tensor(0.). Both are zero. Floats have a "negative zero", and rounding can produce it. Never test a float with == 0; check whether it's close to 0.
Solving a system
torch.linalg.solve(A, b) returns the with . The matrix comes first, then the right-hand side.
# The two timed deliveries from 1.4: (km, traffic level) per row, and the minutes each took.
X = torch.tensor([[2.0, 0.0],
[5.0, 1.0]])
minutes = torch.tensor([8.0, 26.0])
weights = torch.linalg.solve(X, minutes) # the w with X @ w = minutes
print(weights) # tensor([4.0000, 6.0000]): 4 minutes per km, 6 per traffic level
# torch.linalg.solve(torch.tensor([[2.0, 0.0], [4.0, 0.0]]), minutes)
# -> error: "The solver failed because the input matrix is singular."- The answer prints as
4.0000, 6.0000, not4., 6.. That means it's a tiny bit off whole numbers, in the last digits of afloat32. - On a singular matrix,
solveraises an error:The solver failed because the input matrix is singular.
Solve, don't invert
You could also write torch.linalg.inv(X) @ minutes. In exact maths it's the same answer. But a computer rounds every float calculation. inv rounds while building the inverse and again while multiplying. solve works through the equations once, the way you did by hand.
To compare them, we need matrices whose columns almost line up. The Hilbert matrix is a famous one. Entry is , counting from 0. Neighbouring columns are almost the same list of numbers, and the bigger the matrix, the closer to singular it gets.
We build so the true answer is all ones. Then we plug each method's back in and measure how far lands from .
Predict first
On a 10 × 10 Hilbert matrix, you plug each answer back in. Whose x fits the equations H x = b more closely?
inv(H) @ b misses by 1.2 × 10^-4
solve(H, b) misses by 2.7 × 10^-16
The plot's height axis is logarithmic: each grid line is 10 times the one below. A miss of exactly 0 sits on the bottom line.
At , the inv answer misses the equations by about in PyTorch, and the solve answer by about . That's a gap of about in how well each fits. The exact numbers depend on your computer, but the gap is always large.
solve's fits the equations almost perfectly. Both answers drift from the true all-ones, because is nearly singular; solve drifts less.
def hilbert(n: int) -> torch.Tensor:
"""Entry (i, j) is 1 / (i + j + 1). Neighbouring columns almost line up."""
i = torch.arange(n, dtype=torch.float64)
return 1.0 / (i[:, None] + i[None, :] + 1.0) # (n, 1) + (1, n) -> (n, n)
def misses(n: int) -> tuple[float, float]:
"""How far A @ x lands from b, for x from inv(A) @ b and for x from solve(A, b)."""
H = hilbert(n)
b = H @ torch.ones(n, dtype=torch.float64) # so the true answer is all ones
x_inv = torch.linalg.inv(H) @ b
x_solve = torch.linalg.solve(H, b)
return (torch.linalg.vector_norm(H @ x_inv - b).item(),
torch.linalg.vector_norm(H @ x_solve - b).item())
for n in (4, 8, 12):
print(n, misses(n)) # inv misses by more and more; solve stays near 1e-16i[:, None] + i[None, :]adds a column to a row. Broadcasting turns that into an table with entry .torch.ones(n)is a vector of ones, sob = H @ oneshas the known answerones.
So the rule is: solve, don't invert. Reach for inv only when you need the inverse's entries themselves.
Eigenvalues: eig and eigh
There are two functions for eigenvalues and eigenvectors. Pick a matrix below to see what each returns.
eigvals → tensor([2.+0.j, 1.+0.j])
eigh → tensor([0.3820, 2.6180]) ✗ wrong
Not symmetric. Its true eigenvalues are 2 and 1, and eigvals finds them, as complex numbers with +0.j.
eigh reads only the lower triangle and assumes the matrix is symmetric. On any other matrix its answers are wrong.
Shaded cells are the lower triangle: the only entries eigh reads.
The general case: eig
values, vectors = torch.linalg.eig(A)
print(values) # tensor([2.+0.j, 1.+0.j]): complex, even though both are real
print(vectors) # one eigenvector per COLUMN, each of length 1
print(values.real) # tensor([2., 1.]): keep the real parts once you know they're real
rotate = torch.tensor([[0.0, -1.0],
[1.0, 0.0]]) # a quarter turn: no real stretch directions
print(torch.linalg.eigvals(rotate)) # tensor([0.+1.j, 0.-1.j])torch.linalg.eig(A)returns two tensors: the eigenvalues, and a matrix whose columns are the eigenvectors. Columnigoes with eigenvaluei.- The results are complex (dtype
complex64), even when every answer is real. A matrix like the quarter turn has complex eigenvalues, soeigalways returns a type that can hold them. Python writes the imaginary unit asj, so0.+1.jmeans . .realtakes the real parts. Use it once you know the imaginary parts are 0.torch.linalg.eigvals(A)returns only the eigenvalues.- Each eigenvector comes scaled to length 1, with an arbitrary sign. The eigenvalues aren't sorted.
The symmetric case: eigh
For a symmetric matrix, use the faster, more accurate function:
S = torch.tensor([[2.0, 1.0],
[1.0, 2.0]]) # symmetric: S equals S.T
values, vectors = torch.linalg.eigh(S)
print(values) # tensor([1., 3.]): real, smallest first
print(vectors) # columns ±(1, -1)/√2 and ±(1, 1)/√2: at right angles
M = torch.tensor([[0.8, 0.3],
[0.2, 0.7]]) # from 1.5: NOT symmetric; its eigenvalues are 0.5 and 1
print(torch.linalg.eigvals(M).real) # tensor([1.0000, 0.5000]): right
print(torch.linalg.eigh(M).eigenvalues) # tensor([0.5438, 0.9562]): wrong, and no error
# eigh reads only the lower triangle, so it solved [[0.8, 0.2], [0.2, 0.7]] insteadtorch.linalg.eigh(S)returns real eigenvalues, sorted smallest first, and real eigenvectors at right angles.- The result has named parts:
.eigenvaluesand.eigenvectors. You can also unpack it asvalues, vectors = .... - It doesn't check its input. It reads only the lower triangle and assumes the matrix is symmetric. On any other matrix its answers are wrong.
Predict first
M = [[0.8, 0.3], [0.2, 0.7]] has eigenvalues 0.5 and 1. It isn't symmetric. What does torch.linalg.eigh(M) do?
Matrix powers and power iteration
Power iteration applies a matrix again and again. In the eigenvectors chapter, the pizza-shop shares settled to from any start. In code, each week is one product, shares @ T. Step through the loop below.
shares = start
for week in range(0):
shares = shares @ T
# shares:
# [0.0000, 1.0000, 0.0000]
# start @ matrix_power(T, 0):
# [0.0000, 1.0000, 0.0000]Week 0: biggest gap to the long-run shares (0.45, 0.35, 0.20) is 0.6500
The thin ticks mark the long-run shares. The loop and matrix_power always agree.
T = torch.tensor([[0.8, 0.1, 0.1],
[0.2, 0.7, 0.1],
[0.1, 0.3, 0.6]], dtype=torch.float64) # row = this week's shop, column = next week's
shares = torch.tensor([0.0, 1.0, 0.0], dtype=torch.float64) # everyone at shop B
for week in range(30):
shares = shares @ T # one week of switching; shares stay a row vector
print(shares) # tensor([0.4500, 0.3500, 0.2000], dtype=torch.float64)
start = torch.tensor([0.0, 1.0, 0.0], dtype=torch.float64)
print(start @ torch.linalg.matrix_power(T, 30)) # the same 30 weeks in one call
print((T ** 2)[0, 0], torch.linalg.matrix_power(T, 2)[0, 0]) # 0.64 vs 0.67: ** is entry by entry- The shares are a row vector, so one week is
shares @ T, withshareson the left. torch.linalg.matrix_power(T, k)multiplies by itself times. Sostart @ matrix_power(T, 30)is 30 weeks in one call.T ** 2is not .**works entry by entry: its top-left entry is . The true has there.- The matrix uses
dtype=torch.float64, so the printed shares come out clean.
Predict first
T has shape (3, 3) and shares has shape (3,). Does T @ shares give next week's shares?
DeeperThe long-run shares straight from eigAsk for the eigenvector with eigenvalue 1 instead of running the loop. · 2 min
The long-run shares are the eigenvector of with eigenvalue 1, scaled to add up to 1. eig can find it directly:
def long_run_shares(t: torch.Tensor) -> torch.Tensor:
"""The eigenvector of t.T with eigenvalue 1, scaled so the shares add up to 1."""
values, vectors = torch.linalg.eig(t.T) # t.T, because A v = λ v uses a column vector
i = torch.argmin((values - 1).abs()) # the eigenvalue closest to 1
d = vectors[:, i].real # the imaginary parts are 0 here
return d / d.sum() # also fixes the arbitrary sign
print(long_run_shares(T)) # tensor([0.4500, 0.3500, 0.2000], dtype=torch.float64)- It passes
t.T, because uses a column vector. torch.argmingives the position of the smallest entry. Here it finds the eigenvalue closest to 1. On complex numbers,.abs()gives each one's size.- Dividing by
d.sum()makes the shares add up to 1. It also fixes the arbitrary sign.
The full file is in python/examples/02-pytorch-primer/03-linear-algebra/linear_algebra.py. Run it from the python/ folder with uv run python examples/02-pytorch-primer/03-linear-algebra/linear_algebra.py.
Common misconceptions
"inv(A) @ b and solve(A, b) are the same." In exact maths they are. In floats, solve is faster, and its answer fits the equations far better when is close to singular.
"eig returned complex numbers, so something went wrong." No. eig always returns complex tensors. Check that the imaginary parts are 0, then use .real.
"eigh will tell me if my matrix isn't symmetric." It won't. It reads the lower triangle and trusts it.
"A ** k is the matrix power." It raises each entry to the power . Use torch.linalg.matrix_power(A, k).
Recap
torch.linalgholds the linear algebra:vector_norm,det,inv,solve,eig,eighandmatrix_power.solve(A, b)is faster thaninv(A) @ b, and its answer fits the equations far better.eigworks on any square matrix and returns complex results.eighis for symmetric matrices only and returns real, sorted results.matrix_power(A, k)is .A ** kworks entry by entry.- PyTorch names:
torch.linalg.vector_norm,torch.eye,torch.linalg.det,torch.linalg.inv,torch.linalg.solve,torch.linalg.eigandeigvals,.real,torch.linalg.eigh,torch.linalg.matrix_power,torch.argminand.abs().