Linear algebra for LLMsPart 2: Matrices and matrix multiplication

Transpose

7 min

Start with a matrix

AA has 2 rows and 3 columns, so its shape is 2×32 \times 3.

Write

AA, and its shape: 2×32 \times 3.

Row 1 becomes column 1

→

The transpose, written A⊤A^\top, takes the first row of AA (blue) and stands it up as its first column.

Row 2 becomes column 2

→

The second row (pink) becomes the second column. A⊤A^\top has 3 rows and 2 columns: the shape flipped from 2×32 \times 3 to 3×23 \times 2.

Write

A⊤=[142536]A^\top = \begin{bmatrix} 1 & 4 \\ 2 & 5 \\ 3 & 6 \end{bmatrix}, shape 3×23 \times 2.

The rule

(A⊤)ij=Aji\displaystyle (A^\top)_{ij} = A_{ji}
(m×n)  →  (n×m)\displaystyle (m \times n) \;\to\; (n \times m)

The entry in row ii, column jj of A⊤A^\top is the entry in row jj, column ii of AA. Entries on the diagonal (row = column) stay where they are: here 1 and 5.

Write

(A⊤)ij=Aji(A^\top)_{ij} = A_{ji}, and the shape m×nm \times n becomes n×mn \times m.

✏️ Your turn

Transpose BB

Write B⊤B^\top and its shape.

Work it out on paper, then go to the next card to check.

Answer: B⊤B^\top

→

Each column of BB became a row of B⊤B^\top: 3×23 \times 2 became 2×32 \times 3.

Transpose twice and you're back

(A⊤)⊤=A(A^\top)^\top = A

Flipping over the diagonal twice puts every entry back where it started.

Symmetric matrices

=

A square matrix equal to its own transpose is symmetric: Sij=SjiS_{ij} = S_{ji}, a mirror image across the diagonal. Covariance matrices and every matrix of the form XX⊤XX^\top are symmetric (you’ll see why in Four ways to see AB).

Write

Symmetric: S⊤=SS^\top = S, so Sij=SjiS_{ij} = S_{ji}.

Row vectors and column vectors

→

Transposing a row vector (1×31 \times 3) gives a column vector (3×13 \times 1). Papers write a dot product as x⊤yx^\top y: a row times a column gives a 1×11 \times 1 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, shorter

In a transformer

Attention scores are QK⊤QK^\top. QQ and KK each have one row per token, shape T×dkT \times d_k. Transposing KK turns its rows into columns, so every query row meets every key column: (T×dk)(dk×T)=T×T(T \times d_k)(d_k \times T) = T \times T.

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

  • A⊤A^\top turns rows into columns: (A⊤)ij=Aji(A^\top)_{ij} = A_{ji}.
  • The shape flips: m×n→n×mm \times n \to n \times m. The diagonal stays put.
  • (A⊤)⊤=A(A^\top)^\top = A. Symmetric means S⊤=SS^\top = S.
  • A row vector transposed is a column vector, so x⊤yx^\top y is a dot product.
  • Attention uses K⊤K^\top so that every query meets every key: QK⊤QK^\top is T×TT \times T.

Write

The five lines above.