import time
import tracemalloc
import warnings
import numpy as np
import numba
from numba import jit, prange
print(f"numba {numba.__version__}, NUMBA_NUM_THREADS = {numba.config.NUMBA_NUM_THREADS}")numba 0.66.0, NUMBA_NUM_THREADS = 32
parallel=True can multiplynumba 0.66.0, NUMBA_NUM_THREADS = 32
The pybind11 notebook ended on a sentence it did not have room to defend:
parallel=Truemultiplies your compute; if compute is not the constraint, it multiplies nothing.
This notebook is that defence. One keyword, applied to three kernels on the same sixteen-core machine, is worth roughly 3×, better than 15×, and exactly 1× — and the third one, at a different size, turns into a slowdown of more than twenty.
The claim is not that parallelism is unpredictable. It is the opposite. Every one of those numbers follows from a quantity you can work out before typing the decorator, and the point of what follows is to make that quantity concrete enough to use. So we start by measuring the machine, not the code.
Two numbers govern everything below: how many threads Numba will use, and how fast this computer can move data between DRAM and the cores. The first is a config value. The second has to be measured, and the cheapest honest probe is a kernel that does nothing but read.
NT = numba.config.NUMBA_NUM_THREADS
THREADS = [n for n in (1, 2, 4, 8, 16, 32, 64, 128) if n < NT] + [NT]
def best_of(fn, *args, reps=7):
"""Fastest of `reps` calls, in seconds — `%timeit` cannot benchmark a loop variable."""
fn(*args) # warm up: compile, and fault in any fresh pages
best = float("inf")
for _ in range(reps):
t0 = time.perf_counter()
fn(*args)
best = min(best, time.perf_counter() - t0)
return best
def sweep(fn, *args, baseline, reps=7, gb=None):
"""Time `fn` at every thread count, as a speedup over `baseline` seconds."""
times = {}
for nt in THREADS:
numba.set_num_threads(nt)
times[nt] = best_of(fn, *args, reps=reps)
numba.set_num_threads(NT)
for nt, t in times.items():
rate = f"{gb / t / 1e9:7.1f} GB/s" if gb else ""
print(
f"{nt:3d} thread{'s' if nt > 1 else ' '}:{t * 1e3:9.2f} ms"
f"{baseline / t:7.2f}×{rate} {'█' * round(baseline / t)}"
)
return timesOne more piece of scaffolding, and it is doing real work for the argument. Every kernel below has to exist in a serial and a parallel version, and it matters that the two are the same program. They can be, because prange is lowered as an ordinary range when parallel is switched off — so one source, compiled twice, gives both. Nothing in this notebook is a comparison between two loop nests that might have drifted apart.
# `fastmath` lets LLVM reassociate the sum, which is what lets it vectorise the reduction
# at all. Without it this measures floating-point latency rather than bandwidth.
def total_src(a):
acc = 0.0
for i in prange(a.shape[0]):
acc += a[i]
return acc
total, total_parallel = (
jit("f8(f8[::1])", nopython=True, nogil=True, fastmath=True)(total_src),
jit("f8(f8[::1])", nopython=True, nogil=True, fastmath=True, parallel=True)(total_src),
)
probe = np.random.rand(1 << 25) # 268 MB — far past any cache
PROBE_BYTES = probe.nbytes
t_probe = best_of(total, probe, reps=15)
print(f" 1 serial :{t_probe * 1e3:9.2f} ms 1.00×{PROBE_BYTES / t_probe / 1e9:7.1f} GB/s\n")
probe_times = sweep(total_parallel, probe, baseline=t_probe, gb=PROBE_BYTES, reps=15)
CEILING = PROBE_BYTES / min(probe_times.values())
print(f"\nmeasured ceiling: {CEILING / 1e9:.1f} GB/s") 1 serial : 4.49 ms 1.00× 59.8 GB/s
1 thread : 4.40 ms 1.02× 61.0 GB/s █
2 threads: 4.79 ms 0.94× 56.1 GB/s █
4 threads: 4.53 ms 0.99× 59.3 GB/s █
8 threads: 4.70 ms 0.95× 57.1 GB/s █
16 threads: 4.78 ms 0.94× 56.1 GB/s █
32 threads: 4.68 ms 0.96× 57.4 GB/s █
measured ceiling: 61.0 GB/s
Read that sweep carefully, because it is the most surprising table in the notebook and the rest is a consequence of it.
A single core already reaches around 90% of this machine’s memory bandwidth. All sixteen together buy about ten percent more, and then the curve sags. That is not a Numba fact or even a software fact — it is what a modern desktop core is: wide enough, and able to keep enough cache misses in flight, to saturate two DDR5 channels essentially on its own.
So the ceiling is reached by one thread. Any kernel whose time goes on moving data therefore has nothing to gain from the other fifteen cores: the resource they would contend for is already spent. Any kernel whose time goes on arithmetic has everything to gain, because arithmetic units are per-core and there are sixteen of them.
That is the whole predictive rule, and it takes one input — the bytes that must cross the memory bus per call, divided by the serial runtime. Call it the kernel’s bandwidth demand, and compare it to the ceiling:
We now do exactly that for three kernels, in increasing order of how well it works.
Start with the Ricker wavelet from the loops notebook — deliberately the same function, so the two notebooks can be read against each other:
\[ \psi_\sigma(x, y) = (1 - r^2)\, e^{-r^2 / 2}, \qquad r^2 = \frac{x^2 + y^2}{\sigma^2} \]
def f_numpy(x, y, σ):
"""Ricker wavelet on the grid spanned by 1-D `x` and `y`."""
r2 = (x.reshape(-1, 1) ** 2 + y.reshape(1, -1) ** 2) / (σ * σ)
return (1.0 - r2) * np.exp(-0.5 * r2)
M = 3600
N = 4400
σ = 1.5
x = np.linspace(-4.0, 4.0, M)
y = np.linspace(-4.0, 4.0, N)
CELL = M * N * 8 # bytes in one (M, N) float64 array — our unit of memory
print(f"grid: {M} × {N} = {M * N:,} points, {CELL / 1e6:.2f} MB per array")grid: 3600 × 4400 = 15,840,000 points, 126.72 MB per array
@jit is an ordinary function of a function, so both compiled variants come from the identical code object — no rewrite, no prange, not a character changed. The only difference between them is one keyword argument.
one source, two dispatchers: True
49.9 ms ± 137 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
44.4 ms ± 66.3 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
29.2 ms ± 404 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
parallel=True vs interpreted NumPy: 1.75×
parallel=True vs serial @jit: 1.56×
Several times faster than NumPy for one keyword, on code written with no thought of parallelism whatever. That is the strongest thing that can be said for parallel=True, and it is genuinely strong: no rewrite, no thread pool, no prange, no partitioning of the grid, no join. It is worth pausing on how unusual that is. In essentially every other parallel programming model — OpenMP, multiprocessing, concurrent.futures, MPI — you must at minimum say what is to be divided.
Here you did not, because you already had. x.reshape(-1, 1) ** 2 + y.reshape(1, -1) ** 2 is a promise that every grid point is independent of every other; that is what elementwise means. Numba’s parallel accelerator reads array expressions as parallel loops — it calls them parfors — and it will show you the ones it found:
================================================================================
Parallel Accelerator Optimizing: Function f_numpy,
/tmp/ipykernel_636810/1495731415.py (1)
================================================================================
Parallel loop listing for Function f_numpy, /tmp/ipykernel_636810/1495731415.py (1)
----------------------------------------------------------------------|loop #ID
def f_numpy(x, y, σ): |
"""Ricker wavelet on the grid spanned by 1-D `x` and `y`.""" |
r2 = (x.reshape(-1, 1) ** 2 + y.reshape(1, -1) ** 2) / (σ * σ)----| #1
return (1.0 - r2) * np.exp(-0.5 * r2)-----------------------------| #2
------------------------------ After Optimisation ------------------------------
Parallel structure is already optimal.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Two parallel loops, and they are exactly the two arrayexpr nodes the loops notebook dissected: one producing r2, one consuming it. Each is now a range split across sixteen cores.
Sixteen cores, then, for a factor of two over the serial compiled version. Where did the other fourteen go?
1 thread : 44.88 ms 0.99× █
2 threads: 24.51 ms 1.81× ██
4 threads: 15.99 ms 2.77× ███
8 threads: 15.46 ms 2.87× ███
16 threads: 17.96 ms 2.47× ██
32 threads: 28.62 ms 1.55× ██
The curve peaks partway up and then falls over: more cores, less speed. From the sweep alone you would guess memory contention, and you would be right — but the interesting part is which memory, because there are two quite different memory costs in this function and they can be separated by measurement.
The loops notebook already removed one of them. Written as an explicit loop nest, \(r^2\) is a scalar in a register and the 127 MB temporary never exists. Take that version and change one word — range to prange on the outer loop — and the parallelism is over rows of the grid:
def f_loops_src(x, y, σ):
M = x.shape[0]
N = y.shape[0]
res = np.empty((M, N))
inv = 1.0 / (σ * σ)
for i in prange(M):
xi = x[i] * x[i] * inv # invariant in j — hoisted out of it
for j in range(N):
r2 = xi + y[j] * y[j] * inv # a scalar, in a register
res[i, j] = (1.0 - r2) * np.exp(-0.5 * r2)
return res
f_loops, f_loops_parallel = two_ways(f_loops_src, SIG)
ref = f_numpy(x, y, σ)
print("matches:", np.allclose(f_loops_parallel(x, y, σ), ref))matches: True
1 serial : 38.06 ms 1.00× █
1 thread : 37.09 ms 1.03× █
2 threads: 19.22 ms 1.98× ██
4 threads: 10.36 ms 3.67× ████
8 threads: 6.50 ms 5.86× ██████
16 threads: 7.13 ms 5.34× █████
32 threads: 7.49 ms 5.08× █████
Better, and no longer falling over at the top end: removing the temporary removed the traffic the threads had been fighting each other for.
Still a long way from sixteen, though, and one cost remains. The function allocates its own output — 127 MB of address space the process did not have a moment ago, whose pages the kernel hands over one at a time, trapping into the fault handler on each first touch. That work is not arithmetic, it is not in your program at all, and it does not scale the way arithmetic does.
Take it out of the timed region by writing into a buffer the caller already owns:
def f_into_src(x, y, σ, res):
M = x.shape[0]
N = y.shape[0]
inv = 1.0 / (σ * σ)
for i in prange(M):
xi = x[i] * x[i] * inv
for j in range(N):
r2 = xi + y[j] * y[j] * inv
res[i, j] = (1.0 - r2) * np.exp(-0.5 * r2)
f_into, f_into_parallel = two_ways(f_into_src, "void(f8[::1], f8[::1], f8, f8[:, ::1])")
res = np.empty((M, N))
f_into_parallel(x, y, σ, res)
print("matches:", np.allclose(res, ref))matches: True
1 serial : 33.73 ms 1.00× █
1 thread : 33.69 ms 1.00× █
2 threads: 16.93 ms 1.99× ██
4 threads: 8.72 ms 3.87× ████
8 threads: 4.49 ms 7.51× ████████
16 threads: 4.38 ms 7.70× ████████
32 threads: 2.92 ms 11.56× ████████████
An order of magnitude, and still climbing at the top of the sweep. Now put the three serial timings side by side, because subtracting them decomposes the original runtime into its parts:
print(f"{'array expressions':24s}{t_numba.best * 1e3:8.2f} ms")
print(f"{'loops, allocating':24s}{t_loops * 1e3:8.2f} ms ← without the r2 round trip")
print(f"{'loops, into a buffer':24s}{t_into * 1e3:8.2f} ms ← without faulting in 127 MB\n")
print(f"{'so: r2 traffic':24s}{(t_numba.best - t_loops) * 1e3:8.2f} ms")
print(f"{' page faults':24s}{(t_loops - t_into) * 1e3:8.2f} ms")
print(f"{' arithmetic':24s}{t_into * 1e3:8.2f} ms")
print(f"\nbandwidth demand of what is left: {CELL / t_into / 1e9:.1f} GB/s "
f"= {100 * CELL / t_into / CEILING:.0f}% of the ceiling")array expressions 44.30 ms
loops, allocating 38.06 ms ← without the r2 round trip
loops, into a buffer 33.73 ms ← without faulting in 127 MB
so: r2 traffic 6.25 ms
page faults 4.33 ms
arithmetic 33.73 ms
bandwidth demand of what is left: 3.8 GB/s = 6% of the ceiling
Close to half of f_numba’s runtime was never arithmetic. It was a temporary going out to DRAM and coming back, and a kernel handing over pages — and parallel=True multiplies neither. This is Amdahl’s law with the serial fraction measured rather than assumed: the arithmetic part shrinks by ten, everything else barely moves, and the whole function therefore lands within a small factor of where it started. Which is where the first sweep put it.
The last line is the rule from the top of the notebook, applied. Stripped of its temporary and its allocation, this kernel demands a few percent of the machine’s bandwidth — almost all of its time is exp, arithmetic is per-core, and so it scales. What parallel=True multiplied was never “the function”; it was the fraction of the function that was arithmetic. Everything else it inherited unchanged.
Which is why the free version was worth so much less than the prepared one: parallel=True cannot fix your memory traffic, so it pays best on code where you already have. The loops notebook is not superseded by this one. It is a precondition for it.
Now a function that is almost nothing but arithmetic. This one is from my own work — the interferometer curvature matrix from ickc/python-autojax, used in strong gravitational lens modelling and discussed at length in an earlier talk:
\[\tilde{W}_{ij} = \sum_{k=1}^K \frac{1}{n_k^2} \cos\bigl(2\pi[(g_{i1} - g_{j1})u_{k0} + (g_{i0} - g_{j0})u_{k1}]\bigr)\]
In words: for every pair \((i, j)\) of image pixels, sum a cosine over every visibility \(k\) the telescope measured. In production \(M \sim 70{,}000\) and \(K \sim 10^7\) — which is why it is worth parallelising, and why we run it here at a size that finishes inside a notebook.
TWO_PI = 2.0 * np.pi
W_SIG = "f8[:, ::1](f8[::1], f8[:, ::1], f8[:, ::1])"
M_w = 512 # image pixels
K_w = 128 # visibilities
CELL_W = M_w * M_w * 8
rng = np.random.default_rng(0)
noise_map_real = rng.uniform(0.8, 1.2, K_w)
uv_wavelengths = rng.normal(0.0, 1e5, (K_w, 2))
grid_radians_slim = rng.uniform(-1e-5, 1e-5, (M_w, 2))
w_args = (noise_map_real, uv_wavelengths, grid_radians_slim)
W_BYTES = noise_map_real.nbytes + uv_wavelengths.nbytes + grid_radians_slim.nbytes + CELL_W
print(f"M = {M_w} pixels, K = {K_w} visibilities")
print(f"inputs {(W_BYTES - CELL_W) / 1e3:8.1f} kB")
print(f"output {CELL_W / 1e6:8.2f} MB")
print(f"cosines {M_w * M_w * K_w / 1e6:8.0f} M per call")M = 512 pixels, K = 128 visibilities
inputs 11.3 kB
output 2.10 MB
cosines 34 M per call
Those three numbers make the prediction on their own. Thirty-four million transcendental evaluations, against two megabytes of data crossing the memory bus — and essentially all of that two megabytes is the answer on its way out. There is no traffic here to speak of. This kernel is arithmetic and nothing else, which is exactly the case where sixteen arithmetic units beat one.
Here is the vectorised formulation from the talk. It precomputes every pairwise offset \(\delta g\) once, as an \((M, M, 2)\) array, and then accumulates one cosine grid per visibility — so \(M^2K\) work is expressed as \(K\) passes over an \(M^2\) array rather than as a triple loop.
def w_tilde_src(noise_map_real, uv_wavelengths, grid_radians_slim):
M = grid_radians_slim.shape[0]
K = uv_wavelengths.shape[0]
g = TWO_PI * grid_radians_slim
δg = g.reshape(-1, 1, 2) - g.reshape(1, -1, 2)
w = np.zeros((M, M))
for k in prange(K):
w += np.cos(δg[:, :, 1] * uv_wavelengths[k, 0] + δg[:, :, 0] * uv_wavelengths[k, 1]) / (
noise_map_real[k] * noise_map_real[k]
)
return w
w_tilde, w_tilde_parallel = two_ways(w_tilde_src, W_SIG)
w_ref = w_tilde(*w_args)
print("matches:", np.allclose(w_tilde_parallel(*w_args), w_ref))matches: True
Stop at that matches: True, because it ought to bother you.
w += ... is a loop-carried dependence. Every iteration of the k loop reads the array that every other iteration writes. Splitting it across sixteen threads is, on the face of it, a data race — and with a plain for loop and a thread pool it would be one.
It is not, because Numba recognised the shape of it. += into a value that stays live across the whole loop is a reduction, and the parallel accelerator handles reductions the way OpenMP does: give every thread a private accumulator, let it run its own slice with no synchronisation whatever, and combine the partials once at the end.
================================================================================
Parallel Accelerator Optimizing: Function w_tilde_src,
/tmp/ipykernel_636810/104382964.py (1)
================================================================================
Parallel loop listing for Function w_tilde_src, /tmp/ipykernel_636810/104382964.py (1)
----------------------------------------------------------------------------------------------------|loop #ID
def w_tilde_src(noise_map_real, uv_wavelengths, grid_radians_slim): |
M = grid_radians_slim.shape[0] |
K = uv_wavelengths.shape[0] |
g = TWO_PI * grid_radians_slim------------------------------------------------------------------| #5
δg = g.reshape(-1, 1, 2) - g.reshape(1, -1, 2)--------------------------------------------------| #6
|
w = np.zeros((M, M))----------------------------------------------------------------------------| #7
for k in prange(K):-----------------------------------------------------------------------------| #9
w += np.cos(δg[:, :, 1] * uv_wavelengths[k, 0] + δg[:, :, 0] * uv_wavelengths[k, 1]) / (----| #8
noise_map_real[k] * noise_map_real[k] |
) |
return w |
------------------------------ After Optimisation ------------------------------
Parallel region 0:
+--9 (parallel)
+--8 (serial)
Parallel region 0 (loop #9) had 0 loop(s) fused and 1 loop(s) serialized as part
of the larger parallel loop (#9).
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
1 serial : 345.68 ms 1.00× █
bandwidth demand: 0.006 GB/s = 0.010% of the ceiling
1 thread : 342.11 ms 1.01× █
2 threads: 173.97 ms 1.99× ██
4 threads: 89.88 ms 3.85× ████
8 threads: 46.73 ms 7.40× ███████
16 threads: 32.77 ms 10.55× ███████████
32 threads: 33.51 ms 10.32× ██████████
Ten times, against three for the wavelet — and the reason is the line above the sweep. This kernel asks for a hundredth of a percent of the machine’s memory bandwidth. There is nothing to contend over, so the cores get to be sixteen independent cosine engines.
“Give every thread a private accumulator” is a phrase worth pricing, because the accumulator here is a 2 MB array. tracemalloc sees Numba’s allocations — its runtime allocates array data through NumPy’s allocator — so we can just watch the footprint move with the thread count:
def peak_arrays(fn, *args, unit):
"""Peak simultaneously-live memory, in units of one full-size array."""
fn(*args) # warm up
tracemalloc.start()
tracemalloc.reset_peak()
fn(*args)
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak / unit
print(f" 1 serial : {peak_arrays(w_tilde, *w_args, unit=CELL_W):5.1f} arrays\n")
for nt in THREADS:
numba.set_num_threads(nt)
p = peak_arrays(w_tilde_parallel, *w_args, unit=CELL_W)
print(f"{nt:3d} thread{'s' if nt > 1 else ' '}: {p:5.1f} arrays {p * CELL_W / 1e6:7.1f} MB")
numba.set_num_threads(NT) 1 serial : 4.0 arrays
1 thread : 6.0 arrays 12.6 MB
2 threads: 8.0 arrays 16.8 MB
4 threads: 12.0 arrays 25.2 MB
8 threads: 20.0 arrays 41.9 MB
16 threads: 36.0 arrays 75.5 MB
32 threads: 68.0 arrays 142.6 MB
The slope is two full-size arrays per thread: the private accumulator, and the private cosine temporary feeding it. At full thread count the function needs some seventy times the memory of the answer it returns.
That is the real bill for parallel=True on a reduction, and it is the one that bites in production, because it grows precisely when you scale up to the machine where you wanted the parallelism. At the production size the output alone is 40 GB; multiplying that by the thread count is not an option, and nothing will warn you before the job dies. State it as a rule: a prange reduction costs one private copy of the reduction variable per thread. Free for a scalar. nthreads × for an array.
There is a way out, and it is a choice in the source rather than in the decorator. Nothing says the parallel loop has to be the one over \(k\). Go back to the original formulation of this function — the triple loop, transcribed straight from the maths — and parallelise over image pixels instead:
def w_tilde_ij_src(noise_map_real, uv_wavelengths, grid_radians_slim):
M = grid_radians_slim.shape[0]
K = uv_wavelengths.shape[0]
w = np.zeros((M, M))
for i in prange(M):
for j in range(M):
y_offset = grid_radians_slim[i, 1] - grid_radians_slim[j, 1]
x_offset = grid_radians_slim[i, 0] - grid_radians_slim[j, 0]
acc = 0.0
for k in range(K):
acc += np.cos(
TWO_PI * (y_offset * uv_wavelengths[k, 0] + x_offset * uv_wavelengths[k, 1])
) / (noise_map_real[k] * noise_map_real[k])
w[i, j] = acc
return w
w_tilde_ij, w_tilde_ij_parallel = two_ways(w_tilde_ij_src, W_SIG)
print("matches:", np.allclose(w_tilde_ij_parallel(*w_args), w_ref))matches: True
1 serial : 404.71 ms 1.00× █ (vectorised: 345.7 ms)
1 thread : 401.80 ms 1.01× █
2 threads: 202.66 ms 2.00× ██
4 threads: 102.09 ms 3.96× ████
8 threads: 52.27 ms 7.74× ████████
16 threads: 31.04 ms 13.04× █████████████
32 threads: 23.69 ms 17.08× █████████████████
1 threads: 1.0 arrays
32 threads: 1.0 arrays
Half again as fast, and one array of memory at any thread count. Read the two versions against each other, because their ordering reverses:
| serial | parallel | memory | |
|---|---|---|---|
prange over \(k\), vectorised |
faster | ≈ 10× | grows with thread count |
prange over \(i\), triple loop |
slower | ≈ 16× | constant |
The triple loop is the worse serial program — a scalar cosine at a time, no vectorised pass over a grid — and it is the better parallel one, by half again in time and seventy-fold in memory.
It is the same mechanism seen from the other side. Along \(k\), every iteration touches all of w, so threads need private copies and a merge. Along \(i\), every iteration owns its own rows of w: no two threads ever write the same cache line, so there is no reduction, no private copy, and no merge. The work partitions cleanly, and clean partitioning is worth more than a good serial constant.
Notice also that it keeps scaling past sixteen. This machine has sixteen cores and thirty-two hardware threads, and the extra factor is those second threads earning their keep: a chain of dependent cos calls leaves the core’s execution units idle waiting on latency, and a co-resident thread has instructions ready to fill the gaps. Simultaneous multithreading helps exactly when a kernel is latency-bound — which is one more thing you only find out by sweeping.
So the lesson here is not “use parallel=True”. It is: choose which loop is parallel, and prefer the axis along which the threads share nothing. That is a decision about how you wrote the maths down, and no decorator can make it for you.
The other end of the range. The simplest kernel in this notebook — one addition per element, the sort of thing every numerical program is full of:
def add_src(a, b, out):
for i in prange(a.shape[0]):
out[i] = a[i] + b[i]
add, add_parallel = two_ways(add_src, "void(f8[::1], f8[::1], f8[::1])")
n = 1 << 25
a = np.random.rand(n)
b = np.random.rand(n)
out = np.empty(n)
ADD_BYTES = 3 * n * 8 # two arrays read, one written
print(f"{n:,} elements, {a.nbytes / 1e6:.0f} MB per array")
print(f"{ADD_BYTES / 1e6:.0f} MB moved per call, for {n / 1e6:.0f} M additions")
print(f"arithmetic intensity: {n / ADD_BYTES:.3f} flop/byte")33,554,432 elements, 268 MB per array
805 MB moved per call, for 34 M additions
arithmetic intensity: 0.042 flop/byte
One flop per twenty-four bytes. Given the sweep at the top of this notebook you already know what is about to happen: a single core can add twenty-four bytes together far faster than the memory system can deliver them, so the memory system is the whole story — and it is already at its limit before any threads are involved.
1 serial : 19.22 ms 1.00× 41.9 GB/s █
bandwidth demand: 69% of the ceiling
1 thread : 19.23 ms 1.00× 41.9 GB/s █
2 threads: 19.25 ms 1.00× 41.8 GB/s █
4 threads: 19.30 ms 1.00× 41.7 GB/s █
8 threads: 19.57 ms 0.98× 41.1 GB/s █
16 threads: 19.76 ms 0.97× 40.8 GB/s █
32 threads: 20.05 ms 0.96× 40.2 GB/s █
Sixteen cores. Nothing. Not a slowdown, not a speedup — flat to within the measurement noise, because the serial version was already at the machine’s bandwidth limit and there is no second bottleneck for the extra threads to relieve. All of them are standing in the same queue.
The printed demand understates that, incidentally, and it is worth knowing why. ADD_BYTES counts each array once, but a cache line that is written must first be fetched so that the untouched bytes in it survive — write-allocate, or read-for-ownership. Storing to out costs a read as well as a write, so the true traffic is four arrays rather than three, and this kernel is not at the fraction printed above but effectively at the ceiling. Every accounting of memory traffic in this notebook is a lower bound for the same reason.
This is the case the pybind11 notebook ran into with inplace_weighted_sum, and it is the ordinary case. Most array code looks like this: a couple of flops per element, memory-bound, nothing for a thread to do that a memory controller is not already doing.
Flat is the good outcome. Threads are not free to start: a parallel region has to signal the pool, hand out index ranges, and wait for every worker to report back, and that costs the same few microseconds whether the loop body is a billion elements or ten.
print(f"{'n':>12s}{'serial':>13s}{'parallel':>13s}")
for size in (1_000, 10_000, 100_000, 1_000_000, 10_000_000):
aa, bb, oo = np.random.rand(size), np.random.rand(size), np.empty(size)
ts = best_of(add, aa, bb, oo, reps=20)
tp = best_of(add_parallel, aa, bb, oo, reps=20)
verdict = f"{ts / tp:5.2f}×" if tp < ts else f"{tp / ts:5.1f}× SLOWER"
print(f"{size:12,d}{ts * 1e6:10.2f} µs{tp * 1e6:10.2f} µs {verdict}") n serial parallel
1,000 0.26 µs 6.10 µs 23.5× SLOWER
10,000 1.09 µs 7.13 µs 6.5× SLOWER
100,000 14.18 µs 30.88 µs 2.2× SLOWER
1,000,000 148.59 µs 77.35 µs 1.92×
10,000,000 5607.87 µs 5321.74 µs 1.05×
At a thousand elements parallel=True makes this function more than twenty times slower. Look at how little the parallel column moves between \(n = 10^3\) and \(n = 10^4\): that flat few microseconds is the dispatch cost, and it dominates until the array is around a million elements long.
The trap this sets is specific and common. You benchmark the kernel on a big array, parallel=True helps, you ship it — and then it gets called in a loop on small ones. Nothing fails. It just runs slower than the code you replaced.
First, applying it where there is nothing to parallelise. Numba does warn here, which is worth knowing because it is the only one of these three failures it catches:
NumbaPerformanceWarning: The keyword argument 'parallel=True' was specified but no transformation for parallel execution was possible.
Second — and this one is silent — prange is a promise you make, not a property Numba verifies. It recognises reductions, as we saw with w +=. It does not recognise arbitrary loop-carried dependences, and if you write one it will parallelise the loop regardless:
def cumulative_src(a, out):
out[0] = a[0]
for i in prange(1, a.shape[0]):
out[i] = out[i - 1] + a[i] # depends on the previous iteration
cumulative, cumulative_parallel = two_ways(cumulative_src, "void(f8[::1], f8[::1])")
ones = np.ones(1_000_000)
serial_out, parallel_out = np.empty(1_000_000), np.empty(1_000_000)
cumulative(ones, serial_out)
cumulative_parallel(ones, parallel_out)
print(f"serial last element: {serial_out[-1]:>12,.0f} (correct)")
print(f"parallel last element: {parallel_out[-1]:>12,.0f}")
print("\nno exception, no warning — just the wrong answer")serial last element: 1,000,000 (correct)
parallel last element: 31,249
no exception, no warning — just the wrong answer
Each thread began its own chunk from whatever out[i - 1] happened to hold, so the result is the length of one chunk rather than the length of the array. This is the oldest bug in parallel computing and Numba does nothing to protect you from it: prange means “I certify that these iterations are independent”, and the certifying is yours to do. Check against the serial version — as every parallel cell above has — because that check is the only thing standing between you and a plausible wrong number.
Every row is the same decorator. What differs is the kernel — and the column that predicts the outcome is not the one most people would look at.
rows = [
("Ricker, array exprs", 3 * CELL, t_numba.best, threads_ae),
("Ricker, loops", CELL, t_loops, threads_loops),
("Ricker, into a buffer", CELL, t_into, threads_into),
("w̃, prange over k", W_BYTES, t_w, threads_w),
("w̃, prange over i", W_BYTES, t_w_ij, threads_w_ij),
("a + b", ADD_BYTES, t_add, threads_add),
]
print(f"{'':23s}{'serial':>10s}{'GB/s':>8s}{'of max':>8s}{'best':>10s}{'speedup':>9s}{'at':>5s}")
for name, moved, t_ser, times in rows:
t_best = min(times.values())
nt_best = min(times, key=times.get)
d = moved / t_ser
print(
f"{name:23s}{t_ser * 1e3:8.2f} ms{d / 1e9:8.2f}{100 * d / CEILING:7.2f}%"
f"{t_best * 1e3:8.2f} ms{t_ser / t_best:8.2f}×{nt_best:5d}"
)
print("\nGB/s = bytes that must cross the memory bus per call ÷ serial time, counting")
print(" each array traversal once — a lower bound, see write-allocate above")
print(f"of max = that, against this machine's measured ceiling of {CEILING / 1e9:.0f} GB/s")
print(f"at = thread count giving the best time (of {NT} available)") serial GB/s of max best speedup at
Ricker, array exprs 44.30 ms 8.58 14.06% 15.46 ms 2.87× 8
Ricker, loops 38.06 ms 3.33 5.45% 6.50 ms 5.86× 8
Ricker, into a buffer 33.73 ms 3.76 6.15% 2.92 ms 11.56× 32
w̃, prange over k 345.68 ms 0.01 0.01% 32.77 ms 10.55× 16
w̃, prange over i 404.71 ms 0.01 0.01% 23.69 ms 17.08× 32
a + b 19.22 ms 41.90 68.64% 19.23 ms 1.00× 1
GB/s = bytes that must cross the memory bus per call ÷ serial time, counting
each array traversal once — a lower bound, see write-allocate above
of max = that, against this machine's measured ceiling of 61 GB/s
at = thread count giving the best time (of 32 available)
At the extremes the of max column decides everything. Most of the bus — effectively all of it, once stores are counted properly — buys 1.0×. A hundredth of a percent of it buys better than 15×. No amount of tuning moves either, because in one case there is nothing left to give and in the other there is nothing in the way.
In between, bandwidth demand sets a ceiling and the rest of this notebook decides how close you get to it. The two \(\tilde{W}\) rows have identical demand and differ by half again — that gap is the private accumulator, not the bus. The three Ricker rows are the same maths at three levels of preparation. Reading one row tells you what is possible; reading rows against each other tells you what to do.
Fix the traffic first, then parallelise. This inverts the usual order, and the wavelet is the proof: on the array-expression version parallel=True was worth about 3×; on the same maths written as a loop into a caller’s buffer, an order of magnitude. Threads multiply the arithmetic fraction, so the smaller you have made everything else, the more there is to multiply.
Choose the axis. Along \(k\), ten-fold and memory proportional to the thread count; along \(i\), half again as fast and constant memory. Same maths, same decorator, different loop. Numba will parallelise whichever one you point at and will never mention that the other was better.
Price the reduction. One private copy of the reduction variable per thread — free for a scalar, potentially fatal for an array.
Sweep; do not assume. Numba defaults to NUMBA_NUM_THREADS, and that is not where every sweep above peaks: the array-expression wavelet is fastest at a quarter of it, while the kernels that scale keep improving out to twice the core count. numba.set_num_threads is one line, and on the very first kernel it was worth a third of the runtime.
Check the answer. prange is an assertion about your loop, and its failure mode is a plausible wrong number rather than a crash.
Numba hands you the register (the loops notebook), the cores (this one), and the diagnostics to see what it did with both — in Python, in a notebook, without leaving the language your callers already speak. What it does not hand you is the judgement about which loop to parallelise and what that will cost, and those questions read the same in C++, in Fortran and in CUDA. The tool is cheap. The thinking is the work.