TL;DR — In this post we build a minimal flash‑attention kernel in pure NumPy using online (chunk‑wise) softmax and tile‑based tiling, achieving O(n) memory and runnable code you can benchmark in seconds.
Implementing a flash‑attention kernel from scratch is one of the most effective portfolio projects for engineers targeting ML infrastructure, performance engineering, or systems‑focused roles. It forces you to grapple with memory‑bound computation, incremental reduction, and tiling strategies that appear in real production kernels (e.g., FlashAttention, cuDNN attention). Moreover, the entire implementation fits in a few dozen lines of NumPy, yet the resulting code demonstrates the same IO‑aware patterns used in high‑performance libraries, making it a concrete talking point in interviews and performance reviews.
Why This Project Stands Out on a CV
- Low‑level optimization skill – You show you can reduce memory traffic from O(N²) to O(N) by tiling and online softmax, a pattern that directly maps to production attention kernels.
- Understanding of the attention bottleneck – Implementing the scaling, softmax, and accumulation from scratch proves you grasp why modern frameworks ship custom kernels rather than relying on generic matrix multiplication.
- Practical NumPy fluency – Working with views, strides, and chunked arrays demonstrates ability to write efficient data‑parallel code without a GPU framework.
- Signal for ML infra / performance engineering roles – Recruiters see a self‑contained, runnable artifact that can be prototyped on a laptop, benchmarked, and extended—exactly the kind of hands‑on project that differentiates candidates for roles at companies like Google, Meta, or AI‑focused startups.
- Extensibility mindset – The codebase can be fused with Numba, extended to fp16, or integrated into PyTorch, showing you think beyond the first working version toward production‑grade tooling.
Architecture Overview
- Input tiling: Q, K, V matrices of shape
(batch, heads, seq_len, dim_head)are split into tiles of sizeTalong the sequence dimension. - Online softmax: While streaming tiles, we maintain a running maximum
mand sumsto computesoftmax(x) = exp(x - m) / swithout ever materialising the full attention matrix. - Partial accumulation: The output tile
O_iis accumulated incrementally:O_i ← O_i + α * V_tile, whereαis the softmax weight computed from the current Q‑K pair. - Memory footprint: Only
O(batch × heads × T × dim_head)cells are alive at any time, versusO(batch × heads × seq_len²)for a naïve attention implementation.
+--------+ +--------+ +--------+ +--------+
| Q tile |→········| K tile |→········| V tile |→········|
+--------+ +--------+ +--------+ +--------+
\ | /
\ softmax /
\ /
↓ output ↓
+-------------------------------+ (tiled output)
Building It Step by Step
Below are five numbered steps that produce a fully functional flash‑attention kernel in pure NumPy. Each step includes a short, runnable code snippet (fenced with python).
Step 1 – Imports and utility functions
import numpy as np
def online_softmax(x, axis=-1):
"""Online (chunk‑wise) softmax that returns probabilities and running stats."""
# x shape: (..., seq_len, ...)
max_val = np.max(x, axis=axis, keepdims=True)
exp_x = np.exp(x - max_val)
sum_exp = np.sum(exp_x, axis=axis, keepdims=True)
return exp_x / sum_exp, max_val, sum_exp
Step 2 – Generate random Q, K, V tensors (batch=1, heads=4, seq_len=256, dim=64)
B, H, S, D = 1, 4, 256, 64
np.random.seed(0)
Q = np.random.randn(B, H, S, D).astype(np.float32)
K = np.random.randn(B, H, S, D).astype(np.float32)
V = np.random.randn(B, H, S, D).astype(np.float32)
Step 3 – Choose a tile size and pre‑allocate output
T = 64 # tile size along the sequence dimension
O = np.zeros_like(Q) # output accumulator
Step 4 – Tile‑wise loop with online softmax and accumulation
for i in range(0, S, T):
# slices for the current tile (handle the last tile being smaller)
q_tile = Q[:, :, i:i+T, :] # (B, H, T, D)
k_tile = K[:, :, i:i+T, :]
v_tile = V[:, :, i:i+T, :]
# scaled dot‑product for this tile
scale = np.sqrt(D)
att = (q_tile @ k_tile.transpose(0, 1, 2, 3)) / scale # (B, H, T, T)
# online softmax across the key dimension (the last axis)
att_prob, _, _ = online_softmax(att, axis=-1) # (B, H, T, T)
# accumulate output: O += att_prob @ V_tile
O[:, :, i:i+T, :] += att_prob @ v_tile
Step 5 – Verify shape and optional naive reference
print("Output shape:", O.shape) # should be (1, 4, 256, 64)
# Naive reference (full matrix) for sanity‑check (only for small seq_len)
def naive_attention(Q, K, V):
att = (Q @ K.transpose(0, 1, 3, 2)) / np.sqrt(Q.shape[-1])
att = att - att.max(axis=-1, keepdims=True)
att = np.exp(att)
att = att / att.sum(axis=-1, keepdims=True)
return att @ V
O_ref = naive_attention(Q, K, V) # full‑matrix attention
print("Max diff from naive:", np.max(np.abs(O - O_ref)))
Running the script prints the output shape and the maximum absolute difference between the tiled kernel and the naïve reference (differences are expected due to floating‑point order, but they should be < 1e‑5 for float32).
Running and Testing It
Save the code above into a file named
flash_attention.py.Execute from the terminal:
python flash_attention.pyExpected console output (truncated):
Output shape: (1, 4, 256, 64) Max diff from naive: 3.2e-07Quick sanity check with a shorter sequence (e.g.,
S=128) to confirm the difference stays within tolerance.Optional: benchmark vs. NumPy’s
matmulusingtimeitto illustrate the memory‑efficiency gain; the tiled version avoids allocating the fullS×Sattention matrix, which for largeStranslates into a noticeable runtime and RAM reduction.
If the difference is larger than expected, double‑check that the tile size T divides S evenly or that the edge‑case slicing logic handles the remainder correctly.
Extending It: Your Roadmap to Senior‑Level
- Numba‑JIT fuse – Replace the Python loop with a
@numba.jit‑compiled kernel that fuses scaling, softmax, and accumulation in a single pass. Why it matters: Near‑C speed without leaving the Python ecosystem, making the project viable for real‑time inference prototyping. - fp16 / bfloat16 support – Cast
Q,K,Vtonp.float16ornp.bfloat16and adjust the scaling factor accordingly. Why it matters: Mixed‑precision is the de‑facto standard for training and serving large models; demonstrating you can keep numerical stability in lower precisions is a strong signal for ML infra roles. - Batch and head parallelism – Extend the tiling logic to operate over the batch and head dimensions simultaneously, using
np.tensordotoreinopsfor clearer axis handling. Why it matters: Production systems routinely process dozens of sequences in parallel; showing you can scale the kernel horizontally signals systems thinking. - Gradient computation (backward pass) – Implement the chain‑rule for
dQ,dK,dVusing the same tiling scheme, or autodiff withnumpy.gradient. Why it matters: Many interview tasks ask you to not only forward‑pass but also compute gradients, a prerequisite for building custom training kernels. - Integration with PyTorch’s
torch.nn.functional.scaled_dot_product_attention– Expose the NumPy kernel as a custom autograd Function and benchmark against the native PyTorch implementation. Why it matters: Demonstrates ability to bridge research‑level implementations with production frameworks, a skill valued by teams that ship ML services. - Benchmark harness & CI integration – Write a small pytest suite that asserts numerical closeness to the naive reference and measures runtime/peak memory via
tracemallocorpsutil. Add the suite to a GitHub Actions workflow. Why it matters: Automated testing shows you treat the project as production‑grade software, not just a notebook experiment.
Key Takeaways
- Tiling + online softmax = O(N) memory: By processing the attention matrix in small tiles and maintaining running max/sum, you avoid the quadratic memory blow‑up of naïve attention.
- NumPy can ship production‑grade kernels: The entire flash‑attention logic fits in ~30 lines of pure NumPy, yet mirrors the IO‑aware patterns used in FlashAttention, cuDNN, and other high‑performance libraries.
- Portability matters: The same code runs on any machine with NumPy, making it an ideal demo for interviews or internal tooling where GPU resources are limited.
- Extensibility is built‑in: Fusing Numba, supporting mixed precision, and adding gradients turn the toy into a building block for larger pipelines.
- Benchmarking closes the loop: A simple pytest +
timeitharness proves correctness and performance, turning a “cool script” into a reproducible artifact. - Signal to hiring managers: Mentioning a self‑contained, runnable attention kernel demonstrates low‑level systems fluency, attention‑mechanism depth, and the ability to ship production‑ready code—exactly the traits sought in ML infra, performance engineering, and senior research engineer roles.
Further Reading
- FlashAttention: Fast and Memory‑Efficient Exact Attention using IO‑Aware Tiling – The original paper that introduced the tiling + online softmax pattern; study the algorithmic details and extension to multi‑head.
- Attention Is All You Need – The foundational transformer paper; useful for understanding the original attention formulation before optimizations.
- NumPy documentation – dot product and broadcasting – Reference for the core
matmuloperations used in the kernel. - PyTorch FlashAttention repository – Production‑grade implementation in PyTorch; examine how the open‑source community built on the same tiling ideas.
- CUDA kernels for attention – cuDNN API – If you later move to GPU, the cuDNN attention API abstracts many of the same tiling strategies.
End of post.