Technical report7 min read
How hotkernels works
A technical report on making NumPy faster from underneath: where the time goes, how a kernel is proven right, how the fast ones were found, and how they reach code that never asked for them.
NumPy is the layer everything else in scientific Python stands on, and for most of what it does it is very hard to beat. This report is about the places where it is not: a short list of everyday operations where the loop inside NumPy runs several times slower than the processor allows, and what it took to replace those loops without anyone's code having to change.
It is written for someone who has used NumPy for years, is comfortable with the mathematics, and has never needed to read assembly. There is no assembly tutorial here. What there is instead is the reasoning: where the time goes, what the hardware can do that a compiler will not ask of it, how you prove a hand-written loop is right when nobody is going to read it, and what the numbers look like when you are honest about their limits.
The short version
- The opportunity is real but narrow. Measured against the simplest correct C loop, NumPy on an Apple M1 Pro is behind by 1.5x to 7x on boolean masks,
cumsum,clip,histogram,bincount,searchsortedand a few others, and level or ahead on almost everything else. Chapter 1. - The gains come from four ideas, not from cleverness with instructions: do several elements per step, keep steps independent of each other, never let a branch depend on the data, and respect the caches. Chapter 2.
- Correctness is decided by a program. A judge compares each kernel with NumPy on thousands of generated inputs (18,081 for
argmax), with every buffer placed against memory the process may not touch, and decides with a bootstrap test whether a change made it faster. Chapter 3. - The kernels were written by coding agents in a loop against that judge: 442 logged attempts across 49 kernels, of which 287 were kept and 155 thrown away. Chapter 4.
- Assembly beat the compiler for 39 of the 49 kernels on ARM64 and 42 on x86-64; the others ship as their C. On the M1 Pro all 41 kernels measured there beat NumPy at every size measured. Chapters 5 and 6.
- They reach unmodified code by changing a handful of function pointers inside NumPy. A call no kernel takes costs about a nanosecond more. Chapter 7.
- Several results are narrower than their headline, and the judge has blind spots. Chapter 8.
- Every kernel exists for x86-64 with AVX2 as well, written against the same specs and the same judge. On an Intel Core i5-14600KF NumPy already has vector loops for
argmax,clipandastype, so those gain less; where NumPy is still scalar the gains are of the same kind as on ARM64. Chapter 9. - A kernel for a whole expression needs the expression whole, which no hook sees. A lazy layer, designed and prototyped but not in the package, writes NumPy code down as a graph and computes it on request, with NumPy’s results bit for bit. Chapter 10.
- On that graph, fusion computes an expression in one pass, with eighty-one kernels that keep NumPy’s bits and are checked by the judge. With
hotkernels.install()in effect, against plain NumPy, the programs made of expressions on large arrays run up to 2.80x faster on an Apple M1 Pro and 3.09x on an Intel Core i5-14600KF, both the cavity flow, whereinstall()alone gives 1.00x; of the twenty-six programs measured, one is behind NumPy on the M1 Pro, by 2%, and four on the i5-14600KF, by 3% to 15%. It is a prototype too. Chapters 11 and 12. - The workloads are timed run by run, on plain NumPy and with
install(), so a change to the package that made them faster or slower shows where it landed. Chapter 13.
The whole system on one page
flowchart TD survey["<b>Survey</b><br/>time NumPy against naive C<br/>for 61 operation variants"] spec["<b>Spec and reference</b><br/>spec.py: signature and NumPy oracle<br/>naive.c: the simplest correct loop"] agent["<b>Coding agent</b><br/>edits one file: kernel.s"] judge["<b>Judge</b><br/>lint, thousands of cases on guarded memory,<br/>calling convention, bootstrap timing"] log["attempts.md<br/>every attempt, kept or not"] kernels["<b>49 kernels</b><br/>ARM64 NEON and x86-64 AVX2,<br/>assembly where it beats the C"] fused["<b>81 fused kernels</b><br/>the lazy layer's prototype,<br/>not in the package"] binding["<b>Binding</b><br/>seven kinds of hook, into NumPy and bottleneck"] check["<b>Delivery check</b><br/>436,501 calls with and without,<br/>plus NumPy's own test suite"] user["<b>Your code</b><br/>import hotkernels; hotkernels.install()"] survey -->|"shortlist: where NumPy is behind"| spec spec -->|"reviewed by a person, then locked"| agent agent -->|"check, then compare"| judge judge -.->|"correct and significantly faster: commit<br/>anything else: revert"| agent agent --> log judge -->|"final verdict"| kernels judge -->|"final verdict"| fused fused -->|"from a clone: fuse.enable(),<br/>with install() in effect"| user kernels --> binding binding --> check check --> user class judge,kernels hot class user np
The project’s design is in docs/core-design.md. Three things in that picture carry the weight of the project:
- The reference. For every kernel a person writes two small files: a spec that says how to call the kernel and which NumPy expression gives the right answer, and the most naive C loop that computes the same thing. Everything else is measured against these, so they are reviewed by a person and then locked.
- The judge. It is the only reviewer the assembly ever gets. It has to be strict about correctness and honest about the uncertainty in a timing.
- The binding. A kernel is a native function over a flat buffer. Getting
x[mask]in someone’s notebook to call it, without breaking anything when the array is strided, or a subclass, or of another type, is a separate problem and about half the work.
Reading guide
Each chapter stands on the ones before it, but they are written to be read on their own if you only care about one.
- 1Where NumPy leaves time on the tableA NumPy call is a fixed cost plus a loop. Measuring both, operation by operation, shows which loops are worth rewriting and which are already as fast as they can be.
- 2The machine, in fifteen minutesEverything about a processor that the rest of this report leans on: vector registers, dependency chains, branch prediction, caches, and what a compiler is not allowed to do.
- 3The judgeNobody reads the assembly line by line. A program decides whether a kernel is correct, whether it is safe, and whether it is faster, and it has to be right about all three.
- 4Agents in a loopThe kernels were written by coding agents under one rule: keep an edit only if the judge says it is correct and significantly faster. Every attempt is on record, including the ones that failed.
- 5Kernels I: finding and selectingargmax, boolean masks, membership tests and binary search. Four problems where the obvious loop is held back by a branch or a chain, and the tricks that remove it.
- 6Kernels II: adding and countingRunning sums, byte sums, counts, histograms and clipping. Where floating-point rules decide what is allowed, and where a proof replaces arithmetic.
- 7Into NumPyA fast function nobody calls is worth nothing. Seven kinds of hook, each one pointer changed in place, route unmodified NumPy code to the kernels, and a call no kernel takes pays a few nanoseconds at most.
- 8Results, and what they do not sayEvery number, where it came from, and the cases where the result is narrower than the headline.
- 9The same kernels on a second architectureThe 49 kernels for x86-64 with AVX2, written against the same specs and judge as ARM64: what carried over, what did not, and what they are worth where NumPy already has vector loops.
- 10Writing the program down: a lazy layerA design and a prototype for NumPy code whose operations become a graph, computed when the program asks, with NumPy's results bit for bit. The layer by itself makes nothing faster; its graph is what lets the next two chapters compute a whole expression in one pass.
- 11Fusion: one pass for a whole expressionHow the lazy layer's graph is computed faster than one NumPy call per operation, with NumPy's bits: patterns read off the kernels' own specs, programs of kernel calls run a cache-sized block at a time, and the rules that keep every result exact.
- 12What fusion gained, and what is leftTwenty-six programs run four ways and ten more from other codebases, on an Apple M1 Pro and an Intel Core i5-14600KF, with hotkernels.install() in effect: where fusion wins, where it costs, and what no fusion could take.
- 13Over timeHow much faster the workloads run with hotkernels, run by run, with the merges that changed the package marked where they landed.
Ground rules for the numbers
Every figure in this report was measured natively, and each says which machine it is from. Unless it says otherwise, a figure is from an Apple M1 Pro running macOS, NumPy 2.5.5 and Apple clang 21. The x86-64 figures, in chapter 9 and at the end of chapter 12, are from an Intel Core i5-14600KF running Linux, NumPy 2.5.5 and clang 21.1.8, and the workloads of chapter 13 from an Apple M4 Max. A kernel is timed on a single core. Three kinds of number appear, and they are not interchangeable:
| Number | What is timed | Where it is honest |
|---|---|---|
| vs naive C | The kernel against the reference loop compiled with clang -O3, both called from C |
Everywhere. This is the comparison that says what hand-written assembly added |
| vs NumPy | The kernel called from C against the NumPy statement called from Python | At large sizes. At small sizes it flatters the kernel, because NumPy pays its per-call cost and the kernel does not |
| from Python | One Python statement, on plain NumPy and again after install() |
Everywhere. This is what a user gets, and it includes the binding |
When a speedup carries an interval, as in 1.21x [1.19 – 1.23], the bracket is a 95% bootstrap confidence interval, and “significant” means that interval excludes 1.0. Chapter 3 explains how it is computed and lets you play with it.