Linear Algebra for Transformers

Community Article
Published July 22, 2026

Develop a feel for what happens inside a transformer.

πŸ““ Companion notebook: EXDai/linear-algebra-transformers β€” download and run every code snippet yourself. All plots in this article are generated by the notebook.

Episode 11 of the EXD


1. Vectors Are Just Lists of Numbers

A token embedding is a vector β€” a list of 2048 numbers. But we'll start with two dimensions so we can draw it.

Two word vectors in 2D: cat = [0.8, 0.3] and dog = [0.6, 0.7]

cat is the arrow [0.8, 0.3]. dog is [0.6, 0.7]. Each is just two numbers.

In a real transformer, every token in the sequence gets its own 2048-dimensional vector. The math we're about to do β€” rotation, dot products, matrix multiplication β€” generalizes directly to 2048D. Only the shapes of the matrices matter.


2. Rotation (Ep10 Recap)

Rotation is a matrix multiply where the matrix is orthogonal β€” it preserves a vector's length. In a transformer, RoPE rotates Q and K by position-dependent angles so attention knows token order.

RΞΈ=[cosβ‘ΞΈβˆ’sin⁑θsin⁑θcos⁑θ] R_\theta = \begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix}

Apply it to cat:

RΞΈβ‹…cat=[cosβ‘ΞΈβˆ’sin⁑θsin⁑θcos⁑θ][0.80.3] R_\theta \cdot \texttt{cat} = \begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix} \begin{bmatrix} 0.8 \\ 0.3 \end{bmatrix}

cat vector rotated through 12 evenly-spaced positions around the unit circle

The vector traces a circle. Its length (|cat|) stays exactly the same at every angle β€” rotation is an isometry, moving the vector without stretching or shrinking. This is why values stay bounded even after being rotated across dozens of transformer layers.

In Qwen3.6, only 64 of the 256 dimensions per head are rotated (25% partial rotary factor). The other 192 are position-free β€” they carry pure semantic content. See Ep10 for the full deep dive into mRoPE.


3. The Dot Product: How Similar Are Two Vectors?

The dot product multiplies corresponding elements and sums them:

aβ‹…b=a1b1+a2b2+β‹―+anbn=βˆ‘iaibi \mathbf{a} \cdot \mathbf{b} = a_1 b_1 + a_2 b_2 + \cdots + a_n b_n = \sum_i a_i b_i

Geometrically: a Β· b = |a| |b| cos(ΞΈ). It measures how much two vectors point in the same direction.

For our toy vectors:

cat Β· dog        = 0.8Γ—0.6 + 0.3Γ—0.7 = 0.69
cat Β· cat        = 0.8Β² + 0.3Β² = 0.73   (= |cat|Β²)
dog Β· dog        = 0.6Β² + 0.7Β² = 0.85   (= |dog|Β²)
cat Β· (βˆ’cat)     = βˆ’0.73                 (opposite direction)

In a transformer, the attention score between two tokens is a dot product: scoreα΅’β±Ό = Qα΅’ Β· Kβ±Ό. Every pair of tokens gets a score. Here's the full pairwise grid for our toy vectors:

Pairwise dot products. Each cell is aΒ·b for the corresponding vectors. Red = similar, blue = dissimilar.

This grid is the QKα΅€ attention score matrix β€” just with 2D toy vectors instead of 256D head vectors. Every cell is a dot product. High scores (red) mean the model considers those tokens related. Softmax converts these to probabilities.

But there's a problem. Look at the diagonal: catΒ·cat = 0.73 while dogΒ·dog = 0.85. Same operation (self-similarity), different results. Something is wrong.


4. The Problem: Length Distorts Similarity

aΒ·a = |a|Β². So dogΒ·dog is larger simply because dog is a longer vector (|dog| = 0.92 vs |cat| = 0.85).

In a transformer, this means a token with a large-magnitude key vector would dominate the softmax β€” not because it's semantically relevant, but purely because its vector is longer. That would make attention unstable.

The fix: normalize vectors to unit length. Then aΒ·b depends only on the angle between them, not their lengths.

Divide each vector by its length:

cat_norm   = cat / |cat|   = [0.936, 0.351]
dog_norm   = dog / |dog|   = [0.651, 0.760]

Now every self-dot is exactly 1.0, and the pairwise scores measure pure directional similarity:

Normalized dot products. All self-similarities are exactly 1.0. Off-diagonal values are cosine similarities.

Every cell on the diagonal is 1.0. cat_norm Β· dog_norm = 0.876 β€” this is the cosine of the angle between them (ΞΈ = 28.9Β°). The comparison now depends purely on semantic direction, not vector magnitude.

This is exactly why Qwen3.5 applies QK Norm β€” RMSNorm on Q and K before computing attention scores. Each head's vectors are scaled to unit variance so the dot product measures direction, not magnitude. V is deliberately not normalized β€” the model can still control how much information a token carries through the magnitude of V.

RMSNorm(x)=xmean(x2)+Ο΅β‹…Ξ³ \text{RMSNorm}(x) = \frac{x}{\sqrt{\text{mean}(x^2) + \epsilon}} \cdot \gamma

The learned parameter Ξ³ lets the model rescale after normalization.


5. Matrix Γ— Vector: Transforming One Vector Into Another

A matrix is a rectangular grid of learned numbers. Multiply it by a vector to get a new vector β€” possibly with a different number of dimensions.

y=Wxwhereyi=βˆ‘jWij xj \mathbf{y} = \mathbf{W}\mathbf{x} \quad\text{where}\quad y_i = \sum_j W_{ij}\, x_j

Here's a concrete example: a 2Γ—3 matrix transforms a 3D vector into a 2D vector:

[1.00.5βˆ’0.30.20.80.4][0.80.30.5]=[1.0(0.8)+0.5(0.3)+(βˆ’0.3)(0.5)0.2(0.8)+0.8(0.3)+0.4(0.5)]=[0.800.60] \begin{bmatrix} 1.0 & 0.5 & -0.3 \\ 0.2 & 0.8 & 0.4 \end{bmatrix} \begin{bmatrix} 0.8 \\ 0.3 \\ 0.5 \end{bmatrix} = \begin{bmatrix} 1.0(0.8) + 0.5(0.3) + (-0.3)(0.5) \\ 0.2(0.8) + 0.8(0.3) + 0.4(0.5) \end{bmatrix} = \begin{bmatrix} 0.80 \\ 0.60 \end{bmatrix}

Each output element is a weighted sum of all input elements. The weights (matrix entries) are learned during training.

The shape rule: if W is (m Γ— n) and x is (n,), the result is (m,). The inner dimensions must match. This determines every projection shape in Qwen3.6:

Projection W shape Input shape Output shape
Q + gate 8192 Γ— 2048 2048, 8192,
K 512 Γ— 2048 2048, 512,
V 512 Γ— 2048 2048, 512,
O 2048 Γ— 4096 4096, 2048,

In a transformer, every projection (W_Q, W_K, W_V, W_O) is a matrixΓ—vector multiply. The hidden state h (2048D) is multiplied by learned weight matrices to produce Q (4096D + 4096D gate), K (512D), V (512D), and the output (2048D).


6. Projecting Up: Going to a Higher Dimension

When W has more rows than columns (a tall matrix), the output has more dimensions than the input. The vector is "projected up."

We'll project our 2D cat into 3D so we can see it happen:

W_up=[0.60.10.10.70.50.5],cat=[0.80.3],W_upβ‹…cat=[0.510.290.55] \text{W\_up} = \begin{bmatrix} 0.6 & 0.1 \\ 0.1 & 0.7 \\ 0.5 & 0.5 \end{bmatrix}, \quad \texttt{cat} = \begin{bmatrix} 0.8 \\ 0.3 \end{bmatrix}, \quad \text{W\_up} \cdot \texttt{cat} = \begin{bmatrix} 0.51 \\ 0.29 \\ 0.55 \end{bmatrix}

The cat vector on the xy-floor, and the same vector projected into 3D, lifted ~43Β° off the floor. Dashed lines show the shadow.

The orange vector has been lifted off the floor into a third dimension. The original 2D information is still there β€” you can see its shadow on the xy-plane β€” but now there's a z-component adding expressive capacity.

This is what the Q projection does: it gives each token more room by projecting into a higher-dimensional space (2048D β†’ 8192D). That extra space is where 16 attention heads can work simultaneously, each operating on a 256-dimensional slice of the projected vector.


7. Projecting Down: Squeezing Back to Fewer Dimensions

When W has fewer rows than columns (a wide matrix), the output has fewer dimensions. The vector is "projected down" β€” compressed.

We project our 3D vector back to 2D. Recall from Section 6:

v_3d=[0.510.290.55] \text{v\_3d} = \begin{bmatrix} 0.51 \\ 0.29 \\ 0.55 \end{bmatrix}

Now apply W_down (2Γ—3) to get a 2D output:

W_down=[0.40.50.20.30.10.6] \text{W\_down} = \begin{bmatrix} 0.4 & 0.5 & 0.2 \\ 0.3 & 0.1 & 0.6 \end{bmatrix}

W_downβ‹…v_3d=[0.4(0.51)+0.5(0.29)+0.2(0.55)0.3(0.51)+0.1(0.29)+0.6(0.55)]=[0.4590.512] \text{W\_down} \cdot \text{v\_3d} = \begin{bmatrix} 0.4(0.51) + 0.5(0.29) + 0.2(0.55) \\ 0.3(0.51) + 0.1(0.29) + 0.6(0.55) \end{bmatrix} = \begin{bmatrix} 0.459 \\ 0.512 \end{bmatrix}

Left: 3D view of the round-trip. Right: 2D comparison showing the error between original and compressed output.

The round-trip output [0.459, 0.512] is visibly different from the original [0.8, 0.3]. Information was lost in compression β€” the 3D vector held more than could fit back into 2D.

This is what the O projection does: it takes the concatenated head outputs (4096D) and compresses them back into the residual stream (2048D). Sixteen heads' worth of information must be squeezed through a bottleneck. The model learns which information to preserve β€” the O projection weights are trained to keep what matters and discard what doesn't.

Note: V is deliberately not normalized (no "V Norm") because the model uses V's magnitude to control how much information flows through each token. Normalizing V would strip away that control.


8. Everything In One Place

Every operation in a transformer is one of the five we just learned:

Operation Transformer role Notation
Rotation Position-encode Q and K R_ΞΈ Β· q
Dot product Attention score between two tokens qα΅€k / √d
Normalization Remove length bias from scores RMSNorm(q), RMSNorm(k)
Project UP Expand hidden state for multi-head work W_Q Β· h (2048 β†’ 8192)
Project DOWN Compress head outputs back to residual W_O Β· concat (4096 β†’ 2048)
MatrixΓ—Vector (same-dim) Produce lean K and V for GQA W_K Β· h, W_V Β· h (2048 β†’ 512)

Plus two nonlinear functions: softmax (converts scores to probabilities) and sigmoid (the gate in gated attention). That's the entire mathematical foundation of the attention mechanism.


9. Scaling Up: From 2D to 2048D

The operations we did with 2D and 3D vectors are identical to what happens inside Qwen3.6-35B-A3B β€” just with larger matrices:

Operation Toy shape Real shape (Qwen3.6)
Q projection (up) 3Γ—2 β†’ 3D 8192Γ—2048 β†’ 8192D
K projection 2Γ—3 β†’ 2D 512Γ—2048 β†’ 512D
O projection (down) 2Γ—3 β†’ 2D 2048Γ—4096 β†’ 2048D
Rotation 2D rotation 64 of 256 dims per head

to step through the real matrix shapes interactively.


Next: Ep12 β€” Attention Heads. We load Qwen3.6-35B-A3B, feed it a sentence, and pause inside the attention heads β€” watching the actual Q, K, V projections happen on real vectors.

Community

Sign up or log in to comment