Linear algebra for LLMsPart 2: Matrices and matrix multiplication
Transpose
7 min
Start with a matrix
has 2 rows and 3 columns, so its shape is .
Write
Row 1 becomes column 1
The transpose, written , takes the first row of (blue) and stands it up as its first column.
Row 2 becomes column 2
The second row (pink) becomes the second column. has 3 rows and 2 columns: the shape flipped from to .
Write
The rule
The entry in row , column of is the entry in row , column of . Entries on the diagonal (row = column) stay where they are: here 1 and 5.
Write
✏️ Your turn
Transpose
Write and its shape.
Work it out on paper, then go to the next card to check.
Answer:
Each column of became a row of : became .
Transpose twice and you're back
Flipping over the diagonal twice puts every entry back where it started.
Symmetric matrices
A square matrix equal to its own transpose is symmetric: , a mirror image across the diagonal. Covariance matrices and every matrix of the form are symmetric (you’ll see why in Four ways to see AB).
Write
Row vectors and column vectors
Transposing a row vector () gives a column vector (). Papers write a dot product as : a row times a column gives a matrix, which is a single number.
Transpose in PyTorch and in attention
A.T # a 2-D matrix: swap rows and columns
k.transpose(-2, -1) # a batch of matrices: swap only the last two axes
k.mT # the same, shorterIn a transformer
Attention scores are . and each have one row per token, shape . Transposing turns its rows into columns, so every query row meets every key column: .
In PyTorch, .T and .transpose don’t copy any numbers. They return a view of the same memory with the axes swapped (Part 4).
📌 Recap
Transpose in one card
- turns rows into columns: .
- The shape flips: . The diagonal stays put.
- . Symmetric means .
- A row vector transposed is a column vector, so is a dot product.
- Attention uses so that every query meets every key: is .
Write