Pidoku

Matrix Multiplication by Hand

Module 10 Lesson 10.b 1h 15m Difficulty 2/5

Prerequisites 10.a

Matrix multiplication (“matmul”) is 90–95% of the arithmetic in language-model inference. Modules 4–6, 13 and 14 are, in the end, about making this one operation faster. Do the exercises by hand at least once.


Before you start: three words#

WordPlain meaning
Matmul / GEMMMatrix multiplication. Libraries call it GEMM (“general matrix multiply”).
GEMVMatrix × vector: the special case where one side has a single row or column.
FLOPOne floating-point operation (one multiply, or one add). 1.a and 2.f use FLOP counts to estimate time.

1. What is it?#

Take A with shape (M, K) and B with shape (K, N). The product C = A @ B has shape (M, N), and each entry is:

C[i][j] = sum over k of  A[i][k] × B[k][j]

In words: entry (i, j) of the result is the dot product of row i of A with column j of B (10.a).

The inner sizes must match, and they disappear from the result. That is the whole rule:

(M, K) @ (K, N) = (M, N)
     ↑     ↑
     must match; they vanish

2. Why does it exist?#

Because “apply the same transformation to many vectors at once” is the fundamental operation of neural networks, and matmul is exactly that:

One vector through a layer:   y = W x            (M,K) @ (K,1)
A batch of vectors:           Y = X @ Wᵀ         (B,K) @ (K,M)

Stacking layers is chaining matmuls. And because a matmul reuses every number it loads many times (high arithmetic intensity, 2.f), it is the one operation hardware designers have optimised relentlessly. Tensor cores (4.f) exist for it and almost nothing else.


3. Simple analogy#

A bill for several customers in several currencies.

  • Rows of A are customers; columns of A are how many of each product they bought.
  • Rows of B are products; columns of B are each product’s price in a different currency.

C[i][j] is what customer i pays in currency j: “how many of each product” combined with “what each product costs” — one dot product per customer–currency pair.


4. Tiny example#

Work this on paper before you read the answer.

A = [1  2]      B = [5  6]
    [3  4]          [7  8]

C[0][0] = row0(A) · col0(B) = 1·5 + 2·7 = 5 + 14 = 19
C[0][1] = row0(A) · col1(B) = 1·6 + 2·8 = 6 + 16 = 22
C[1][0] = row1(A) · col0(B) = 3·5 + 4·7 = 15 + 28 = 43
C[1][1] = row1(A) · col1(B) = 3·6 + 4·8 = 18 + 32 = 50

C = [19  22]
    [43  50]

A non-square case — a row times a column gives one number:

[1 2] × [3]   →  (1,2) @ (2,1) = (1,1)
        [4]
result = 1·3 + 2·4 = 11

And the shape you will meet constantly — a batch of inputs through one layer:

X = [1  0  2]      W = [ 1  0]      X is (2,3): two inputs of 3 numbers
    [0  3  1]          [ 2  1]      W is (3,2): turns 3 numbers into 2
                       [-1  1]

C[0][0] = 1·1 + 0·2 + 2·(-1) = -1
C[0][1] = 1·0 + 0·1 + 2·1    =  2
C[1][0] = 0·1 + 3·2 + 1·(-1) =  5
C[1][1] = 0·0 + 3·1 + 1·1    =  4

C = [-1  2]     shape (2,2)
    [ 5  4]

Two inputs, each turned from 3 numbers into 2. That is one neural-network layer on a batch of 2. In a language model, each row of X is one token, K is the hidden size (thousands), and the batch can be thousands of tokens.


5. Technical explanation#

Cost#

Each of the M × N outputs needs K multiplications and K additions:

FLOPs = 2 · M · N · K

A worked example from a real model size — the feed-forward “up” projection of a dense 8B-class model (hidden size d = 4,096, feed-forward size d_ff = 14,336) on a prompt of 2,048 tokens:

2 · 2,048 · 14,336 · 4,096 ≈ 2.4 × 10^11 = 240 GFLOPs     for ONE matrix in ONE layer

The feed-forward block uses three such matrices (the SwiGLU design, 10.e), and the model has 32 layers: about 23 TFLOPs for the feed-forward parts of one 2,048-token prompt. A GPU sustaining around 600 TFLOP/s needs roughly 38 ms for that. This is where time to first token goes (12.c).

Three ways to see it (all useful)#

1. Dot products — the definition above. Best for understanding.

2. Mixes of columns. Column j of the result is a weighted mix of A’s columns: C[:, j] = sum_k B[k][j] · A[:, k]. Best for intuition about what a layer does.

3. A sum of outer products. C = sum_k A[:, k] ⊗ B[k, :]: each k adds one “rank-1” layer (a column times a row) onto the result. This is how hardware actually does it. Tensor cores repeatedly add small blocks of these updates into an accumulator held in fast on-chip storage.

Properties#

Associative:      (AB)C = A(BC)        ← same answer, very different FLOP counts
Distributive:     A(B+C) = AB + AC
NOT commutative:  AB ≠ BA
Transpose:        (AB)ᵀ = Bᵀ Aᵀ
Identity:         AI = IA = A

Associativity is a performance tool. Take A (1, 4096), B (4096, 4096), C (4096, 4096):

(A@B)@C:  2·1·4096·4096 + 2·1·4096·4096       ≈ 67 MFLOPs
A@(B@C):  2·4096·4096·4096 + 2·1·4096·4096    ≈ 137 GFLOPs      about 2,000x more work

Same answer, 2,000 times the work. Compilers and libraries exploit this, and so should you in custom code. LoRA adapters (18.g) rely on exactly this trick: they compute (x @ A) @ B with two thin matrices instead of forming the large A @ B.

Tiled multiplication#

Real implementations never compute one entry at a time. They split the matrices into tiles (blocks such as 128 × 128):

C[I,J] = sum over Kk of  A[I,Kk] @ B[Kk,J]        I, J, Kk index tiles, not single numbers

Each tile of A and B is loaded into fast on-chip memory once and used for a whole tile of output. That raises the work done per number loaded from about 1 to roughly a third of the tile size (see 3.b for caches, 4.d for GPU memory). Every production GEMM library — cuBLAS, CUTLASS, rocBLAS, oneDNN — is a carefully tuned hierarchy of tiles:

Grid level:        which output tile does each group of threads compute?
Block level:       tiles staged in shared memory
Warp level:        smaller tiles held in registers
Instruction level: tensor-core matrix instructions on small fragments

5.b has you write a simple version.


6. Under the hood#

A modern GEMM kernel on a Hopper-class GPU, roughly:

for each output tile (e.g. 128×128, owned by one thread block):
    accumulator for the tile in registers
    for k_tile in range(0, K, 64):
        copy A[128×64] and B[64×128] from HBM into shared memory, asynchronously
            (the Tensor Memory Accelerator, TMA, does this copy in hardware)
        wait until the copy has landed
        issue tensor-core instructions that multiply the tiles and add into the accumulator
            (on Hopper, warpgroup "wgmma" instructions; on Blackwell, "tcgen05"
             instructions that keep the accumulator in a dedicated tensor memory)
    write the accumulator to C in HBM
        ("epilogue": may also add a bias, apply an activation or quantize, 11.h)

Three ideas here recur throughout this material: double buffering (load the next tile while computing the current one), accumulating on-chip (avoid round trips to HBM), and fusing the epilogue (finish the output before it is ever written out).


7. Performance implications#

Shape matters enormously.

(4096, 4096) @ (4096, 4096)   → excellent: full tiles, each loaded number reused thousands of times
(1, 4096) @ (4096, 4096)      → a GEMV: each weight used once; memory-bound, tensor cores mostly idle
(129, 4096) @ (4096, 4096)    → "tile quantization": 129 = 128 + 1, so a second row of tiles runs
                                 almost empty. Can cost close to 2x.

Tile quantization is why time sometimes jumps when a dimension crosses a multiple of 128. Round batch sizes and hidden sizes to friendly multiples where you can.

Wave quantization: if a matmul splits into 133 thread blocks and the GPU has 132 SMs, it runs in two “waves” and the second is nearly empty — roughly half the GPU idle for half the time.


8. Production implications#

  • Never write your own GEMM for production. cuBLAS, cuBLASLt and CUTLASS represent thousands of engineer-years. Write your own only to learn (5.b), or to fuse something the libraries cannot.
  • Check which kernel is selected. CUBLASLT_LOG_LEVEL=2, or Nsight Compute (6.d), shows it. A shape that falls back to a generic kernel can be several times slower.
  • Pad shapes to tensor-core-friendly multiples (at least 8 for 16-bit types, 16 for 8-bit, and ideally 64 or 128). Model makers do this too: vocabulary sizes are chosen or padded to such multiples.
  • Watch for accidental GEMVs. Decoding one token for one user is inherently GEMV-shaped (12.c), and that is expected. A GEMV where you expected a GEMM means a shape bug.

9. Common mistakes#

Getting the inner sizes backwards. (M,K) @ (K,N). On a shape error, print both shapes and read them left to right.

Assuming A@B == B@A. It does not, and often cannot.

Ignoring the order of a chain. It can cost orders of magnitude.

Counting FLOPs as M·N·K instead of 2·M·N·K. It halves every estimate.

Forgetting that the batch size is “free” for weight reads but not for memory. A bigger batch reads the same weights once, but needs more memory for activations.


10. Hands-on exercise#

A. By hand. Compute, then check with code:

1.  [2 1] @ [1 0]        2.  [1 2 3] @ [1]      3.  [1 0] @ [0 1]
    [0 3]   [2 1]                       [0]         [0 1]   [1 0]
                                        [2]

(Answers: 1 → [[4,1],[6,3]]; 2 → [7]; 3 → [[0,1],[1,0]].)

B. Three loop orders. Implement matmul in any language as (i) the textbook i, j, k loops, (ii) a sum of outer products, (iii) the i, k, j order. Check that all three agree, time each on 512 × 512 matrices, and explain the differences using what 3.b says about caches.

C. Tiling. Implement a tiled matmul and sweep the tile size. Plot GFLOP/s against tile size and compare with the naive version and with an optimised BLAS (NumPy uses one).

D. Tile quantization. On a GPU, time (M, 4096) @ (4096, 4096) for M ∈ {127, 128, 129, 255, 256, 257}. Plot it and explain the jumps.

E. Association order. Time (A@B)@C against A@(B@C) for the shapes in section 5 and confirm the ratio.


11. Interview questions#

  1. State the shape rule and the FLOP count for matrix multiplication.
  2. Explain matmul as a sum of outer products, and why hardware likes that view.
  3. What is tile quantization and how do you avoid it?
  4. Why is decoding for a single user GEMV-shaped, and why does that matter?
  5. For (1,4096) @ (4096,4096) @ (4096,4096), which order do you choose and why?
  6. What does a GEMM kernel keep in registers, in shared memory and in HBM?

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in