Skip to content

About

Reproducible cross-layer optimization of HNSW vector search on Apple Silicon

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

HNSW vector search on Apple Silicon

A reproducible performance case study: making approximate nearest-neighbor search in hnswlib faster on an Apple M3 Max without changing a single result. Every optimized variant must return exactly the baseline's top-10 neighbors and distances, so no speedup can come from returning worse answers.

Horizontal bars of cumulative speedup on SIFT1M: baseline 1.00, plus whole-vector prefetch 2.40, plus split layout 2.55, plus RCM order 2.58, plus PGO 2.60, plus branch-free visited check 2.69, plus lossless uint8 vectors 4.12.

Reproduce

git clone https://github.com/ElyasEbrahim/SoftwareOptimization.git
cd SoftwareOptimization
./run_detached.sh

This starts reproduce.sh in a detached tmux session, so the run keeps going if you close the terminal or the app that launched it. It also keeps the Mac awake for the length of the run. Run ./reproduce.sh directly to watch it in the foreground instead.

The pipeline pins hnswlib to commit ca42672 and downloads SIFT1M (sift-128-euclidean.hdf5, 501 MB) from ann-benchmarks.com, checking both by SHA-256. It then builds every variant, builds or reuses the index, tunes, measures, and writes everything to results/runs/<timestamp>/. A full run from a fresh clone took 33 minutes on an M3 Max with the default 5 cycles, including the download and the 5-minute index build. With 10 cycles, expect about 45. It needs Xcode, Python 3 with the z3-solver package (version 5.4.1 was used), curl, and about 3 GB of free disk.

To rerun stages against the latest run, use ./reproduce.sh <stage>.... The stages, in order, are env, fetch, build, data, index, tune, matrix, scaling, bandwidth, verify, counters, and report. Set MATRIX_VARIANTS to a comma-separated list to measure only some variants. Set FORCE_INDEX=1 to rebuild the index and CYCLES=10 for enough measurement cycles to test significance.

Set DATASET=gist to run the same pipeline on GIST1M, which downloads gist-960-euclidean.hdf5 (3.6 GB). A 10-cycle GIST run took 64 minutes, including a 22-minute single-threaded index build.

The counters stage records hardware counters with Instruments. It needs full Xcode and can't record inside some sandboxes. If it fails, the run continues and prints how to rerun that stage.

Method

  • Workload: top-10 search over SIFT1M, which has 1M base vectors, 10,000 test queries, and 128 dimensions. Every component is an integer from 0 to 255, which the data stage checks.
  • Index: one HNSW graph (M=16, efConstruction=200, seed 100), built single-threaded so it is deterministic. Rebuilding it reproduces the same SHA-256.
  • Operating point: the smallest search setting that reaches 95% recall@10 (ef=52).
  • Baseline: unmodified hnswlib compiled with its own CMake flags for Clang (-O3 -ffast-math -march=native). The flags its Python package uses are measured too.
  • Fair tuning: the prefetch window and the PGO profile come from held-out queries drawn from the base vectors, never from the test queries.
  • Measurement: one thread at the highest scheduling priority. Each cycle runs every variant once in a shuffled order, with two warm-up and five timed rounds each.
  • Statistics: each effect is the median of its per-cycle throughput ratios, so slow drift on the machine cancels out. Each comes with a 95% bootstrap interval and an exact sign-flip test, adjusted across comparisons with Benjamini-Hochberg. Significance needs at least ten cycles.
  • Scaling: the baseline and the final stack run with 1 to 16 threads at user-interactive QoS, plus 4 threads at background QoS, which macOS confines to the efficiency cores.
  • Verification: every run saves its top-10 labels and distances, and their SHA-256 must equal the baseline's. An A/A control, the patched build with every feature turned off, should never come out significant.

Results

Five runs, one thread, at 95.04% recall@10:

Run Cycles Baseline QPS Best stack QPS Speedup
Pilot, 2026-11-23 5 9,372 24,731 2.62×
Replication, 2026-11-24 5 9,501 23,854 2.51×
Second layer, 2026-11-25 10 8,629 23,180 2.69×
Bandwidth, 2026-11-25 10 8,883 36,638 4.12×
Fresh clone, 2026-11-28 5 9,394 38,818 4.13×

The last two runs' best stack stores vectors as uint8, which the earlier runs didn't include. The fresh-clone run cloned this repository from GitHub and ran every stage, as a grader would, and every verification check passed. All 667 measured runs, across every configuration, thread count, and day, returned the same top-10 results byte for byte. Every rebuild of the index from scratch, including the fresh-clone run's, reproduced the same graph. Absolute throughput varied by up to 10% from day to day, while the key speedup ratios moved by less than 5%, which is why every effect is measured as a ratio within each cycle.

Effects from the 10-cycle runs, each tested for significance:

Layer Change Effect Significant
Memory hierarchy Whole-vector prefetch 2.41× yes
Data representation Lossless uint8 vectors, on top of the stack 1.53× yes
Compiler -ffast-math, versus the Python package's flags 1.58× yes
Data layout Vectors split from links, on top of prefetch 1.06× yes
Branches Branchless visited filter, on top of the stack 1.03× yes
Data layout RCM graph reordering, on top of prefetch and split 1.01× yes
Compiler PGO 1.00× no
ISA Hand-written NEON kernel 0.99× yes, slower
Loop Batched distances 0.99× no
Algorithm Early abandon of partial distances 0.93× yes, slower
  • SIFT's components are integers from 0 to 218, so storing them as uint8 loses nothing, and every distance stays exactly the same. This cuts memory from 652 to 268 bytes per vector. The float stacks use no extra memory.
  • Hardware counters show back-end stalls falling from 80% to 51% of pipeline capacity. The branchless filter cut discarded speculative work from 26% to 23%.
Two line charts of queries per second against threads. SIFT1M: the baseline reaches 88 thousand at 12 threads, the float stack flattens near 173 thousand, and the uint8 stack keeps rising to 342 thousand at 16. GIST1M: the baseline reaches 3 thousand, and the float stack flattens near 4.3 thousand from 6 threads on.

Thread scaling, analyzed with the USE method on memory bandwidth:

  • Utilization: measured random-read capacity peaks near 110 GB/s. At 12 threads the float stack demands up to 97 GB/s, 89% of capacity, while the baseline never exceeds 62%.
  • Saturation: the float stack's median query latency rises 59%, from 43 to 68 µs, between 1 and 12 threads, and its throughput falls at 14 and 16 threads. The baseline scales to 10.3× on the 12 performance cores, the float stack to only 7.5×.
  • Intervention: with the same search path and 4× fewer bytes per vector, the uint8 stack uses at most 43% of capacity, scales to 8.9× on 12 threads, and keeps climbing to 342,000 queries per second on 16 threads, 3.6× the baseline. That confirms bandwidth as the float stack's limit. Something else still caps the uint8 stack's scaling, and it hasn't been identified.
  • Errors: none. Every multi-threaded run returned the baseline's results.
  • Scheduling: at background QoS, which confines threads to the efficiency cores, 4 threads deliver only 1.1× to 1.2× one performance core.

Demand figures assume every access misses the caches, so they're upper bounds. Actual memory traffic wasn't measured.

Generality: GIST1M

One 10-cycle run on GIST1M: 960 dimensions, real-valued components, 1,000 queries, at ef=300, which gives 95.33% recall@10.

Change Effect Significant
Whole-vector prefetch 2.07× yes
-ffast-math, versus the Python package's flags 1.97× yes
Vectors split from links, on top of prefetch 1.06× yes
Branchless visited filter 1.01× no
RCM graph reordering, on top of prefetch and split 1.01× no
PGO, on top of the stack 1.01× no
Early abandon of partial distances 0.97× no
Best stack versus baseline 2.24× yes
  • Speedups: prefetching and the split layout carry over. The branchless filter's gain doesn't, because at 960 dimensions the distance arithmetic dominates each step. uint8 storage doesn't apply, because GIST is real-valued and the conversion would be lossy.
  • Bandwidth: each query touches up to 20 MB, from 5,186 distances of 3,840 bytes each. On one thread the best stack already demands up to 80% of one core's random-read bandwidth. With threads it saturates near 87 GB/s, 89% of capacity, from about 6 threads on. It scales to only 4.0× on 12 threads, against 6.2× for the baseline, and its advantage shrinks from 2.26× to 1.45×.
  • Exactness: every variant except the Python-flags build returned the baseline's results byte for byte. That includes hand-written NEON and early abandon, because in this build the compiler's vectorized loop rounds exactly like the hand-written kernel: 0 of 1 million random real-valued distances differed, at 128 and 960 dimensions. That's a property of this compiler and these flags, not something the proof guarantees. The Python-flags build sums in a different order, which changed the last bits of 92.7% of returned distances, by at most 2.6 parts per million. One query in 1,000 got a different top-10, and recall was unchanged.
  • Verification: the search-logic proofs don't depend on the data, and all five index rewrites passed the runtime check on GIST too, at 13.2 million neighbor entries each. The GIST index hash is pinned from its first build, and a rebuild hasn't yet confirmed it's deterministic.

Full numbers are in each run's summary.md. results/runs/20261124-index-rebuild-check/ is a run stopped on purpose after the index stage, kept for its index-determinism result.

Formal verification

Claim: for any query whose components are integers from 0 to 255, every optimized variant returns the same top-10 neighbors and distances as unmodified hnswlib on this index. ./reproduce.sh verify checks the whole argument in about a minute. It has three parts:

  1. Arithmetic (verify/kernels.py, using Z3's IEEE-754 float32 theory). On this data, every subtraction, square, addition, and fused multiply-add a kernel performs is exact, because every intermediate value is an integer below 2^24. So every kernel returns the exact integer distance in whatever order it sums. That covers the -ffast-math vectorized loop, hand-written NEON, early abandon's partial sums, and the uint8 kernel. The fused multiply-add is also checked on the real instruction for all 4.24 billion possible inputs.
  2. Search logic (verify/search.py, using Z3). Each change to the search loop is proved by an inductive step: if the original and changed loops agree before an iteration, they agree after it. This covers filter-first prefetching, the branch-free visited check, batched distances, early abandon, and graph reordering, for neighbor lists of any length and any distance values. Each proof's hypotheses are also checked for satisfiability, so none holds vacuously.
  3. Implementation (validate=1 in the benchmark). After every layout and order rewrite, each node's label, vector, and levels, and the order of each neighbor list, are compared with the original index: 22.1 million neighbor entries per configuration.

Each part has controls, deliberately broken versions that must fail and do:

  • summing beyond 2^24;
  • counting before writing in the branch-free filter;
  • abandoning early before the result set is full, or against too low a bound;
  • reordering a neighbor list;
  • a corrupted index.

The proof rests on five assumptions:

  • hnswlib's std::priority_queue behaves as a max-heap and orders elements by distance alone. Its comparator never reads node ids.
  • Prefetch instructions have no architectural effect. The Arm architecture defines them as hints.
  • The compiler is correct, and -ffast-math's assumptions hold, because the data contains no NaNs or infinities.
  • Concurrent queries don't interfere, because the index is read-only during search and each query takes its own visited list. This one is argued, not proved.
  • Every component is an integer from 0 to 255. The data stage checks this, and the uint8 conversion refuses any other value.

All 667 measured runs agree with the proof: every one returned the baseline's results byte for byte.

Layout

Path Contents
reproduce.sh The pipeline, stage by stage
run_detached.sh Starts the pipeline in a detached tmux session
bench/src/ Benchmark harness, data tools, and analysis scripts, including make_figures.py, which draws the figures
bench/patched/hnswlib/ hnswlib's headers with the optimizations behind compile-time flags, listed in its README
bench/build_variants.sh Builds every variant, including PGO
verify/ Z3 proofs of result equivalence and the hardware check
third_party/hnswlib/ Unmodified hnswlib at the pinned commit
results/runs/ One directory of raw and summary results per run
results/figures/ Figures drawn from those results
data/ Downloaded and derived data, kept out of Git

License

MIT; see LICENSE. hnswlib, vendored in third_party/hnswlib/ and modified in bench/patched/hnswlib/, is under the Apache License 2.0. The datasets aren't redistributed here; the pipeline downloads them from ann-benchmarks.com.

About

Reproducible cross-layer optimization of HNSW vector search on Apple Silicon

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages