Chapter 3 of 10 · ~20 min read & lab+50 XP
Chapter 3 · Linear Algebra

Matrix Algebra, Multiplication, Broadcasting & Tensor Shapes

From hand-multiplying 2×2 matrices to mastering (B, H, T, D) Transformer shapes, FLOPs counting, broadcasting, and einsum

Why ML Engineers & Data Scientists Actually Need This

Matrix Multiplication (GEMM) is 95% of all GPU compute in Deep Learning — from Linear Layers to Transformer Attention!

ML / AI Engineer

Every `nn.Linear(in, out)` is literally `X @ W.T + b`, and FlashAttention / LoRA speedups exist purely because changing multiplication order `(AB)C` vs `A(BC)` saves 100× FLOPs!

Data Scientist

Replacing nested Python loops with one NumPy matrix multiply (`X @ w`) computes predictions for 1,000,000 rows in 2 milliseconds instead of 20 seconds.

Interview & Debug Edge

Knowing `(M, K) @ (K, N) -> (M, N)` costs `2·M·K·N` FLOPs lets you answer LLM inference latency, KV-cache, and Attention complexity questions effortlessly!

Step 0 · Test Your Gut Before Any Math!

You need to multiply 3 matrices: A (1000 × 1000), B (1000 × 4), and C (4 × 1000). Since matrix multiplication is associative, (A @ B) @ C and A @ (B @ C) give the EXACT same answer. Does the order affect speed?

What You Will Master in This Chapter
  • Distinguish elementwise matrix addition / Hadamard product (*) from true matrix multiplication (@).
  • Compute small matrix products by hand using the Row-by-Column dot-product rule and verify shape compatibility (M×K)@(K×N) → (M×N).
  • Apply key matrix laws: non-commutativity (AB ≠ BA), transpose reversal (AB)ᵀ = BᵀAᵀ, and associative FLOPs optimization.
  • Predict batched N-D tensor shapes, catch silent broadcasting bugs, and write clean einsum contractions in NumPy/PyTorch.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
No mysterious math notation — translate everything into English first
How to Say It Aloud
“Matrix Multiply Shape Rule”
Plain-English Meaning
The INNER numbers (K and K) MUST match and disappear; the OUTER numbers (M, N) become your output shape!
Everyday Example
(32, 768) @ (768, 10) → (32, 10) (32 items → 10 class logits!).
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Every neural network forward pass and backward pass is fundamentally a sequence of matrix multiplications (GEMMs) and broadcasted elementwise operations. Start by mastering simple 2×22 \times 2 hand multiplication — the exact same rule scales seamlessly to 70-billion-parameter LLMs!

1. Matrix Addition, Scaling & Hadamard Product vs. Matrix Multiplication

Everyday Story First (Zero Math Yet!)

Imagine running a bakery with 2 recipes (Cake & Cookie — rows of Matrix A) using 2 ingredients (Flour & Sugar), and 2 suppliers (Store 1 & Store 2 — columns of Matrix B) with different ingredient prices. To find the cost of Cake at Store 2, you take the Cake Row of A and dot-product it with the Store 2 Column of B! That's ALL matrix multiplication is — a tidy grid of dot products!

Click all 4 output cells below to see Row × Column light up in real time!

A (M × K)Row i (len K)MK (must match!)@B (K × N)Col jKN=C (M × N)C[i,j]Outer dims survive!C[i,j] =A[i,:] · B[:,j]Cost: 2·M·N·K
Figure 3.1 — Matrix Multiplication Shape Contraction: inner dimensions K must match and collapse; outer dimensions (M × N) survive.

First, never confuse elementwise operations with matrix multiplication:

  • Matrix Addition (A+BA + B): Requires identical shapes (m×n)(m \times n). Simply add matching cells: (A+B)ij=Aij+Bij(A + B)_{ij} = A_{ij} + B_{ij}.
  • Hadamard (Elementwise) Product (A⊙BA \odot B, written A * B in Python): Also requires identical shapes and multiplies cell-by-cell: (A⊙B)ij=AijBij(A \odot B)_{ij} = A_{ij} B_{ij} (used in gating layers like SwiGLU and LSTM gates!).
  • Matrix Multiplication (ABAB, written A @ B in Python): Combines rows of AA with columns of BB via dot products:

(AB)ij=∑k=1KAikBkj=(Row i of A)⋅(Col j of B)(AB)_{ij} = \sum_{k=1}^K A_{ik} B_{kj} = (\text{Row } i \text{ of } A) \cdot (\text{Col } j \text{ of } B)

The Shape Compatibility Law

For A∈RM×KA \in \mathbb{R}^{M \times K} and B∈RK×NB \in \mathbb{R}^{K \times N}:

  • The inner dimensions (KK) must match — and they contract (disappear).
  • The outer dimensions (M×NM \times N) survive as the output shape.
  • Exact FLOPs cost: Each of the M⋅NM \cdot N output cells does KK multiplies and KK adds ≈2MNK\approx \mathbf{2 M N K} floating-point operations!

Worked Example 1 — Multiplying Two Matrices Step-by-Step by Hand

Let A=[1203−14]A = \begin{bmatrix} 1 & 2 & 0 \\ 3 & -1 & 4 \end{bmatrix} (shape 2×32 \times 3) and B=[2105−12]B = \begin{bmatrix} 2 & 1 \\ 0 & 5 \\ -1 & 2 \end{bmatrix} (shape 3×23 \times 2).

  • Inner dimensions match (3=33 = 3), so output C=ABC = AB has shape 2×22 \times 2:
    • C1,1=(1)(2)+(2)(0)+(0)(−1)=2C_{1,1} = (1)(2) + (2)(0) + (0)(-1) = \mathbf{2}
    • C1,2=(1)(1)+(2)(5)+(0)(2)=11C_{1,2} = (1)(1) + (2)(5) + (0)(2) = \mathbf{11}
    • C2,1=(3)(2)+(−1)(0)+(4)(−1)=6−4=2C_{2,1} = (3)(2) + (-1)(0) + (4)(-1) = 6 - 4 = \mathbf{2}
    • C2,2=(3)(1)+(−1)(5)+(4)(2)=3−5+8=6C_{2,2} = (3)(1) + (-1)(5) + (4)(2) = 3 - 5 + 8 = \mathbf{6} AB=[21126]AB = \begin{bmatrix} 2 & 11 \\ 2 & 6 \end{bmatrix}

Two Crucial Algebraic Rules (Watch Out!)

  1. Order Matters (AB≠BAAB \ne BA): Above, ABAB is 2×22 \times 2, whereas BABA is 3×33 \times 3! Even for square matrices, multiplying in the opposite order almost always gives a different answer.
  2. Transpose Reverses Order: (AB)T=BTAT(AB)^T = B^T A^T ("Shoes & Socks rule": take off your shoes before your socks!).
Hands-On Mini-Lab · Click Any Output Cell C[i, j] to Watch Row × Column Dot Product!

Click any of the 4 cells in result matrix C on the right. Watch which exact Row of A (sky blue) and Column of B (emerald) light up to compute it!

Matrix A
2
1
0
3
×
Matrix B
4
5
2
1
=
Click C[i, j]!
C[0,1] = (Row 0 · Col 1) = (2×5) + (1×1) = 10 + 1 = 11
Try It Yourself

Multiply A = [[1, 3], [2, 0]] by B = [[4, -1], [2, 5]] by hand. Then check if AB equals BA!

2. Associativity & 125× Speedups from Smart Parentheses

Everyday Story First (Zero Math Yet!)

Ever wonder why A @ B is NOT the same as B @ A? Think about getting dressed in the morning: putting on Socks then Shoes (Shoes @ Socks) works great — reversing the order (Shoes then Socks) looks ridiculous! Matrices are actions, and the order of actions matters!

✓ Smart Order: (X @ Aᵀ) @ Bᵀ — Passes through rank-16 bottleneck268M FLOPs (125× faster!)✗ Naive Order: X @ (Aᵀ @ Bᵀ) — Materializes full 4096 × 4096 matrix34,400M FLOPs (34.4 Billion FLOPs!)
Figure 3.3 — Why Parentheses Matter in ML: evaluating (X @ Aᵀ) @ Bᵀ through the rank-16 bottleneck uses 125× fewer FLOPs than X @ (Aᵀ @ Bᵀ).

Although matrix multiplication is not commutative (AB≠BAAB \ne BA), it IS associative: (AB)C=A(BC)(AB)C = A(BC). Both groupings give the exact same numbers, yet their runtime can differ by orders of magnitude!

Worked Example 2 — LoRA Low-Rank Forward Pass FLOPs

Suppose we have a batch of 10241024 token vectors X∈R1024×4096X \in \mathbb{R}^{1024 \times 4096} passing through a rank-1616 LoRA adapter (AT∈R4096×16A^T \in \mathbb{R}^{4096 \times 16}, BT∈R16×4096B^T \in \mathbb{R}^{16 \times 4096}):

  • Smart Order (X @ A.T) @ B.T:
    1. (1024×4096)@(4096×16)→2⋅1024⋅4096⋅16≈134M FLOPs(1024 \times 4096) @ (4096 \times 16) \to 2 \cdot 1024 \cdot 4096 \cdot 16 \approx \mathbf{134\text{M FLOPs}}
    2. (1024×16)@(16×4096)→2⋅1024⋅16⋅4096≈134M FLOPs(1024 \times 16) @ (16 \times 4096) \to 2 \cdot 1024 \cdot 16 \cdot 4096 \approx \mathbf{134\text{M FLOPs}}
    • Total: ~268M FLOPs
  • Naive Order X @ (A.T @ B.T):
    1. Forming the dense 4096×40964096 \times 4096 matrix costs 537M537\text{M} FLOPs.
    2. Multiplying (1024×4096)@(4096×4096)(1024 \times 4096) @ (4096 \times 4096) costs 34.4 Billion FLOPs!
  • Always contract through the smallest bottleneck dimension first!
Formula Anatomy · Click Any Colored Piece to Decode It
Shape & Cost Blueprint: (M × K) @ (K × N) = (M × N)

How ML engineers instantly verify layers and count GPU FLOPs in their head!

Must Match & Collapses!

Columns of the left matrix MUST equal rows of the right matrix — otherwise PyTorch throws `RuntimeError: mat1 and mat2 shapes cannot be multiplied`!

In our example: Batch (32, 768) @ Weights (768, 512) → K = 768 matches!
Put it together with real numbers: Transformer Attention Q @ Kᵀ with shape (B, H, T, d) @ (B, H, d, T) → (B, H, T, T) — that's why standard Attention scales quadratically as O(T²) in context length!
Try It Yourself

Given u ∈ ℝ^(1000×1), v ∈ ℝ^(1000×1), and x ∈ ℝ^(1000×1), compare the cost of (u @ vᵀ) @ x versus u @ (vᵀ @ x).

3. Batched N-D Tensors, Broadcasting Rules & Einsum

Everyday Story First (Zero Math Yet!)

Suppose you have a (1000, 5) table of house features and want to subtract each column's average (5,). Do you write a loop? No — NumPy broadcasts the (5,) vector automatically across all 1,000 rows! Just watch out for the classic silent bug: adding a (1000,) row vector to a (1000, 1) column vector accidentally creates a giant (1000, 1000) matrix!

✓ Safe Row Centering (keepdims=True)X: ( 100 , 12 )mean: ( 100 , 1 ) ← stretches 1 → 12Result: ( 100 , 12 )Zero extra RAM copied — exact intended shape!✗ Deadly Silent Broadcasting Bug!y_true: ( 64 , 1 )y_pred: ( [1], 64 ) ← left-padded with 1!Result: ( 64 , 64 ) 💥No error thrown — quietly computes 4,096 wrong diffs!
Figure 3.2 — Right-Aligned Broadcasting: (N, D) − (N, 1) cleanly centers every row, whereas (64, 1) − (64,) silently explodes into a (64, 64) bug!

In Deep Learning, we almost never multiply isolated 2D matrices — we multiply 3D and 4D batched tensors like (B, H, T, D):

  • Rule for X @ Y: The last two axes perform matrix multiplication: (..., M, K) @ (..., K, N) -> (..., M, N). All leading axes broadcast!
  • The 3 Broadcasting Rules (always align shapes from the RIGHT):
    1. If arrays have different ranks, left-pad the shorter shape with 1s.
    2. Two axes are compatible if they are equal OR one of them is 1.
    3. Any axis of size 1 stretches virtually (zero RAM copied!) to match the other.
ML OperationInput ShapesOutput Shape
Linear Layer(B, T, D_in) @ (D_in, D_out)(B, T, D_out)
Multi-Head Attention Scores(B, H, T, D) @ (B, H, D, T)(B, H, T, T)
Attention Output(B, H, T, T) @ (B, H, T, D)(B, H, T, D)
Row-Wise Mean Centering(N, D) - (N, 1)(N, D)

Self-Documenting Tensor Algebra with einsum

In np.einsum / torch.einsum, every axis gets a letter. Any letter appearing on the left but omitted on the right is summed (contracted):

  • Attention scores: torch.einsum("bhtd,bhsd->bhts", Q, K)
  • Batch dot product: torch.einsum("bd,bd->b", u, v)
  • Outer product: torch.einsum("i,j->ij", a, b)
Pause & Check · Quick Intuition Pulse

Pause & Check: In PyTorch, you accidentally add tensor `a` of shape `(100, 1)` and tensor `b` of shape `(100,)`. Does PyTorch throw an error or silently produce a surprising shape?

Try It Yourself

What output shape does `np.einsum('btd,dk->btk', X, W)` produce if X has shape (8, 128, 512) and W has shape (512, 2048)?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Because matrices represent chained functions! If Matrix BB transforms a photo into hidden features, and Matrix AA transforms hidden features into 'Cat vs. Dog' scores, then applying BB followed by AA (A(B(x))) algebraically forces the Row × Column dot-product rule! Elementwise multiplication (A * B) couldn't mix features together at all!

Interactive Visual Lab
Lab Challenge: Click at least 2 different output cells C[i, j] in the grid (or press Auto-Play Sweep) to watch row i dot column j.
A (3×4) @ B (4×3) = C (3×3)
A (Row 0 highlighted)
1
2
0
1
3
1
2
0
0
2
1
3
B (Col 0 highlighted)
2
1
0
0
3
1
1
0
2
4
1
1
C (Click any cell!)
C[0, 0] = A[0, :] · B[:, 0] = 1×2 + 2×0 + 0×1 + 1×4 = 6
Geometric Takeaway: Inner dimensions contract (2MNK FLOPs), outer dimensions survive, associative order through bottlenecks yields 100×+ speedups, and broadcasting always aligns from the right.
Where This Powers Real ML, Deep Learning & GenAI

Transformer Attention & GQA

Attention scores (B, H, T_q, T_k) come from contracting head dim D via Q @ Kᵀ; Grouped-Query Attention shares fewer KV heads across query groups via broadcasting.

Backpropagation Through a Linear Layer

For Y = XW + b with X:(B, D_in), W:(D_in, D_out), dY:(B, D_out), shape matching immediately forces dX = dY @ Wᵀ and dW = Xᵀ @ dY!

LLM Prefill (Compute-Bound) vs Decode (Memory-Bound)

Prefill runs matrix-matrix GEMM (M = T tokens) saturating GPU Tensor Cores, whereas token-by-token decode runs matrix-vector GEMV (M = 1), bottlenecked by GPU memory bandwidth.

FlashAttention Tiling

Avoids materializing the giant O(T²) (B, H, T, T) attention matrix in GPU HBM by computing tiled block matmuls inside ultra-fast on-chip SRAM.

Production NumPy & PyTorch Code Patterns
import numpy as np

# 1. Elementwise (*) vs Matrix Multiply (@)
A = np.array([[1.0, 2.0], [3.0, 4.0]])
B = np.array([[5.0, 6.0], [7.0, 8.0]])
hadamard = A * B                       # [[5, 12], [21, 32]]
matmul   = A @ B                       # [[19, 22], [43, 50]]

# 2. Batched Multi-Head Attention: (B, H, T, D)
B_sz, H, T, D = 2, 4, 8, 16
rng = np.random.default_rng(0)
Q, K = rng.normal(size=(B_sz, H, T, D)), rng.normal(size=(B_sz, H, T, D))
scores     = (Q @ np.swapaxes(K, -2, -1)) / np.sqrt(D)       # (2, 4, 8, 8)
scores_ein = np.einsum("bhtd,bhsd->bhts", Q, K) / np.sqrt(D) # identical!
assert np.allclose(scores, scores_ein)

# 3. Always use keepdims=True when centering rows/columns!
X = rng.normal(size=(100, 12))
X_centered = X - X.mean(axis=1, keepdims=True)               # (100, 12) - (100, 1)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Silent broadcasting bugs between (N,) and (N, 1)
Best Practice: Subtracting y_pred (64,) from y_true (64, 1) silently produces a (64, 64) matrix instead of (64,)! Always assert shapes match or squeeze/keepdims explicitly.
Trap #2: Using `*` instead of `@` for matrix multiplication
Best Practice: `*` computes the elementwise Hadamard product; always use `@` or `torch.matmul` for matrix multiplication.
Trap #3: Calling `.view()` right after `.transpose()` in PyTorch
Best Practice: Transposing changes tensor strides without moving memory; use `.reshape(...)` or `.contiguous().view(...)` to avoid a RuntimeError.
Chapter Mastery Check (+50 XP)
Score: 0 / 5
1If A has shape (3, 5) and B has shape (5, 2), what is the shape of AB and roughly how many FLOPs (2MNK) does it take?
2Which identity is ALWAYS true for the transpose of a product of conformable matrices AB?
3In multi-head attention, Q and K both have shape (2, 8, 16, 64). What is the shape of Q @ K.transpose(-2, -1)?
4If y_true has shape (64, 1) and y_pred has shape (64,), what is the shape of (y_true - y_pred)?
5For Y = XW where X is (B, D_in), W is (D_in, D_out), and upstream gradient dY is (B, D_out), what is dW?

Apply What You Learned — Solve Matching Coding Problems