PyTorch primer3 / 6

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:

[2051]w=[826]⇒w=(4,6)\begin{bmatrix} 2 & 0 \\ 5 & 1 \end{bmatrix} \mathbf{w} = \begin{bmatrix} 8 \\ 26 \end{bmatrix} \quad\Rightarrow\quad \mathbf{w} = (4, 6)

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 AA from matrices as transformations:

Length, identity, determinant, inverse
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 A
  • torch.linalg.vector_norm(v) is the length ∥v∥\lVert \mathbf{v} \rVert. For (3,4)(3, 4) it's 5.
  • torch.eye(n) is the n×nn \times n identity matrix.
  • torch.linalg.det(A) is the determinant. AA doubles areas, so it's 2.
  • torch.linalg.inv(A) is the inverse. inv(A) @ A gives 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 x\mathbf{x} with Ax=bA\mathbf{x} = \mathbf{b}. The matrix comes first, then the right-hand side.

Solving for the delivery weights
# 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, not 4., 6.. That means it's a tiny bit off whole numbers, in the last digits of a float32.
  • On a singular matrix, solve raises 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 (i,j)(i, j) is 1/(i+j+1)1 / (i + j + 1), 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 b\mathbf{b} so the true answer is all ones. Then we plug each method's x\mathbf{x} back in and measure how far HxH\mathbf{x} lands from b\mathbf{b}.

Predict first

On a 10 × 10 Hilbert matrix, you plug each answer back in. Whose x fits the equations H x = b more closely?

246810121e-161e-141e-121e-101e-81e-61e-41e-21e0n (the matrix is n × n)miss ‖A x − b‖

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.

How far H x lands from b, on a log scale. As the Hilbert matrix grows, inv(H) @ b fits the equations worse and worse. solve(H, b) stays near the smallest error a float64 can show.

At n=10n = 10, the inv answer misses the equations by about 3×10−43 \times 10^{-4} in PyTorch, and the solve answer by about 10−1510^{-15}. That's a gap of about 3×10113 \times 10^{11} in how well each fits. The exact numbers depend on your computer, but the gap is always large.

solve's x\mathbf{x} fits the equations almost perfectly. Both answers drift from the true all-ones, because HH is nearly singular; solve drifts less.

inv versus solve, in PyTorch
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-16
  • i[:, None] + i[None, :] adds a column to a row. Broadcasting turns that into an n×nn \times n table with entry (r,c)=r+c(r, c) = r + c.
  • torch.ones(n) is a vector of ones, so b = H @ ones has the known answer ones.

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.

20
11
not symmetric: top-right ≠ bottom-left

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.

eigvals always returns complex numbers. eigh returns real ones, smallest first, but reads only the lower triangle. On any matrix that isn't symmetric, its answers are wrong.

The general case: eig

eig: any square matrix
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. Column i goes with eigenvalue i.
  • The results are complex (dtype complex64), even when every answer is real. A matrix like the quarter turn has complex eigenvalues, so eig always returns a type that can hold them. Python writes the imaginary unit ii as j, so 0.+1.j means 0+1i0 + 1i.
  • .real takes 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:

eigh: symmetric matrices only
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]] instead
  • torch.linalg.eigh(S) returns real eigenvalues, sorted smallest first, and real eigenvectors at right angles.
  • The result has named parts: .eigenvalues and .eigenvectors. You can also unpack it as values, 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 (0.45,0.35,0.20)(0.45, 0.35, 0.20) 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.

Week 0 of 20
The loop applies T once per week. matrix_power(T, k) does k weeks in one call, and gives the same shares. The thin ticks mark the long-run shares.
The pizza shops: a loop and a matrix power
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, with shares on the left.
  • torch.linalg.matrix_power(T, k) multiplies TT by itself kk times. So start @ matrix_power(T, 30) is 30 weeks in one call.
  • T ** 2 is not T2T^2. ** works entry by entry: its top-left entry is 0.82=0.640.8^2 = 0.64. The true T2T^2 has 0.8×0.8+0.1×0.2+0.1×0.1=0.670.8 \times 0.8 + 0.1 \times 0.2 + 0.1 \times 0.1 = 0.67 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 T⊤T^\top with eigenvalue 1, scaled to add up to 1. eig can find it directly:

Long-run shares from eig
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 Av=λvA\mathbf{v} = \lambda\mathbf{v} uses a column vector.
  • torch.argmin gives 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 AA 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 kk. Use torch.linalg.matrix_power(A, k).

Recap