hotkernels

Documentation37 min read

Get started

Install the package, add one line, and see what it did.

There is very little to do. Install the package, call install() once, and NumPy uses the kernels for the rest of the process.

Requirements

Machine A Mac with Apple Silicon (ARM64), or Linux on x86-64 with a processor of the x86-64-v3 level (AVX2, FMA, BMI2: Intel since 2013, AMD since 2015)
Python 3.11 or later, the standard build with the interpreter lock
NumPy 2.3 or a later NumPy 2

Wheels are published for CPython 3.11 to 3.14. With another Python the package is built from source when it is installed, which takes a few seconds and needs the Xcode command line tools (xcode-select --install) on a Mac, or a C compiler and GNU binutils on Linux.

Each figure on this site names the machine it was measured on: an Apple M1 Pro for ARM64, unless it says otherwise, and an Intel Core i5-14600KF for x86-64. On x86-64 the same calls are served by kernels written separately for it, and NumPy is faster to begin with for some of them, so the gains are not the same.

On any other machine the package still installs, with no compiler, and install() does nothing, so code that calls it stays portable.

Install

pip install hotkernels

or uv pip install hotkernels.

To work on the kernels themselves, clone the repository and run uv sync; the judge and the other development tools come with it.

Without changing your code

python -m hotkernels runs a script with hotkernels installed, as python would run it:

python -m hotkernels my_script.py --its --own --arguments
python -m hotkernels -m pytest            # a module, as python -m runs it
python -m hotkernels --report my_script.py  # print report() to standard error at the end

--inexact installs the kernels that are not bit-identical to NumPy as well.

Turn it on

import numpy as np
import hotkernels

hotkernels.install()            # NumPy now uses the kernels, in the whole process

x = np.random.standard_normal(1_000_000)
x[x > 0]                        # served by a kernel
np.clip(x, 0, 1)                # served by a kernel
x[::2].sum()                    # not something a kernel handles: NumPy does it, as before

hotkernels.uninstall()          # NumPy is exactly as it was

That is the whole interface:

Call What it does
hotkernels.install() Points NumPy at every kernel that returns NumPy’s result bit for bit
hotkernels.install(inexact=True) Also installs the two that do not: np.cumsum on float32 and float64
hotkernels.install(bottleneck=False) Leaves bottleneck’s functions alone: see What gets faster
hotkernels.uninstall() Puts every pointer back
with hotkernels.enabled(): Installs for the duration of a block, and on leaving it puts hotkernels back as the block found it. Takes inexact and bottleneck as install() does
hotkernels.report() What is installed, and how often each kernel ran

Importing the package changes nothing; only install() does. Calling it twice with the same arguments is harmless, and so is uninstall() without install(). Calling it with other arguments, install(inexact=True) after install() for instance, takes every hook out and puts them all back with the new arguments, and the counts in report() start again. So does enabled() with arguments that differ from the installation in force; with hotkernels.enabled(inexact=True): inside an install() turns the inexact kernels on for the block only.

install() never raises because of the machine, the Python or the NumPy it finds. It logs on the hotkernels logger: one line at the INFO level saying how many hooks are in place, or why there are none, and a warning for each hook that could not be applied or failed its self-test. report() lists the same hooks.

See what it did

print(hotkernels.report()) after your code has run:

hotkernels 0.3.1: installed, 47 of 49 kernels (NumPy 2.5.5)

NumPy call         Elements Kernel    Result            Kernel calls  Left to NumPy
np.argmax          float32  assembly  exact                        0              0
np.argmax          float64  assembly  exact                        1
argmax(axis=1)     float64  C         exact                        1
np.clip            float64  assembly  exact                        1
x[mask]            float64  assembly  exact                        1
x[mask] = v        float64  assembly  exact                        1              0
np.cumsum          int64    assembly  exact                        1              0
np.cumsum          float64  assembly  within tolerance not installed: needs install(inexact=True)
x.astype(float32)  uint8    C         exact                        1              3
np.sum             uint8    assembly  exact                        1              0
...

Left to NumPy is the column to read when nothing got faster. It counts calls that reached a hook and did not meet a kernel’s conditions: another element type, a strided array, an argument the kernel does not implement. A large number there tells you what your arrays look like.

Both columns count the calls you wrote. np.argmax(m, axis=1) is one call, however many rows NumPy splits it into, whether a kernel took its rows or NumPy did. The rows marked C are loops built into hotkernels rather than kernels; the first line does not count them among the kernels. Nor does it count the row elementwise ufuncs, marked NumPy: NumPy’s own loops, which hotkernels calls directly for small elementwise calls (see Things worth knowing). Its “Left to NumPy” counts every other ufunc call that reached the hook, including the ones NumPy’s own Python functions make inside your calls.

report() returns a hotkernels.Report, which printing renders as the table. Its fields can be read too: installed, inexact, unsupported (why install() did nothing, or None), version, numpy_version, problems (one line per hook not in place), and kernels, one entry per row, with the same columns as fields: name, numpy_call, elements, implementation, result, installed, note, calls and left_to_numpy. A test that must know a kernel ran can compare calls before and after.

What gets faster

A kernel takes a call only when the array is a plain, contiguous ndarray of the kernel’s element type and every other argument is one the kernel implements. Any other call goes to NumPy as it was written.

You write Element types A kernel takes it when
np.argmax(x), np.argmin(x), x.argmax(), x.argmin() float32, float64 For these types, including strided input and axis= (one kernel call per row or column). Runs and rows of any length
np.argmax(m, axis=1), m.argmax(axis=1), and argmin float32, float64 m is two-dimensional, in C order, with at least one column; axis is the number 1 or -1, by position or by name; no out and no keepdims. Rows of any length: narrow rows, such as the scores of a classifier with a few classes, gain most
np.clip(x, lo, hi), x.clip(lo, hi) float32, float64; int64 on arrays of up to 4,096 elements Scalar bounds with lo <= hi; the output is a new array or the array itself (np.clip(x, lo, hi, out=x)), not another array that overlaps it. Small arrays gain most with bounds that are Python numbers and no out other than x itself. For int64, both bounds are Python ints or np.int64 and there is no out: see below
x[mask] float32, float64, int32, int64, int16, uint16, uint8, int8, bool The mask has the shape of x, of any number of dimensions. A mask over the rows of a two-dimensional x stays with NumPy
np.compress(mask, x), np.extract(mask, x) float32, float64, int32, int64, int16, uint16, uint8, int8, bool x and mask the same size, x of any shape. For np.compress the mask is one-dimensional and there is no axis or out
x[mask] = v float32, float64, int32, int64 As for x[mask], and v is a value it takes for the array’s type: see Things worth knowing
np.putmask(x, mask, v), np.copyto(x, v, where=mask) float32, float64, int32, int64 v is a value it takes for the array’s type (see Things worth knowing), and x and mask are the same size (np.putmask) or the same shape (np.copyto, with no casting), of any shape
np.nonzero(mask), mask.nonzero(), np.where(mask) bool One-dimensional; np.where with nothing but the mask
np.nonzero(m), m.nonzero(), np.where(m), and np.argwhere(m), which calls np.nonzero bool m is two-dimensional and in C order, of any shape, empty ones included. Other layouts and three or more dimensions stay with NumPy
np.where(mask, a, b) float64, int64 mask is a boolean array and a and b are arrays of its exact shape and one element type, of any number of dimensions; or, for float64, one of a and b is such an array and the other a single number: a Python float, a Python int up to 2^53, or an np.float64. Shapes that would broadcast, and mixed element types, stay with NumPy
np.cumsum(x), x.cumsum(), np.cumsum(x, out=o), x.cumsum(out=o) int64, bool; float32 and float64 with inexact=True No axis or dtype. out left out, or a writable, contiguous, one-dimensional array of the result’s type (int64 for a mask) and of x’s element count that does not overlap x; for int64 also x itself (np.cumsum(x, out=x)): see below
x.astype(np.float32) uint8 Other arguments at their defaults
np.round(x, decimals), np.around(x, decimals), x.round(decimals) float64, on arrays of up to 4,096 elements, and on one number: an np.float64, a zero-dimensional float64 array or a Python float decimals left out or a Python int from 0 to 15; no out. Values whose rounding overflows, and signalling NaNs, go to NumPy, which warns: see below
np.maximum.accumulate(x) int64 x is one-dimensional, with at least one element; no dtype or out, and axis left out, 0 or -1
np.fmax.accumulate(x) int64, float64 As for np.maximum.accumulate, and a float64 x holds no signalling NaN, no negative zero, and NaNs of one bit pattern only
a.cumsum(axis=0), np.cumsum(a, axis=0), a.cumprod(axis=0), np.cumprod(a, axis=0), np.add.accumulate(a), np.multiply.accumulate(a), np.maximum.accumulate(a), np.fmax.accumulate(a) float64 a has two or more dimensions, is in C order, and has at least one row and one column; the axis is the first (the number 0 or -a.ndim, or left out for .accumulate); no dtype; out left out, or a C-ordered float64 array of a’s shape that is a itself or does not overlap it. For the maximum and np.fmax, a holds no signalling NaN, no negative zero, and NaNs of one bit pattern only: see below
np.fmax.reduceat(x, starts) float64 x is one-dimensional, with at least one element; starts is a one-dimensional int64 array, not a list, with at least one start and every start inside x; no dtype or out, and axis left out, 0 or -1; x holds no signalling NaN. Fastest on short runs: see below
m.any(axis=1), np.any(m, axis=1) bool m is two-dimensional, in C order, with at least one column; axis is the number 1 or -1, by position or by name, and no other argument is given
m.any(axis=0), np.any(m, axis=0) bool m is two-dimensional, in C order, with at least one row and one column; axis is the number 0 or -2, by position or by name, and no other argument is given
w -= b, w += b, np.subtract(w, b, out=w), np.add(w, b, out=w) float64 on arrays of 131,072 elements (1 MB) or more, float32 on arrays of 65,536 elements (256 KB) or more; Apple Silicon only The result goes into the first operand, and w and b are contiguous arrays of one shape. Gains only in one situation: see below
w *= b, w /= b, w *= 0.9, w /= s, np.multiply(w, b, out=w), np.divide(w, b, out=w) float64, on arrays of 131,072 elements (1 MB) or more; Apple Silicon only The result goes into the first operand, which is contiguous; the other is a contiguous array of the same shape or a number. Gains only in the same situation as w -= b
np.median(x), np.median(x, axis=None) float64 The array alone, of any shape, with no other argument than axis=None; no NaN. A zero median beside a negative zero, and a mean of the two middle elements that overflows, goes to NumPy: see below
np.argsort(x, kind="stable"), x.argsort(kind="stable") float64, int64, uint64 x is one-dimensional with at least 256 elements, and need not be contiguous: a reversed view or one with a step is taken too; kind is "stable" or "mergesort", or stable=True is given with no kind; no order or descending, and axis left out, 0 or -1. The default kind stays with NumPy: see below
a + b, a - b, a * b, a / b, a * 2.0, a > 0, a == b, -a, abs(a), x += y, np.exp(a), np.maximum(a, b), np.add(a, b, out=c), and every other NumPy ufunc with one or two inputs bool, every integer type, float32, float64; arrays of up to 16,384 elements Plain contiguous arrays of one shape; or an array and a row of it (m - row); or an array and a number: a Python float or int, or a NumPy number of the array’s type. No keyword but out, which is the first input itself or an array that shares no memory with the inputs, of the result’s shape and type. The types must need no conversion: int64 + float64, float32 * np.float64(2) and float16 stay with NumPy. NumPy’s own loop computes the result: see below
np.sum(x), x.sum() uint8, bool, float32, float64 No other arguments. For the floats, x is one-dimensional and its sum is finite: see below
np.sum(x, axis=-1), x.sum(axis=-1) float32, float64 x has two or more dimensions, is in C order, and its last axis has 1 to 7 elements; axis is the number -1 or the number of the last axis, by position or by name; dtype and out left out or None, and no keepdims, initial or where. The result is NumPy’s bit for bit: see below; a call in which any row sums to NaN stays with NumPy
np.count_nonzero(x) int64, float64 No axis
np.histogram(x, bins, range) float64 An integer bin count; no weights or density
np.bincount(x), np.bincount(x, minlength=m) uint8, int16, int64 x is one-dimensional; no weights; minlength, if given, is a Python int. For int16 and int64, x has at least one element, none negative, and the result is no longer than 65,536 counts or than x
np.unique(x) int64 At least one element, of any shape or layout; no return_index, return_inverse or return_counts (or each False), no axis, sorted left at True. The largest element minus the smallest is less than 256 or than the number of elements
np.isin(x, values) int64, int32 At most eight test values, given as an array of the same element type or as a list or tuple of Python ints that fit it; flags at their defaults. Test values of another element type stay with NumPy
np.searchsorted(a, v), a.searchsorted(v), np.digitize(x, bins) float64 a is one-dimensional; v is a float64 or float32 array of any shape, or a Python number; either side; no sorter. For np.digitize, with or without right=True, when the bins increase
np.searchsorted(a, v), a.searchsorted(v), np.digitize(x, bins) int64 a is one-dimensional; v is an int64 array of any shape, an np.int64 (an element of an int64 array is one), or a Python int that fits int64; either side; no sorter. Needles of any other type stay with NumPy: see below
np.interp(x, xp, fp) float64 xp and fp are one-dimensional and the same length; no left, right or period; xp holds no NaN; at most 64 sample points per query
bottleneck.nanmean(a, axis), bottleneck.nanstd(a, axis, ddof), bottleneck.nanmin(a, axis), bottleneck.nanmax(a, axis), and pandas and empyrical calling them float64 a is two-dimensional, and the axis that is kept has its elements next to each other: axis=0 of a C-ordered array or of a rolling-window view, axis=1 of a Fortran-ordered one. axis and ddof are Python ints. The result is bottleneck’s own, bit for bit. One-dimensional arrays and axis=None stay with bottleneck: see below

“Contiguous” means any shape for the operations that work element by element or reduce the whole array: a contiguous 40 by 25 array reaches the clip kernel as one run of 1,000 elements.

How much faster each one is, from Python and at three sizes, is in the results. Which hooks each of these calls meets on its way, and exactly what each hook changes inside NumPy, is in Into NumPy, with a figure that traces any of them.

Things worth knowing

  • Float cumsum is opt-in for a reason. The fast kernels add in a different order from NumPy. The result is as accurate, but not bit-identical, and the output of a non-negative input is not guaranteed to be non-decreasing. Code such as np.searchsorted(np.cumsum(p), r) relies on that. Use install(inexact=True) only when it does not matter to you. Why it cannot be both exact and fast.
  • np.cumsum(x, out=o) writes into your array and returns it. o must be a plain array of the result’s element type and of x’s element count, one-dimensional, contiguous and writable, and must not overlap x; on int64 it may also be x itself, so a running total computed in place a slice at a time, np.cumsum(t[a:b], out=t[a:b]), is served without an extra array. A mask needs an int64 o. On float32 and float64 (with inexact=True) x itself goes to NumPy: the float kernels are not safe in place. An o that overlaps x only in part, or is of another type, length, shape or layout, goes to NumPy, which copies, casts or raises as before.
  • Elementwise operators on small arrays skip NumPy’s call path, not its arithmetic. On a 16-element array a + b spends about 250 ns in NumPy, of which the addition is a few: the rest is NumPy working out what the call means. hotkernels asks NumPy once which loop it would use for, say, a float64 array times a Python float, and from then on calls that loop directly. The loop is NumPy’s, so the result is NumPy’s bit for bit, and warnings and np.errstate behave exactly as before: an overflow warns with NumPy’s message, np.errstate(divide="raise") raises. On an Apple M1 Pro, at 16 float64 elements, a + b is about 2x faster, a * 2.0 2.6x and a > 0 3.2x; at 4,096 elements 1.2x to 1.8x; above 16,384 elements the call goes to NumPy, where the saving would be under 5%. A whole program gains only as much as its small elementwise calls cost it: shap’s explainers, which make hundreds of thousands of them on rows of a dozen features, run 4% to 10% faster. Ufuncs of other libraries, such as scipy.special.expit, are not covered.
  • np.sum on float32 and float64 gives NumPy’s result bit for bit. NumPy adds the elements in a fixed order, in blocks of up to 128 whose sums it adds in pairs, and hotkernels makes exactly the same additions in the same order, only several blocks at a time. So, unlike float cumsum, it is installed by default. On an Apple M1 Pro np.sum(x) on float32 is about 20x faster than NumPy on 16 elements, 10x on 4,096 and 3x on a million, and on float64 about 20x, 6x and 1.9x. On an Intel Core i5-14600KF np.sum(x) on float32 is about 24x faster than NumPy on 16 elements, 14x on 4,096 and 2.6x on a million, and x.sum(), whose own call path is shorter, about 8x on 16 and 4,096 elements and 2.6x on a million; on float64 np.sum(x) about 23x, 9x and 1.6x, and x.sum() about 8x, 6x and 1.6x. Only np.sum(x) and x.sum() with nothing else are taken: axis=None, axis=0, dtype, out, keepdims, initial and where go to NumPy, and so do a matrix, a strided array, and an array whose elements are not aligned to their size (4 or 8 bytes), which NumPy itself adds in another order. A sum that overflows or meets a NaN or an infinity is handed to NumPy, so that the result and the warning are NumPy’s own.
  • np.sum(x, axis=-1) along a short last axis gives NumPy’s result bit for bit. NumPy adds a row of fewer than eight elements from left to right, and hotkernels makes the same additions in the same order, several rows at once, where NumPy calls its loop once for every row. The common case is a dot product of short vectors, np.sum(a * b, axis=-1) on vectors of two or three, as in a noise generator or in geometry: on an Apple M1 Pro a million rows of two float64 elements are summed about 17x faster than NumPy, a million of two float32 about 40x, and rows of seven float64 about 7x. Rows of eight or more go to NumPy, which adds them in another order, and so do np.add.reduce(x, axis=-1) and np.mean(x, axis=-1). A sum that overflows, or meets infinities of both signs or a signalling NaN, goes to NumPy too, which warns as before.
  • x[mask] = v on float64 and int64 rewrites elements it does not change, and so do np.putmask and np.copyto(x, v, where=mask). On a dense mask the kernel stores unselected elements back with their own bits. The result is identical; the array must be writable throughout, which a normal array is. On float32 and int32 nothing but the selected elements is written.
  • Which values x[mask] = v takes depends on the array’s type, in all three spellings, and every other value goes to NumPy, which converts it, warns or raises by its own rules. On float64, a Python float, or a Python int (rounded to the nearest double, as NumPy does). On float32, a Python float that is a NaN, an infinity or a zero or rounds to a normal float32 (one that would overflow to infinity or become a denormal is NumPy’s, since NumPy warns about the first), a Python int of at most 2^24 in magnitude, or an np.float32. On int64 and int32, a Python int in the type’s range (outside it NumPy raises OverflowError) or the array’s own scalar type, np.int64 or np.int32. A bool, a float for an integer array, an np.float64 for a float32 array and the other NumPy scalars all go to NumPy.
  • A mask holding a byte other than 0 or 1 goes to NumPy. NumPy treats any non-zero byte as True, and a boolean view of other data can hold a 2. Every mask is read once before a kernel sees it, in the indexing syntax, in the function forms, in mask.sum(), in np.cumsum(mask), in np.where(mask, a, b), in m.any(axis=1) and in np.nonzero(m) alike. m.any(axis=0) is the one exception: its kernel takes any non-zero byte as True, as NumPy does, so such a matrix is served and no mask is read twice.
  • The mask functions are counted under the indexing syntax. In report(), np.compress and np.extract count on the x[mask] rows, np.putmask and np.copyto on x[mask] = v, and np.where(mask) on np.nonzero. np.copyto without where is another operation and is not counted at all. np.where(mask, a, b) has a row of its own, np.where(c, a, b), whose element type reads float64: it counts int64 calls too, for the same reason as x[mask] below. mask.sum() counts on the np.sum row, whose element type reads uint8: one kernel adds the bytes of both. In the same way x[mask] on int64 counts on the float64 row of x[mask] and on int32 on the float32 row, on int8 and bool on the uint8 row and on uint16 on the int16 row, and x[mask] = v on int64 and int32 on the float64 and float32 rows of x[mask] = v: those kernels move elements without computing on them, so each serves a float type and the integer type of its width.
  • np.nonzero on a boolean matrix returns what NumPy returns, views and all. For a two-dimensional mask NumPy builds one array of (row, column) pairs and returns two views of its columns; hotkernels does the same, so the arrays you get have the same strides and the same base as NumPy’s. A matrix of 40 rows of 22 with 5% True is about 5x faster than NumPy on an Apple M1 Pro, and a million elements 15x to 27x. On an Intel Core i5-14600KF the same mask takes about 355 ns against NumPy’s 1.75 µs, and a million elements in rows of 22 is about 24x faster than NumPy with 5% True and 10x with half. In report() it has a row of its own, np.nonzero, matrix.
  • np.maximum.accumulate on a one-dimensional float array stays with NumPy. It carries a NaN forward from where it appears, which no kernel does. Down the columns of a float64 matrix it is served: see below. np.fmax.accumulate, the running maximum that skips NaN, is served on float64 and gives NumPy’s result bit for bit, the payload of a leading NaN included.
  • A float64 array holding a signalling NaN goes to NumPy in np.fmax.accumulate. NumPy turns one into a quiet NaN and forgets the maximum so far; the kernel would skip it. Arithmetic never produces a signalling NaN, so you only meet one in data built bit by bit, but every float64 array is read for them before the kernel sees it.
  • A float64 array holding a negative zero, or NaNs of different bit patterns, also goes to NumPy in np.fmax.accumulate. There NumPy’s own answer depends on how it was built: its x86-64 and ARM64 builds give a running maximum of 0.0 and -0.0 different signs. You get whatever your NumPy gives. The same read finds them.
  • Accumulating down the columns of a matrix gives NumPy’s result bit for bit. a.cumprod(axis=0), a.cumsum(axis=0), np.maximum.accumulate(a, axis=0) and np.fmax.accumulate(a, axis=0) on a C-ordered float64 matrix compute each element exactly as NumPy does, the previous row’s result and this row’s element, but a row at a time instead of a column at a time: about 7x to 10x faster than NumPy at 253 × 4,789 on an Apple M1 Pro, and in place too (a.cumprod(axis=0, out=a)). It is plain C inside hotkernels, not a judged kernel, with rows of its own in report(). A sum or product that meets a NaN, overflows or underflows is finished by NumPy from the row where that happened, so the warnings, or the error under np.errstate, are NumPy’s own. The maximum and np.fmax leave a matrix holding a signalling NaN, a negative zero or NaNs of different bit patterns to NumPy, as np.fmax.accumulate does on one dimension. Other axes, Fortran order, other element types and dtype= go to NumPy.
  • np.fmax.reduceat gains on short runs only. On runs of 16 it is faster than NumPy: about 11x at a million elements on an Intel Core i5-14600KF with 5% NaN (2.2x without), and about 3x on an Apple M1 Pro. Longer runs lose, because every element is read once more, for signalling NaNs, before the maximum is taken. On x86-64 runs of several hundred elements are about as fast as NumPy, and long runs of an array too large for the processor’s second-level cache can be slower (0.8x at runs of 1,024 in a million elements). On Apple Silicon runs of 64 are still faster (1.3x at a million elements), and runs of 256 or more are slower from about 262,144 elements (0.6x to 0.8x of NumPy); on 4,096 elements they are about level. If your runs are long, leave this call to NumPy with uninstall() or outside enabled(). Give starts as an int64 array; a list or int32 starts go to NumPy.
  • np.fmax.reduceat leaves two kinds of answer to NumPy. When x holds a negative zero and the maximum of some run is a zero, or x holds NaNs of different bit patterns and some run is all NaN, the whole call goes to NumPy. Which zero or which NaN NumPy returns there depends on the vector instructions it picked when it started, which differ between processors, and hotkernels does not guess. Values from ordinary arithmetic have one NaN pattern, and a zero maximum among negative values only matters if a negative zero is present.
  • Only the stable argsort is served. np.argsort(x, kind="stable"), kind="mergesort" and stable=True have one right answer, equal elements in their original order, and the kernel returns it: the same array as NumPy, NaNs last and zeros of both signs in the order they came. np.argsort(x) with no kind is not a stable sort. On an array with equal elements its answer depends on how NumPy’s quicksort happens to partition, which no other sort reproduces, so it stays with NumPy. If your code does not depend on that order, asking for kind="stable" is the faster call with hotkernels installed: about ten times faster at a million elements than NumPy’s default kind as well. np.unique(x, return_index=True) and scikit-learn’s ranking metrics ask for the stable kind themselves.
  • A stable argsort borrows memory while it runs: 32 bytes per element, freed before it returns, where NumPy’s own stable sort borrows 4. A million elements borrow 32 MB. If that memory cannot be had the call goes to NumPy.
  • Sorted input is recognised. An array already in order, or in strictly descending order, is answered without sorting. One that is nearly in order, with a handful of elements out of place or a few new ones appended to a sorted array, goes to NumPy, whose sort is built for exactly that and is faster there than the kernel.
  • m.any(axis=1) and m.any(axis=0) are served, not their neighbours. m.all(axis=1), m.any() and np.logical_or.reduce(m, axis=1) go to NumPy, and so does either call with keepdims, out or where, or with the axis given as a NumPy integer or as False. Along axis 1, a matrix of 22 columns is about 40 times faster than NumPy at a million elements on an Intel Core i5-14600KF and about 24 times on an Apple M1 Pro; rows of four columns gain most. On x86-64 rows of one, two or eight columns gain least, though all are well ahead of NumPy. On Apple Silicon every width measured, from one column to 1,000, is faster than the compiled loop it replaces. From Python it is ahead of NumPy as well, with one exception: rows of 1,000 columns that hold a True are about 1.6 times slower than NumPy at a million elements, because every byte is checked before the kernel runs while NumPy stops at each row’s first True. A matrix of one column is about 1.4 times faster than NumPy.
  • m.any(axis=0) gains most on small and narrow matrices. On an Intel Core i5-14600KF a mask of 30 rows by 31 columns takes about 95 ns against NumPy’s 840 ns, and a single row of 31 about 96 ns against 500 ns. A matrix of 31 columns is about 18 times faster than NumPy at 4,096 elements and 37 times at a million; one of 256 columns and 4,096 rows about 5.5 times. A matrix with no rows or no columns goes to NumPy. On an Apple M1 Pro a matrix of 31 columns is about 15 times faster than NumPy at 4,096 elements and 40 times at a million.
  • np.argmax(m, axis=1) gains most on narrow rows. NumPy spends 6 to 20 ns on each row, whatever its length; hotkernels under 1 ns on a row of up to four elements and about 2 ns on a row of ten. On 300,000 rows of ten float64 that is about 3.5x faster than NumPy, and on rows of two to five 12x to 20x (Apple M1 Pro; not yet measured on x86-64). Rows of six float64 or nine float32 elements and more go to the kernel one row at a time, which holds Python’s interpreter lock while it runs, where NumPy releases it. axis=0, arrays of three or more dimensions, and keepdims=True go to NumPy, and long columns there still reach the kernel.
  • np.bincount on int16 and int64 reads the array twice. NumPy’s result is one count longer than the largest element, so the array is read once for its smallest and largest elements before it is counted. An array holding a negative element goes to NumPy, which raises its ValueError as before. So does a result much longer than the array, such as np.bincount(np.array([10**9])): NumPy gets that memory from the system already zeroed, and the kernel would write every count. The gain at a million elements is largest on int16 (about 9x on an Apple M1 Pro, 4.5x on an Intel Core i5-14600KF) and smaller on int64 (about 4x and 1.9x), whose array is four times the size to read twice. Other integer types, int32 and uint16 among them, and weights stay with NumPy.
  • np.unique is fast on labels, not on arbitrary integers. Class labels, a few distinct values close together, are what scikit-learn validates on every call, and those are about 18x faster at a million elements on an Apple M1 Pro and about 39x on an Intel Core i5-14600KF. The array is read once for its smallest and largest elements first; when they are far apart, compared with the number of elements, the call goes to NumPy, which costs it that one read: well under 1% of what NumPy then takes. np.unique with counts, an inverse or indices, with sorted=False, or on any type other than int64, goes to NumPy as before.
  • np.clip(x, 0, 1) is faster by less than np.clip(x, -1, 1). A lower bound of exactly zero needs extra care for negative zeros. It is still several times faster than NumPy.
  • A small np.clip is fast when its bounds are plain numbers. np.clip(x, lo, hi) and x.clip(lo, hi) skip NumPy’s own call path, most of a call on a small array, when the bounds are Python floats or ints, or NumPy scalars of the array’s own type, and there is no dtype, casting or where, and no out unless it is the array itself. The result has the element type NumPy gives it: a float32 array clipped to Python floats stays float32. Other calls, such as np.float64 bounds on a float32 array (NumPy returns float64), out= another array, or a bound of None, go through NumPy’s call path first; the kernel still serves them where it served them before, and they gain only on larger arrays.
  • np.clip(x, lo, hi, out=x) clips in place. The gradient-clipping idiom, np.clip(g, -5, 5, out=g) or g.clip(-5, 5, out=g), is served on float32 and float64 arrays under the same conditions as np.clip(g, -5, 5), and returns g itself, as NumPy does. It costs one copy more than clipping into a new array: the kernels must not write over the data they are reading, so hotkernels copies 4 KB of the array at a time to a buffer of its own and clips the copy back into place. An out that is any other array goes through NumPy’s call path first, and one that overlaps x without being x goes to NumPy. On int64 the in-place call is NumPy’s.
  • np.clip on int64 and np.round are served on short arrays only. On a short array most of a NumPy call is NumPy’s own call path, about 1.8 µs for np.clip, 1.1 µs for np.round(x, 2) and 4.8 µs for np.median, and hotkernels answers it with a plain loop of its own in about 0.1 µs. On longer arrays NumPy’s own loops are as good or better, and above 4,096 elements np.clip and np.round go to NumPy as before. In report() each has a row of its own, marked C, as np.median has, which the count of kernels on the first line leaves out: they are part of hotkernels, not judged kernels.
  • np.median is fast on large arrays too. Above 64 elements hotkernels does not sort: it finds the middle elements from the bits of the numbers, reading the array three times, where NumPy partitions a copy of it. On an Apple M1 Pro that is about 8x faster than NumPy on a million normally distributed float64 (9.2 ms to 1.2 ms), about 7x on an astronomical image of 1,024 × 1,024, and 4x on 1,000 elements. On data already in order, or nearly, NumPy’s own partition is quick, and the gain is smaller: 1.7x on a million sorted elements, 1.2x on a smooth curve, and on a sorted array with a little noise added hotkernels is slower, 0.74x at a million elements. It takes a buffer of up to eight bytes an element, usually a few per cent of that, where NumPy copies the whole array, and releases the interpreter lock from 8,192 elements. Astropy’s robust statistics (biweight_location, biweight_scale, median_absolute_deviation) call np.median(data, axis=None) and are served; np.nanmedian, bottleneck’s nanmedian, np.percentile and np.quantile are not.
  • w -= b, w += b, w *= 0.9 and w /= s gain after a large matrix product, on Apple Silicon only. When Accelerate multiplies by a large matrix, it does so on several cores, and updating that matrix in place afterwards, as the gradient step w -= lr * g of a training loop does, takes NumPy up to 15 times as long as it would otherwise. hotkernels runs these updates with a loop of its own that asks for each part of the array ahead of time in a way that removes the delay: in a small training loop on an Apple M1 Pro the step went from about 460 µs to about 95 µs, and the whole program from 260 ms to 153 ms. Everywhere else it runs at about NumPy’s speed, on an array already in the processor’s cache or in a program without a large matrix product: from 0.99x to 1.07x of NumPy, measured on its own. Arrays under 131,072 elements go to NumPy, since there the loop was up to 2% slower and the delay was not seen. float32 is served the same way from 65,536 elements: in a float32 version of that training loop with 1,024 hidden units the step went from about 830 µs to 120 µs, and the program from 561 ms to 360 ms; with 256 hidden units Accelerate multiplies on one core, there is no delay, and nothing changes. The result is NumPy’s bit for bit. w *= 0.9 (weight decay), w /= s, np.multiply(w, b, out=w) and np.divide(w, b, out=w) on float64 are served the same way from 131,072 elements, with a number or an array for the second operand: right after the product w *= 0.9 on a 784 × 256 matrix went from about 450 µs to 45 µs, and the training loop with weight decay added from 264 ms to 146 ms. w = w - b, a scalar added or subtracted such as w -= 0.5, multiplying or dividing float32, and other element types go to NumPy. On x86-64 nothing changes: whether the same delay arises there has not been measured. In report() the six rows, x += y and x -= y on each type and x *= y and x /= y on float64, are marked C and count no calls left to NumPy, since every call of those operations on those types passes their hook. Setting VECLIB_MAXIMUM_THREADS=1 before NumPy starts removes the delay too, and made that training faster still (170 ms), but it changes every matrix product in the program, so hotkernels does not do it for you.
  • np.clip on int64 needs integer bounds. Python ints that fit int64, or np.int64, with lo <= hi, and no out. A float bound gives NumPy’s float64 result, and is NumPy’s.
  • np.round gives NumPy’s result bit for bit, because it does what NumPy does, in the same order: multiply by the power of ten, round to the nearest whole number with ties to even, divide. So np.round(-0.004, 2) is -0.0 and np.round(0.125, 2) is 0.12, as with NumPy. One number, np.round(np.float64(x), 1) or np.around of a zero-dimensional array, gives an np.float64, as NumPy does, and about 16x faster than NumPy on x86-64: NumPy spends about 1.6 µs on its call path for a few nanoseconds of arithmetic. Negative decimals, more than 15, and decimals given as a NumPy integer go to NumPy. So does a call where the multiplication overflows, or the array holds a signalling NaN: NumPy computes it and warns, or raises under np.errstate, as it always did.
  • np.median gives NumPy’s result bit for bit: the middle element, or the two middle elements added and halved, as NumPy’s mean of them does. Some calls go to NumPy, which then answers and warns as it always did: an array holding a NaN; two middle elements whose sum overflows, or that are infinities of both signs; a half that is too small to be exact; and a median of zero when the array holds a negative zero anywhere, since which zero NumPy returns then depends on how its partition orders equal elements (NumPy 2.5 returns +0.0). np.median(x, axis=None) is served as np.median(x) is; any other axis, and every other argument, out, keepdims and overwrite_input included, are NumPy’s.
  • np.isin is fastest when the test values are close together: all between 0 and 65,534, or all within 32,767 of the first one (on x86-64, all between 0 and 32,767 for int64, and all within 65,533 of each other for int32). Otherwise it runs at the speed of compiled C, which is still ahead of NumPy. On Apple Silicon int32 is served by compiled C for any test values. On int32 the test values must be int32 too, or Python ints that fit int32: np.isin(x, np.array([1, 2])) on an int32 x compares with int64 test values and goes to NumPy; np.isin(x, [1, 2]) is served.
  • np.searchsorted and np.interp trust you that the array is sorted, as NumPy does. Neither checks. On an array that is not sorted both return a meaningless result, and the kernel’s is not the same meaningless result as NumPy’s. Sorted data, including NaNs at the end of a, gives NumPy’s answer bit for bit.
  • np.searchsorted on a float64 array also takes float32 needles. NumPy converts them to float64 before it searches, and so does hotkernels, a chunk at a time, so the answer is NumPy’s, NaN needles included. On x86-64 that is about 15x faster than NumPy with 4,096 needles and 5x to 20x with a million. A float32 signalling NaN among the needles, which NumPy warns about when it converts it, sends the call to NumPy, which warns.
  • np.searchsorted on an int64 array takes int64 needles only. An int64 array of needles, an np.int64, which is what indexing an int64 array gives you, or a Python int that fits int64. A needle of another type, such as an np.int32, a float or a list, goes to NumPy, which converts it and the array to a common type first; convert the needles with v.astype(np.int64) to have them served. On x86-64 one needle is about twice as fast as NumPy whatever the length of the array, because most of such a call is NumPy’s call path; with many needles the gain is 3x to 4x on arrays that fit the cache and less beyond. On Apple Silicon (an M1 Pro) one needle is about 1.8x faster, and many needles 2x to 3.5x.
  • np.digitize is served when its bins increase. It calls np.searchsorted, on either side. With decreasing bins it searches them reversed, as a view no kernel takes, and runs at NumPy’s speed.
  • np.interp with a few queries against a long table stays with NumPy. A NaN among the sample points is something the kernel cannot handle, so xp is read once before every call. With more than 64 sample points per query that pass would cost more than the kernel saves.
  • bottleneck’s own functions are served too, when bottleneck is installed. pandas and empyrical, among others, send NaN-aware reductions to bottleneck instead of NumPy, so no NumPy hook sees them. hotkernels serves nanmean, nanstd, nanmin and nanmax along one axis of a two-dimensional float64 array, with bottleneck’s result bit for bit, however your code or the library got hold of the function. At 252 × 4,789, the rolling windows of a year over twenty years of daily returns, they are about 4x to 7x faster than bottleneck on an Apple M1 Pro, and nanmin and nanmax 9x to 20x. hotkernels never imports bottleneck: if it is not imported when you call install(), its functions are served from the moment it is, and report() says “waiting” until then. install(bottleneck=False) leaves them alone. In report() they are the bn.* rows, and on those rows “Left to NumPy” counts calls left to bottleneck, such as one-dimensional arrays, axis=None, float32 and pandas’ Series.std(). If your bottleneck was built so that it rounds nanstd differently from the kernel, which install() checks against bottleneck’s own answer, nanstd stays with bottleneck and report() lists it under the hooks that are not in place.
  • Free-threaded Python is not supported. install() does nothing there, and report() says so.
  • NumPy 2.0 to 2.2 are not supported. They answer a few calls differently from later releases (np.clip drops the sign of a zero on 2.0, and np.count_nonzero(x) gives a Python int before 2.3), and the kernels give the later answer. Installing hotkernels brings NumPy 2.3 or later; with an older NumPy in place install() does nothing, and report() says so.
  • x[mask] is served as syntax. x[mask], x[mask] = v and operator.getitem(x, mask) reach the kernels. x.__getitem__(mask) and x.__setitem__(mask, v), written out, do not: they call NumPy’s own functions directly, and get NumPy’s speed.
  • Subclasses mostly stay with NumPy. x[mask], the methods and the hooked functions take a kernel only for a plain ndarray; masked arrays, memory maps and your own subclasses go to NumPy there. clip and argmax are also hooked beneath NumPy’s own handling of array types, so for a subclass they serve whatever plain buffer NumPy hands them, and NumPy wraps the result as it always did.

Checking it yourself

From a clone of the repository:

uv run delivery demo          # run examples/workload.py with and without hotkernels, and compare
uv run delivery check         # 436,501 calls, NumPy's and bottleneck's, both ways; results, errors and warnings must agree
uv run delivery time          # time each statement from Python on your machine
uv run delivery numpy-tests   # NumPy's own test suite, both ways; a minute or two

delivery demo is the quickest way to see the effect: an ordinary NumPy program on two million elements that runs in 45 ms on plain NumPy and 8.4 ms with the one line added, with the same results bit for bit.

Whole expressions, fused (prototype)

install() makes each NumPy call faster on its own: a * b + c is still two calls and two passes over memory. The repository also holds a prototype that computes such an expression whole. A lazy stand-in for numpy writes the program down as a graph, and fusion computes each float64 expression in it in one pass, block by block, with NumPy’s results bit for bit. install() is in effect with it, so a call fusion cannot take still reaches the package’s kernels, and the rest goes to NumPy. It is not part of pip install hotkernels, and the package does not import it.

What it gives whole programs at their large size, fused with install() in effect, against plain NumPy, with install() alone beside it:

Program M1 Pro: fused M1 Pro: install() alone i5-14600KF: fused i5-14600KF: install() alone
Cavity flow, a stencil solver from NPBench 2.80x 1.00x 3.09x 1.00x
Horizontal diffusion, NPBench 2.34x 1.05x 2.31x 1.06x
Veros, equation of state 1.68x 0.97x 1.69x 1.00x
Particle filter 1.43x 1.12x 1.18x 1.09x
scikit-learn metrics 3.50x 3.56x 3.19x 3.24x
Character RNN, small arrays 0.98x 1.12x 0.97x 1.15x
  • It gains on expressions on large float64 arrays: element-by-element arithmetic, maxima and minima, square roots, np.where(a <= s, b, c), and sums along short rows. A comparison whose mask the program keeps, matrix products, np.exp and the other functions of a mathematics library, float32 and complex go to the package’s kernels where one takes them, and to NumPy otherwise.
  • Where a program’s gain is single calls, it is install()'s, and the fused run keeps it, as for the scikit-learn metrics.
  • On small arrays the graph costs more than it saves. A program of many calls on small arrays, such as the character RNN, runs slower than with install() alone, and can fall behind plain NumPy.
  • On ARM64 all eighty-one fused kernels are NEON assembly. On x86-64 three are AVX2 and the rest are built from their C references, which clang vectorises as well.

To try it, from a clone of the repository, on macOS or Linux x86-64, with clang:

uv sync
uv run python -m prototypes.lazy.build_core     # the layer's C core: optional, the figures above were taken with it
uv run python -m prototypes.lazy.build_fused    # build the fused kernels

Then, in uv run python from the repository’s root:

import numpy
from prototypes.lazy import fuse, get_lazy

fuse.enable()                   # also runs hotkernels.install(); False, and nothing changes, if the kernels are not built
np = get_lazy()                 # stands where `import numpy as np` stood; patches nothing
weights = np.asarray(numpy.random.standard_normal(1_000_000))
gradient = np.asarray(numpy.random.standard_normal(1_000_000))
w = weights - 0.1 * gradient    # written down, not computed
w.gather()                      # an ndarray with NumPy's bits: one kernel call, one pass
fuse.STATS                      # what was planned, which kernels ran, what was left to NumPy
fuse.disable()                  # also takes hotkernels out again, if enable() put it in

The timing tools and the tests are in the prototype’s README. How the layer works is in a lazy layer, how fusion works in fusion, and every program it was measured on in what fusion gained.