Matrices
Stacking vectors together to represent whole sentences at once.
By the end of this chapter, you'll be able to:
- Read a matrix's shape and know what each dimension represents
- Multiply two matrices by hand and predict the resulting shape
- Connect a matrix directly to a batch of token embeddings
A single token's embedding is a vector. A whole sentence — many tokens, each with its own embedding — is naturally a grid of numbers: one row per token, one column per embedding dimension. That grid is a matrix, and it's the data structure almost everything in this handbook actually operates on.
Shape is the first thing to read
A matrix's shape is written rows × columns. A sentence with 3 tokens, each embedded in 2 dimensions, is a (3, 2) matrix:
| d1 | d2 | |
|---|---|---|
| I | 1 | 2 |
| love | 3 | 4 |
| AI | 5 | 6 |
Row 0 is the first token's embedding, [1, 2]. Row 1 is the second token's, [3, 4]. This is exactly the sentence array from the Vectors
chapter — a matrix is just what you get when you stack vectors on top of each
other.
Matrix multiplication
Multiplying two matrices only works when the inner dimensions match: an (m, n) matrix can multiply an (n, p) matrix, producing an (m, p) result.
Each entry of the result is a dot product: row i of the first matrix against
column j of the second. This is precisely what happens in
X @ X.T: X is (3, 2), X.T (its transpose) is (2, 3) — inner dimensions match
(both 2) — producing a (3, 3) result, one score per pair of tokens.
import numpy as np
X = np.array([
[1, 2],
[3, 4],
[5, 6],
])
print(X.shape) # (3, 2)
print(X.T.shape) # (2, 3)
print((X @ X.T).shape) # (3, 3)Shape-checking is the fastest debugging tool you have
Before worrying about whether a matrix multiplication is correct, check whether it's even possible. If the inner dimensions don't match, NumPy (and every deep learning framework) will raise a shape error immediately — that error message is usually the fastest way to catch a bug in how vectors are being combined.
Transpose, precisely
The transpose of a matrix, written , flips rows and columns: row i,
column j of becomes row j, column i of . A (3, 2) matrix
transposes into a (2, 3) matrix. It doesn't change any of the numbers — it changes
how they're arranged, which is exactly what's needed to make X @ X.T's
dimensions line up.
Check your understanding
1. A matrix has shape (4, 8). What do the two numbers represent if it's a batch of token embeddings?
2. Can a (5, 3) matrix be multiplied by another (5, 3) matrix directly (not transposed)?