1.1 Linear algebra for language models
Vectors, matrix shapes, inner products, and the transformations behind attention.
Updated
A transformer is easier to understand when every matrix has a job and every axis has a name. This chapter develops the small amount of linear algebra needed to read the attention equations.
Vectors as representations
Section titled “Vectors as representations”A token ID is an integer. Its embedding is a vector , obtained by selecting a row of a learned embedding matrix. The vector’s coordinates are learned features. Individual coordinates need not correspond to human-readable concepts.
A sequence of tokens becomes a matrix with one token per row:
Throughout these notes, sequence positions are rows and feature dimensions are columns. Libraries may add batch and attention-head axes, but the same idea still applies.
Linear maps and shapes
Section titled “Linear maps and shapes”Multiplying by a learned matrix produces . The same map is applied independently to every token position. It mixes features, not positions.
For one output coordinate,
In attention, three such maps create queries, keys, and values. The maps share an input but learn different parameters. Sharing a source does not make their roles interchangeable.
Python implementation
import numpy as np
rng = np.random.default_rng(7)X = rng.normal(size=(4, 8)) # 4 positions, 8 featuresW_Q = rng.normal(size=(8, 3)) # map features to 3 query featuresW_K = rng.normal(size=(8, 3))
Q = X @ W_Q # (4, 3)K = X @ W_K # (4, 3)scores = Q @ K.T # (4, 4): positions against positionsassert scores.shape == (4, 4)Inner products compare two vectors
Section titled “Inner products compare two vectors”The inner product returns a scalar. In attention, it is a learned compatibility score. Its magnitude depends on both direction and vector length, so it is not generally a cosine similarity.
For two sequence matrices, computes all pairwise query–key scores at once. Entry compares the query at position with the key at position .
A useful distinction
Section titled “A useful distinction”The product mixes features separately at each position. The product , where , mixes positions separately for each value feature. Attention combines these two kinds of operation.
Weighted sums
Section titled “Weighted sums”Suppose and . Then is a weighted average of the value vectors. With fixed values, the result lies in their convex hull.
This describes a single attention head before its output projection. It does not imply that an entire transformer can only average its inputs: learned projections, residual paths, and nonlinear feed-forward layers change what the full network can compute.
Continue reading
Section titled “Continue reading”The next step is to see how a model constructs the weights . The scaled dot-product attention equation (2.3) turns compatibility scores into normalized weights. The attention chapter derives that computation and implements it in NumPy.