Linear Algebra for AI Infrastructure
Tensors, shapes, matrix multiplication, GEMM tiling, and the math that connects model architecture to hardware performance.
AI infrastructure doesn’t require proving theorems daily, but it requires that when you see a formula, you can immediately answer three engineering questions: what shape are the tensors, how much compute and memory does it cost, and what can go wrong numerically?
This chapter builds that intuition for linear algebra — the mathematical foundation underlying every matrix multiply, every attention computation, and every GPU kernel optimization.
1. Three Questions for Every Formula
Take the language model output projection as an example:
Question 1 — Shape: Do the inner dimensions match? ✓. Output is .
Question 2 — Cost: Each output element requires multiply-adds. Total: FLOPs (counting one multiply + one add as 2 ops).
Question 3 — Risk: Large weights → large logits → numerical instability in softmax. Need to consider dtype, memory layout, tiling strategy, and numerical stability.
These three questions apply to every operation in the AI infrastructure stack.
Notation
| Symbol | Meaning |
|---|---|
| Scalar | |
| Vector | |
| Matrix or higher-order tensor | |
| Batch size, sequence length, hidden size, vocabulary size | |
| Number of attention heads, dimension per head | |
| Element-wise multiplication |
2. Scalars, Vectors, Matrices, and Tensors
- Scalar: a single number — e.g., learning rate
- Vector: 1D array — e.g., a token’s hidden state
- Matrix: 2D array — e.g., linear layer weights
- Tensor: N-dimensional array — e.g., a batch of sequences
In engineering, a “tensor” carries more than just shape:
data pointer + shape + stride + dtype + device + layout
Two tensors with the same shape may have different memory layouts. Two tensors with the same values may have different dtypes and different numerical error characteristics.
Shape, Indexing, and Stride
A row-major matrix:
Stored contiguously as [1, 2, 3, 4, 5, 6] with stride . Element is at offset .
Transpose has shape and stride — no data copy needed. But scanning along the last dimension is no longer contiguous in memory — this matters for GPU coalescing.
When you see
view,reshape,transpose, orcontiguousin PyTorch, always think about both the logical dimensions and the physical memory layout.
Broadcasting
Element-wise operations require matching shapes. Broadcasting allows dimensions of size 1 (or missing) to be logically expanded:
The bias is reused across batch and sequence dimensions without copying.
Rules (align from the trailing dimension):
- Both sizes are equal, or
- One of them is 1, or
- One side has no dimension there
Danger: Wrong shapes may “accidentally broadcast” — code runs without error but computes the wrong thing. Always verify shapes explicitly.
Norms
Norms measure the “size” of a vector or matrix:
- L1 norm: — used in sparse regularization
- L2 norm: — Euclidean distance, used in gradient clipping
- Frobenius norm: — the matrix equivalent of L2
- Max norm:
In AI infra, norms appear everywhere:
- Gradient clipping: if , scale down
- Weight decay: adds to loss, penalizing large weights
- Layer normalization: divides by (related to RMS norm)
3. Dot Product and Matrix Multiplication
Dot Product
Two intuitions:
- Weighted sum: is weights, is values
- Similarity: normalized dot product = cosine similarity. Larger means more aligned.
This is the core operation inside attention: query-key dot products measure how much each key “matches” the query.
Matrix Multiplication
Matrix multiply is a batch of dot products:
For and :
- Output shape:
- FLOPs: (each of elements requires multiply-adds)
- Memory reads: elements
- Memory writes: elements
Batched Matrix Multiplication
In transformers, matmuls are batched over multiple heads and batch dimensions:
Shape:
This is exactly the attention score computation: .
4. GEMM Tiling: Why It Matters for GPU Kernels
General Matrix Multiply (GEMM) is the most performance-critical operation in deep learning. Understanding tiling explains why GPU kernels are fast — and when they’re not.
Block Decomposition
Split matrices into tiles along , , and the reduction dimension :
Each output tile accumulates partial products along . The GPU kernel:
- Loads a tile of and into shared memory
- Computes partial output using registers (high reuse)
- Iterates along , accumulating
- Writes the final output tile back to HBM
This changes data movement order, not the mathematical result.
Arithmetic Intensity of GEMM
For a multiply:
For square matrices ():
A 4096×4096 GEMM has AI ≈ 1365 — well above the H100’s ops:byte ratio of 295. Large GEMMs are compute-bound. But small GEMMs (like per-token decode with ) have AI ≈ 1 — severely memory-bound.
This is why LLM decode is slow: each token generates a GEMM with , which can never saturate GPU compute.
Tile Size Tradeoffs
| Larger tiles | Smaller tiles |
|---|---|
| ✅ Higher data reuse → higher arithmetic intensity | ✅ Less shared memory per tile → more tiles per SM |
| ✅ Fewer trips to HBM | ✅ Better occupancy |
| ❌ More shared memory → lower occupancy | ❌ More HBM trips |
| ❌ Tail blocks waste compute if dimensions aren’t divisible | ✅ Less waste on irregular shapes |
Optimal tile size depends on the GPU’s shared memory capacity, register count, and the specific matrix dimensions. This is what autotuners like cuBLAS and Triton’s compiler optimize.
5. SVD and Low-Rank Approximation (LoRA Connection)
Any matrix can be decomposed:
Where and are orthogonal matrices and is diagonal with singular values .
Keeping only the top singular values gives the best rank- approximation:
Why this matters for AI infra: LoRA (Low-Rank Adaptation) freezes the pretrained weight and adds a low-rank update:
Instead of fine-tuning parameters, you train only parameters. With and , that’s a 128× parameter reduction.
This directly impacts infrastructure: LoRA adapters are small enough to hot-swap in serving, store hundreds per GPU, and fine-tune on a single consumer GPU.
Self-Check
- Given two tensor shapes, determine if matrix multiplication is valid and predict the output shape
- Calculate the FLOPs for a given matrix multiplication
- Explain why large GEMMs are compute-bound but small GEMMs () are memory-bound
- Explain stride and why transpose doesn’t copy data
- Identify broadcasting bugs: given two shapes, predict if they broadcast and what the result shape is
- Explain why LoRA reduces trainable parameters and its infrastructure implications
- Calculate arithmetic intensity for a GEMM and compare to the GPU’s ops:byte ratio
References
- The Matrix Cookbook — comprehensive matrix identity reference
- 3Blue1Brown — Essence of Linear Algebra — visual intuition
- LoRA: Low-Rank Adaptation of Large Language Models
- NVIDIA cuBLAS Documentation