All courses
Courses › How LLMs really work · foundation

Linear algebra in numpy

Write matrix products with @, transpose with .T, and check shapes in code.

Builds on: Vectorized numpy, Matrix multiplication

▶ Watch this lesson Start the whole course

What the animation says

Two ways to multiply

On paper, X times W is one product. Rows of X meet columns of W. In numpy you have two ways to write a times sign: the star, and the at sign. Here are two small square arrays, A and B, each two by two. This line multiplies them with the star. What comes out?

Star hides, at multiplies

It runs, with no warning, and gives zero, two, three, zero. The star multiplies matching entries: one times zero, two times one, and so on. The at sign does the real matrix product. Each entry is a row of A with a column of B. First row, one two, with first column, zero one: zero plus two, so two. The full product is two, one, four, three. Different numbers, and the star never complained. With square arrays, the wrong operator hides. Use the at sign for matrix products.

Inner sizes meet, outer stay

Now X with three rows and two columns, times W with two rows and three columns. The inner sizes, two and two, match. The result takes the outer sizes: three by three. First row of X, one two, meets each column of W: one, two, and four. The star can't do this. Shapes three by two and two by three don't line up, so numpy raises an error. Row two of X, three four, with the third column of W, two one, gives ten. Tap where ten lands.

.T flips the shape

Dot T is the transpose. Rows become columns, so shape four by three becomes three by four. Take X, four by three. X at X fails: inner sizes three and four don't match. Value error. Flip the second one. X at X transposed is four by three times three by four: a four by four grid. Each entry is a dot product of two rows. Row zero with row one gives fourteen. Now flip the first one instead: X transposed, at X. What shape comes out?

Assert the shape

Three by three. The inner fours match, and the outer threes become the shape. So where you put the transpose decides which sizes meet in the middle. Make that a habit in code. After each product, assert the shape you expect. This line checks that Y is T by d out. If it isn't, you find out here, not three layers later. Remember: the at sign multiplies matrices, the star goes entry by entry, dot T swaps the sizes.

From XW on paper to correct code

You can read $XW$ and predict that $(T\times d)(d\times d_{out})\to T\times d_{out}$. But how do you write that product in numpy, flip a matrix, and *know* the result is right? The trap: `*` also multiplies arrays, but entry by entry. With square arrays it runs without complaint and gives a wrong answer. You need `@`, `.T`, and the habit of checking shapes.

@ multiplies, .T flips, shapes check

`A @ B` is exactly the matrix product you learned. Each output entry is the dot product of a row of `A` with a column of `B`. `A.T` is the transpose: rows become columns, so shape `(m, n)` becomes `(n, m)`. Shapes act as a built-in check. The inner sizes must match, and the result takes the outer sizes. If they don't fit, numpy raises an error instead of guessing.

The exact rules

For `A` of shape `(m, k)` and `B` of shape `(k, n)`: - `C = A @ B` has shape `(m, n)`, with `C[i, j] = (A[i, :] * B[:, j]).sum()`. - `A.T` has shape `(k, m)`, and `A.T[j, i] == A[i, j]`. - `A * B` multiplies matching entries. It needs equal or broadcastable shapes. - 1D array `v` of shape `(k,)`: `v @ B` gives `(n,)`. `.T` on a 1D array does nothing.

A 3×2 times 2×3 by hand

`X = [[1,2],[3,4],[5,6]]` has shape (3,2). `W = [[1,0,2],[0,1,1]]` has shape (2,3). Inner sizes are 2 and 2, so they match. `X @ W` has shape (3,3). Row `[1,2]` with the columns `[1,0]`, `[0,1]`, `[2,1]` gives 1, 2, 2+2=4. Row `[3,4]` gives 3, 4, 6+4=10. Row `[5,6]` gives 5, 6, 10+6=16. Result: `[[1,2,4],[3,4,10],[5,6,16]]`. `X * W` fails: shapes (3,2) and (2,3) can't broadcast.

Check shapes as you go

Print or `assert` shapes after each product. `X @ X.T` computes the dot product of every pair of rows at once. Using `@` on two arrays whose inner sizes differ raises a `ValueError`.
import numpy as np
T, d, d_out = 4, 3, 2
X = np.arange(T * d).reshape(T, d)   # (4, 3)
W = np.ones((d, d_out))              # (3, 2)
Y = X @ W
assert Y.shape == (T, d_out)         # (4, 2)
G = X @ X.T                          # (4,3) @ (3,4)
print(G.shape, G[0, 1])              # (4, 4) 14: row0 . row1
try:
    X @ X                            # (4,3) @ (4,3): 3 != 4
except ValueError:
    print("inner sizes don't match")

Remember

`@` is the matrix product and `*` is entry by entry. `.T` swaps the two sizes of a shape. Before trusting a result, check that the inner sizes match and that the output has the outer sizes, for example with `assert Y.shape == (T, d_out)`.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.