HJ.
← All writing

DOWN THE STACK / PHASE 1

Phase 1: From "what is attention?" to HNSW in C++

"If we understand something, we can explain it clearly in writing."
Leslie Lamport · Who Builds a House Without Drawing Blueprints?, 2015

I've been a backend engineer for 7+ years (Python, Go, Node). In March I started an 18-month learning plan focused on AI systems research engineering: making models run faster and cheaper, not training them. Phase 1 was about two weeks. Here's what I learned.

Picking a direction

My first question was which AI skill a backend engineer should learn. The first answers pointed at fine-tuning and data science, which isn't what I want. What I actually want is systems work: inference, memory, vector search. My OS and low-level background turns out to be an asset here. The loop I settled on: read a paper, implement it, benchmark it, hit a wall, fill that one gap, repeat.

FlashAttention: my first paper

I started with FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (Tri Dao et al.). My first read was shaky. I could say "it's faster because it uses SRAM," but I didn't understand the code. Why transpose? Why divide by sqrt(d)? What are Q, K and V?

So I stepped back. I watched 3Blue1Brown's linear algebra series (chapters 1-4) and the transformers video, and wrote my own summary of attention: every token gets a query, key and value; Q·K scores how related two tokens are; softmax turns the scores into weights; the weights mix the values.

Then I built it up step by step in NumPy:

  1. Plain attention: softmax(QK^T / sqrt(d)) · V
  2. Online softmax: keep a running max and running sum, and rescale old results when a bigger max shows up
  3. Tiled attention: the same trick on blocks of Q, K and V, so the full N×N matrix never exists
  4. Benchmarks against naive attention on my M1 MacBook Air

The memory results made it click (d=64, block size 64):

N Naive memory Tiled memory Saved
256 1.6 MB 294 KB 82%
1024 24.5 MB 677 KB 97%
4096 386 MB 2.2 MB 99%

Naive attention holds the whole N×N matrix, so memory grows with N². Tiled attention only ever holds one block, so memory stays almost flat. The output matched naive attention every time. In Python the tiled version wasn't faster, because of loop overhead, but memory was the point. The one-line summary of the paper: recomputing is cheaper than moving memory.

Vector search: four ways to find the nearest neighbor

Next I switched to vector search, the core of vector databases.

  • Brute force (NumPy): check every vector. Always correct, but it scales with N: about half a second for 1M vectors.
  • KD-tree: split the space along one axis at a time. At 2 dimensions it was about 47x faster than brute force. At 64 dimensions it was about 10x slower, because it ends up checking almost every branch anyway. That's the curse of dimensionality, and it's why KD-trees don't work for real embeddings (768+ dimensions).
  • Flat graph: connect each vector to its nearest neighbors and walk greedily toward the query. It worked, but only 38% recall.
  • HNSW (Hierarchical Navigable Small World paper): the same graph idea in layers. Sparse top layers make big jumps, and the bottom layer does the fine search, like express trains and local trains. My Python version hit 96% recall. At 20,000 vectors it finally beat NumPy brute force on search time (0.0041s vs 0.0065s).

The key idea: HNSW is approximate. You trade a little accuracy for speed that barely grows as the data grows, and ef is the knob between recall and speed.

A tiny vector database

I wrapped HNSW in a small VectorDB class: insert with string IDs and metadata, search with metadata filters, delete (by marking nodes as deleted rather than removing them), and save/load with pickle. My first load re-inserted every vector, which meant rebuilding the whole graph. Saving the neighbor lists and restoring them directly made loading instant.

Learning C++ (the slow part)

To see why production vector search runs in C++, I rewrote brute force and then HNSW in C++. It was slow going: compiler errors, pointers, segfaults. I honestly wondered if I was just too slow. What I learned:

  • Brute force in C++ with no flags was about as fast as NumPy (0.52s vs 0.51s). With -O2 it took 0.12s, about 4x faster. One compiler flag.
  • Passing vectors by reference instead of copying them cut the HNSW build time from about 20s to 6.7s.
  • Final comparison: HNSW build went from 132s in Python to about 6.7s in C++, and search was around 10x faster. Recall came out at 76% vs 96% in Python, so I still need to tune that.

What I'm taking away

  • Understand the math first, and most of the code confusion goes away.
  • Build the naive version, feel where it hurts, then build the fix. Each step motivated the next one.
  • Write in plain words. My write-ups aren't in "research language," and that's fine.
  • Benchmark properly: warm up first, run several times and take the median. Single runs on a laptop are noisy.

Up next (Phase 2): GPU programming with Triton, reading production code (hnswlib), quantization, and a tiny inference server.