| # Restructure the maths before optimizing the code |
|
|
| The biggest wins are algorithmic. A well-tiled implementation of the wrong algorithm loses to a |
| restructured one. Work through this before touching tile sizes. |
|
|
| ## Questions to ask |
|
|
| 1. **Can I avoid materializing the large intermediate?** (attention's N×N score matrix) |
| 2. **Can a sequential dependence become an associative reduction?** (scan, recurrence) |
| 3. **Can I trade compute for memory, or recompute instead of store?** (checkpointing, backward recompute) |
| 4. **Can I change what stays resident?** (block the loop so the working set fits smem/registers) |
| 5. **Does the output have structure the algorithm ignores?** (sparsity, low rank, symmetry, banding) |
|
|
| ## Catalog |
|
|
| | transform | what it buys | seen in | |
| |---|---|---| |
| | **online softmax** (running max + rescaled sum) | O(N²)→O(N) memory, single pass | FlashAttention | |
| | **chunked/blocked recurrence** | turns a sequential scan into a sequence of GEMMs | Mamba-2 SSD, Gated DeltaNet | |
| | **WY representation** | expresses a product of Householder-like updates as one matmul | DeltaNet family | |
| | **associative / Blelloch scan** | parallelizes a prefix dependence | cumsum, linear attention | |
| | **radix partitioning** | avoids a full sort for top-k / grouping | radix top-k, MoE token permute | |
| | **counting sort + exclusive scan** | stable grouping in two passes, no comparison sort | MoE dispatch | |
| | **low-rank factorization** | shrinks a GEMM's K | LoRA, MLA's compressed KV, PowerSGD | |
| | **absorb / fold weights** | removes an entire GEMM by folding it into a neighbour | MLA V-absorb | |
| | **split-K / stream-K** | fills the machine when M·N is too small for the SM count | skinny GEMMs | |
| | **recompute in backward** | trades FLOPs for HBM traffic | activation checkpointing | |
| | **two-pass → one-pass** | fuse statistics with the transform | fused LayerNorm/RMSNorm | |
| | **persistent kernel** | removes launch and pipeline-drain cost between stages | megakernels | |
| | **symmetry exploitation** | halves the work | `X @ X.T` is symmetric (Muon/Newton-Schulz) | |
|
|
| ## Sanity check before implementing |
|
|
| Compute the arithmetic intensity of the *restructured* algorithm and re-run the roofline. If the |
| restructure does not move you toward the compute-bound side (or cut absolute traffic), it is not |
| actually a win — write it down in the ledger and move on. |
|
|