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
Matrix Multiplication (GEMM) is 95% of all GPU compute in Deep Learning — from Linear Layers to Transformer Attention!
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!
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.
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!
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?
- 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.
Every neural network forward pass and backward pass is fundamentally a sequence of matrix multiplications (GEMMs) and broadcasted elementwise operations. Start by mastering simple hand multiplication — the exact same rule scales seamlessly to 70-billion-parameter LLMs!
1. Matrix Addition, Scaling & Hadamard Product vs. Matrix Multiplication
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!
First, never confuse elementwise operations with matrix multiplication:
- Matrix Addition (): Requires identical shapes . Simply add matching cells: .
- Hadamard (Elementwise) Product (, written
A * Bin Python): Also requires identical shapes and multiplies cell-by-cell: (used in gating layers like SwiGLU and LSTM gates!). - Matrix Multiplication (, written
A @ Bin Python): Combines rows of with columns of via dot products:
The Shape Compatibility Law
For and :
- The inner dimensions () must match — and they contract (disappear).
- The outer dimensions () survive as the output shape.
- Exact FLOPs cost: Each of the output cells does multiplies and adds floating-point operations!
Worked Example 1 — Multiplying Two Matrices Step-by-Step by Hand
Let (shape ) and (shape ).
- Inner dimensions match (), so output has shape :
Two Crucial Algebraic Rules (Watch Out!)
- Order Matters (): Above, is , whereas is ! Even for square matrices, multiplying in the opposite order almost always gives a different answer.
- Transpose Reverses Order: ("Shoes & Socks rule": take off your shoes before your socks!).
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!
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
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!
Although matrix multiplication is not commutative (), it IS associative: . 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 token vectors passing through a rank- LoRA adapter (, ):
- Smart Order
(X @ A.T) @ B.T:- Total: ~268M FLOPs
- Naive Order
X @ (A.T @ B.T):- Forming the dense matrix costs FLOPs.
- Multiplying costs 34.4 Billion FLOPs!
- Always contract through the smallest bottleneck dimension first!
How ML engineers instantly verify layers and count GPU FLOPs in their head!
Columns of the left matrix MUST equal rows of the right matrix — otherwise PyTorch throws `RuntimeError: mat1 and mat2 shapes cannot be multiplied`!
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
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!
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):
- If arrays have different ranks, left-pad the shorter shape with
1s. - Two axes are compatible if they are equal OR one of them is
1. - Any axis of size
1stretches virtually (zero RAM copied!) to match the other.
- If arrays have different ranks, left-pad the shorter shape with
| ML Operation | Input Shapes | Output 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: 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?
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)?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Because matrices represent chained functions! If Matrix transforms a photo into hidden features, and Matrix transforms hidden features into 'Cat vs. Dog' scores, then applying followed by (A(B(x))) algebraically forces the Row × Column dot-product rule! Elementwise multiplication (A * B) couldn't mix features together at all!
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.
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)