Module contents
Lesson 22 of 26Advanced 110 min

Compiling the hot loop: Numba, pybind11 and fair comparisons

When NumPy is not enough, compile. Understand the interpreter's overhead, accelerate code with Numba, write C++ extensions with pybind11 or nanobind that receive arrays without copies and release the GIL, and compare the options rigorously on the same kernel to know what to choose and when it is not worthwhile.

After this lesson you can

  • Quantify Python interpreter overhead and the overhead of each NumPy call.
  • Accelerate kernels with Numba (njit, prange, fastmath), understanding its restrictions.
  • Write and compile a C++ extension with pybind11 or nanobind that operates on NumPy arrays without copies and releases the GIL.
  • Share memory between NumPy, PyTorch and C++ through the buffer protocol and DLPack.
  • Design and present a fair performance comparison between implementations, with verified accuracy and reference to the roofline.

Before you start

Motivation: the loop NumPy cannot swallow

The rule you learned in the vectorization lesson is to take the loop out of Python and give it to NumPy, which runs it in C. It works when the loop is an operation on whole arrays. But some loops are not, and they arise in exactly the projects you want to build:

  • AlphaZero self-play. Each move requires hundreds of Monte Carlo tree-search simulations (800 per move during training in the AlphaZero paper). Each simulation descends the tree choosing a child by the PUCT formula, applies a move to a board, then climbs back up updating counters. It is a sequential traversal with branches and irregular data structures: the self-play pipeline spends almost all its time in code like this.
  • An event-by-event backtest. A strategy with a trailing stop decides at each event according to its state (am I in a position? what was the maximum since entry?), and that state depends on the entire previous path. This is the event-driven backtester architecture, and no array expression can replace it.

The cell runs such a backtest over 200000 prices, first traversing a NumPy array and then a Python list, and compares it with a computation that does vectorize (buy and hold).

[ ]A backtest that resists vectorizationBrowser
import time
import numpy as np

rng = np.random.default_rng(0)
n = 200_000
precios = 100 * np.exp(np.cumsum(0.001 * rng.standard_normal(n)))   # un camino aleatorio de 200000 eventos

def backtest(p, stop=0.02, espera=50):
    """Largo con stop dinámico: cierra si el precio cae un 2 % desde el máximo desde la entrada y reentra 50 eventos después."""
    dentro, maximo, entrada, reabrir, pnl, operaciones = True, p[0], p[0], 0, 0.0, 0
    for t in range(1, len(p)):
        x = p[t]
        if dentro:
            if x > maximo:
                maximo = x
            if x < maximo * (1 - stop):                 # salta el stop: el estado depende de todo el camino
                pnl += x / entrada - 1
                dentro, reabrir, operaciones = False, t + espera, operaciones + 1
        elif t >= reabrir:
            dentro, maximo, entrada = True, x, x
    return pnl, operaciones

for nombre, datos in (("array de NumPy", precios), ("lista de floats", precios.tolist())):
    t0 = time.perf_counter()
    pnl, ops = backtest(datos)
    dt = time.perf_counter() - t0
    print(f"{nombre:16s}: {dt * 1e3:6.0f} ms, {dt / n * 1e9:5.0f} ns por evento  ({ops} operaciones, P&L {pnl:+.3f})")
t0 = time.perf_counter(); r = np.diff(np.log(precios)).sum(); dt = time.perf_counter() - t0
print(f"comprar y mantener, vectorizado: {dt * 1e3:6.2f} ms, {dt / n * 1e9:5.1f} ns por evento")

Three things about the output (in your browser, with Pyodide; exact numbers depend on the machine and load, ratios much less so). The loop costs on the order of a hundred nanoseconds per event (171 ns in the reference run, 62 ns in another with less load) for half a dozen comparisons and multiplications that a processor handles in a few nanoseconds. Traversing the NumPy array element by element is slower than traversing a list, by three to four times (650 versus 171 ns per event in the reference, 219 versus 62 in the other): each p[t] on an array creates a new np.float64 object, whereas the list already stores float objects. The vectorized calculation, a different computation (buy and hold, without state), takes about 40 ns per event with three array operations (20 in the other run). The stop-based backtest cannot use that recipe; its overhead is the interpreter.

This lesson gives you tools for that case, in increasing order of intervention:

  • Measure overhead from the interpreter and each NumPy call, to know when compilation pays off.
  • Numba, which compiles numerical Python functions to machine code at runtime.
  • pybind11 and nanobind, which expose C++ as Python modules, and how to cross the boundary without copying: the buffer protocol and DLPack, which share memory among NumPy, PyTorch and C++.
  • C++ PyTorch extensions.
  • Fair comparisons: a benchmark of the same kernel in eight versions, with verified accuracy, the roofline as arbiter and Bailey’s and Hoefler and Belli’s rules to avoid fooling yourself.

Anatomy of overhead

To know how much a compiler can gain, you need to know where interpreter time goes. See what CPython executes for return x + y:

[ ]Inside the interpreterBrowser
import dis, sys, timeit
import numpy as np

def suma(x, y):
    return x + y
dis.dis(suma)
print("\nun float de Python ocupa", sys.getsizeof(1.0), "bytes; en un array float64 ocupa 8")

def ns(stmt, setup="pass", number=20_000):
    return min(timeit.repeat(stmt, setup, number=number, repeat=5)) / number * 1e9

base = ns("pass")
print(f"z = x + y con floats: {ns('z = x + y', 'x = 3.0; y = 4.0') - base:5.0f} ns, descontado el bucle")
ts = {}
for n in (1, 10, 100, 1000, 10_000, 100_000):
    s = f"import numpy as np; a = np.ones({n}); b = np.ones({n}); c = np.empty({n})"
    ts[n] = ns("np.add(a, b, out=c)", s, number=max(20, 20_000 * 100 // (100 + n)))
N = np.array(list(ts), dtype=float); T = np.array(list(ts.values()))
t0, c = np.linalg.lstsq(np.stack([np.ones_like(N), N], 1) / T[:, None], np.ones_like(T), rcond=None)[0]
for n, t in ts.items():
    print(f"np.add con n = {n:>6d}: {t:9.0f} ns  ({t / n:8.2f} ns por elemento)")
print(f"ajuste t(n) = t0 + c·n:  t0 = {t0:.0f} ns,  c = {c:.2f} ns por elemento,  10 % de sobrecoste en n = {9 * t0 / c:.0f}")

The disassembly has three bytecode instructions, besides RESUME, which marks function entry: a superinstruction loading both arguments on the stack (recent CPython versions fuse consecutive loads this way; its exact name changes between versions), BINARY_OP with operand 0, meaning +, and RETURN_VALUE. Each hides a lot of work:

  1. Dispatch. The interpreter’s evaluation loop reads the instruction, jumps to its handler and moves pointers on a value stack. Since Python 3.11 the interpreter is adaptive and specialized (PEP 659): after a few executions it rewrites BINARY_OP as BINARY_OP_ADD_FLOAT or BINARY_OP_ADD_INT if types repeat, saving some subsequent work, but each execution still checks the assumption.
  2. Dynamic dispatch by type. x and y can be anything. The interpreter checks each operand’s type (a pointer in the object header) and calls that type’s addition function; if none exists or it returns NotImplemented, it tries the other operand’s.
  3. Heap objects. A Python number is not a number: it is an object with a reference count, a pointer to its type and then the value. In 64-bit CPython an float occupies 24 bytes to store 8 bytes of data (the cell prints 16 because Pyodide is 32-bit WebAssembly, with 4-byte pointers). Adding means unpacking both double, adding them and creating a new object for the result, as well as adjusting reference counts and releasing the variable’s previous value.

In the cell, np.add on one-element arrays costs on the order of a microsecond in Pyodide (968 ns in the reference run), and per element falls to around a nanosecond as nn grows: a relative least-squares fit of t(n)=t0+c nt(n) = t_0 + c\,n separates the two parts (t0=926t_0 = 926 ns, c=1.19c = 1.19 ns). Adding two float in Python costs 28 ns there: a one-element NumPy call costs more than thirty interpreter additions. In another run, with less load, everything was faster (t0=511t_0 = 511 ns, c=0.56c = 0.56 ns, 11 ns per addition), but the call-to-addition ratio remained several dozen. The practical consequence is a simple calculation.

Proof

φ\varphi decreases because its denominator grows with nn. Since t0+c n>0t_0 + c\,n > 0, φ(n)<ε  ⟺  t0<ε(t0+c n)  ⟺  (1−ε) t0<ε c n\varphi(n) < \varepsilon \iff t_0 < \varepsilon(t_0 + c\,n) \iff (1 - \varepsilon)\,t_0 < \varepsilon\, c\, n, and dividing by εc>0\varepsilon c > 0 gives the result.

∎

The ratio t0/ct_0 / c is the problem’s natural scale: the number of elements a call “costs”. On the reference machine with native CPython, the next local cell measures t0≈400t_0 \approx 400 ns and c≈0.36c \approx 0.36 ns when data fit in cache, so t0/c≈1100t_0 / c \approx 1100 and a NumPy operation needs around ten thousand elements for fixed cost to drop below 10%. With ten-element arrays, over 90% of the time is overhead: vectorizing a loop over small arrays does not help.

The next cell measures each stage separately on your machine with native CPython: each measurement differs from another in one thing, and the difference is that thing’s cost. z = x versus the empty loop measures dispatching two instructions (load x and store z); z = x + y with small integers adds loading y and addition without creating objects, because CPython precreates integers from −5 to 256; with large integers the result must be created. For arrays it compares np.add(a, b, c), which writes to an existing array (the third positional argument is out), with np.add(a, b), which allocates a new one: the call is the same apart from allocation.

[ ]Anatomy of overhead on your machineLocal GPU
import json, timeit
import numpy as np

def ns(stmt, setup="pass"):
    t = timeit.Timer(stmt, setup)
    number, _ = t.autorange()
    return min(t.repeat(7, number)) / number * 1e9

m = {
    "bucle": ns("pass"),
    "carga": ns("z = x", "x = 3"),
    "is": ns("z = x is y", "x = 3; y = 4"),
    "int_peq": ns("z = x + y", "x = 3; y = 4"),
    "int_grande": ns("z = x + y", "x = 10**6; y = 2 * 10**6"),
    "float": ns("z = x + y", "x = 3.0; y = 4.0"),
    "np_escalar": ns("z = x + y", "import numpy as np; x = np.float64(3); y = np.float64(4)"),
}
arr = {}
for n in (1, 10, 100, 1000, 10_000, 100_000, 1_000_000):
    s = f"import numpy as np; a = np.ones({n}); b = np.ones({n}); c = np.empty({n})"
    arr[n] = (ns("np.add(a, b, c)", s), ns("np.add(a, b)", s))   # el tercer argumento es out: misma llamada, sin reservar
for k, v in m.items():
    print(f"{k:11s} {v:7.1f} ns por iteración")
print(f"\n{'n':>9s} {'np.add(a, b, c)':>16s} {'np.add(a, b)':>13s} {'ns/elem':>8s}")
for n, (t_out, t_new) in arr.items():
    print(f"{n:9d} {t_out:14.0f} ns {t_new:11.0f} ns {t_out / n:8.2f}")
n_ = np.array([1, 10, 100, 1000, 10_000, 100_000], dtype=float); t_ = np.array([arr[int(k)][0] for k in n_])
t0, c = np.linalg.lstsq(np.stack([np.ones_like(n_), n_], 1) / t_[:, None], np.ones_like(t_), rcond=None)[0]
print(f"\nt(n) = t0 + c·n con n <= 1e5: t0 = {t0:.0f} ns, c = {c:.3f} ns/elem (en caché);"
      f" con n = 1e6, {arr[1_000_000][0] / 1e6:.2f} ns/elem;  10 % de sobrecoste en n = {9 * t0 / c:.0f}")
print("datos del interactivo:", json.dumps({**{k: round(v, 1) for k, v in m.items()}, "t0": round(t0, 1), "c": round(c, 4),
      "arr": {n: [round(a, 1), round(b, 1)] for n, (a, b) in arr.items()}}))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the reference run, an empty iteration of the timeit loop cost 6.2 ns, loading and storing a variable another 11 ns, loading y and adding two small integers another 7 ns, and creating the result integer (with 10**6 + 2 * 10**6) another 8.6 ns: of the 26.5 ns to add two large integers (excluding the loop), about three quarters goes to moving pointers on the interpreter stack and creating the result object. An addition of two np.float64 cost 62.6 ns per iteration (including the loop), over twice that of two float (27.3 ns): NumPy scalars go through NumPy’s type machinery, designed for arrays. For arrays the fit gives t0=398t_0 = 398 ns and c=0.36c = 0.36 ns per element, with a 10% threshold at n∗=9 t0/c=10000n^* = 9\,t_0/c = 10000. At a million elements the per-element cost rises to 1.19 ns: the three arrays (24 MB) no longer fit in one core’s 2 MiB L2 and the operation depends on L3 and memory bandwidth, not arithmetic. Allocating the result, which costs tens of nanoseconds for small arrays, costs almost as much as the addition itself for large arrays (70.7 versus 32.8 µs with n=105n = 10^5): newly allocated memory must be touched for the first time. That is the reason for the out= versions in the vectorization lesson.

InteractiveAnatomy of overhead
np.add(a, b) with n = 1000: 1.54 µs26 %51 %23 %ufunc call: 398 nsAllocate result: 785 nsCompiled loop: 354 ns
Compiled loop (354 ns). The only useful work: an SIMD-vectorized C loop adding 1000 float64 pairs at about 0.35 ns per element.
110¹10²10³10⁴10⁵10⁶0.10 ns1.0 ns10 ns100 ns1.00 µs10.0 µsarray elements nfixed = 10%Python float loopnp.float64 loop
  • NumPy: measured time / n
  • one Python z = x + y per element
  • same with np.float64
With n = 1000, fixed cost is 26 % of the total. Per element, NumPy is cheaper than a Python loop from n ≈ 19; with n = 1, one NumPy operation costs 18 Python-loop float additions.
Operation
1000
Stage 3 of 3
Operation time1.54 µs
Call (independent of n)25.9 %
Per element1.5 ns
10% overhead atn ≈ 10000
Each bar breaks down an operation's time into the stages measured in the previous cell (reference run). Start at «array de n» with n = 1000: play through the stages and see how much is useful work. Lower n to 1 and raise it to a million. Then compare int 3 + 4 with large int, float and np.float64. The chart below gives cost per element: from what n is NumPy cheaper than a Python loop, and from what n does its fixed cost stop mattering?

The interactive chart summarizes this. NumPy’s cost per element falls as t0/nt_0/n until it meets cc, and drops below a Python z = x + y from a few dozen elements: for an array of twenty numbers, NumPy is already cheaper per element than a loop. But fixed cost stops mattering only around ten thousand. Between them is the awkward zone: arrays of hundreds of elements processed in a Python loop, exactly what a tree search or stateful simulator does. There NumPy does not help and you need to compile.

Numba: compiling the loop at runtime

If a loop cannot be expressed as array operations, the alternative is to eliminate the interpreter: translate the function to machine code working directly with double in registers. Doing it at runtime, once argument types are known, is the idea of JIT compilation.

Numba (Lam, Pitrou and Seibert, 2015) is an LLVM-based JIT compiler for a subset of numerical Python. When you first call a function decorated with @njit:

  1. Bytecode analysis. Numba reads the function’s bytecode (the same you saw with dis) and translates it to its own intermediate representation with explicit control flow.
  2. Type inference. From this call’s argument types (for example, float64[:, ::1], a C-contiguous 2D float64 array) it propagates types to every variable and operation. If a variable can have two types that cannot be unified, or an operation is unsupported, compilation fails with an TypingError.
  3. LLVM IR generation. With all types known, each operation becomes low-level instructions on unboxed values: an float64 is a register, an array is a pointer, shape and strides.
  4. Optimization and machine code. LLVM applies the optimizations of a C compiler (those studied in compiler optimizations: constant propagation, unrolling, SIMD vectorization…) and generates code for the CPU running it, with that CPU’s instructions (AVX2, AVX-512).

The object returned by @njit is a dispatcher: it stores one compiled version per combination of argument types (its signatures), and on each call checks the types, chooses a version and calls it. That dispatch has its own fixed cost, measured below.

The options that matter:

  • @njit is @jit(nopython=True): the entire body compiles without Python objects. Since Numba 0.59, @jit also compiles in nopython mode by default and no longer silently falls back to “object mode” (which called the interpreter for what it could not compile) when inference fails: it now fails with an error.
  • parallel=True with prange distributes loop iterations across threads. Numba does not check that iterations are independent: if two write to the same location, that is a race condition. It does recognize simple reductions (s += ... on a scalar) and combines them correctly.
  • fastmath=True enables LLVM permissions to treat floating-point arithmetic as real arithmetic: reassociate sums, assume no NaNs or infinities, use approximate reciprocals. The key permission is reassociation: without it, an s += x[i] reduction must sum in order and cannot be vectorized. It is the same problem as the recurrences in the vectorization lesson.
  • cache=True saves compiled code to disk next to the source file (in __pycache__), and subsequent processes load it instead of compiling.

This lesson’s lab uses a kernel poorly expressed with arrays (it needs N×NN \times N temporaries or a block loop) and with much arithmetic per datum: Lennard-Jones forces between all pairs of NN particles. Acting on particle ii is

Fi=∑j≠i24 ϵ[2(σrij)12−(σrij)6]ri−rjrij2,rij=∥ri−rj∥2,\vb{F}_i = \sum_{j \ne i} 24\,\epsilon \left[2\left(\frac{\sigma}{r_{ij}}\right)^{12} - \left(\frac{\sigma}{r_{ij}}\right)^{6}\right] \frac{\vb{r}_i - \vb{r}_j}{r_{ij}^2}, \qquad r_{ij} = \norm{\vb{r}_i - \vb{r}_j}_2,

with ϵ=σ=1\epsilon = \sigma = 1. Per ordered pair (i,j)(i, j), the code calculates the difference (3 subtractions), r2r^2 (3 products and 2 additions), 1/r21/r^2 (one division), (1/r2)3(1/r^2)^3 (2 products), the coefficient (5 operations), and accumulates three components (3 products and 3 additions): 22 flops per pair, counting division as one. This is the core of a molecular-dynamics simulation without a neighbor list and is O(N2)\bigO(N^2): with N=16384N = 16384 there are 268 million pairs.

[ ]The Lennard-Jones kernel in Python and NumbaLocal GPU
import time
import numpy as np
import numba
from numba import njit, prange

def red(N, seed=0):
    """N partículas en una red cúbica de paso 1.12 (cerca del mínimo del potencial) con un poco de ruido."""
    k = int(np.ceil(N ** (1 / 3)))
    g = np.stack(np.meshgrid(*(np.arange(k),) * 3, indexing="ij"), -1).reshape(-1, 3)[:N]
    return 1.12 * g + 0.05 * np.random.default_rng(seed).standard_normal((N, 3))

def lj_python(X):
    P = X.tolist(); n = len(P); F = []
    for i in range(n):
        xi, yi, zi = P[i]; fx = fy = fz = 0.0
        for j in range(n):
            if j != i:
                dx, dy, dz = xi - P[j][0], yi - P[j][1], zi - P[j][2]
                inv2 = 1.0 / (dx * dx + dy * dy + dz * dz)
                s6 = inv2 * inv2 * inv2
                c = 24.0 * inv2 * s6 * (2.0 * s6 - 1.0)
                fx += c * dx; fy += c * dy; fz += c * dz
        F.append((fx, fy, fz))
    return np.array(F)

def cuerpo(X):
    """El mismo algoritmo, escrito para Numba: bucles explícitos sobre un array (N, 3)."""
    n = X.shape[0]; F = np.zeros_like(X)
    for i in prange(n):                     # sin parallel=True, prange es un range normal
        xi, yi, zi = X[i, 0], X[i, 1], X[i, 2]
        fx = fy = fz = 0.0
        for j in range(n):
            if j != i:
                dx = xi - X[j, 0]; dy = yi - X[j, 1]; dz = zi - X[j, 2]
                inv2 = 1.0 / (dx * dx + dy * dy + dz * dz)
                s6 = inv2 * inv2 * inv2
                c = 24.0 * inv2 * s6 * (2.0 * s6 - 1.0)
                fx += c * dx; fy += c * dy; fz += c * dz
        F[i, 0] = fx; F[i, 1] = fy; F[i, 2] = fz
    return F

lj_numba = njit(cuerpo)
lj_numba_fm = njit(fastmath=True)(cuerpo)
lj_numba_par = njit(parallel=True, fastmath=True)(cuerpo)
HILOS = 8
numba.set_num_threads(HILOS)

X = red(1024)
for nombre, f in (("njit", lj_numba), ("njit fastmath", lj_numba_fm), ("njit parallel fastmath", lj_numba_par)):
    t0 = time.perf_counter(); f(X); t1 = time.perf_counter(); f(X); t2 = time.perf_counter()
    print(f"{nombre:24s} primera llamada {t1 - t0:6.2f} s, segunda {1e3 * (t2 - t1):6.2f} ms")
t0 = time.perf_counter(); F_py = lj_python(X); t_py = time.perf_counter() - t0
print(f"{'Python puro':24s} {1e3 * t_py:6.0f} ms ({1e9 * t_py / (1024 * 1023):.0f} ns por par)")
for nombre, f in (("njit", lj_numba), ("njit fastmath", lj_numba_fm), ("parallel", lj_numba_par)):
    print(f"error relativo de {nombre:14s}: {np.abs(f(X) - F_py).max() / np.abs(F_py).max():.1e}")
print("firmas compiladas:", lj_numba.signatures)
for nombre, f in (("njit", lj_numba), ("njit fastmath", lj_numba_fm)):
    asm = f.inspect_asm(f.signatures[0])
    print(f"{nombre:14s}: divisiones vectoriales (vdivpd) {asm.count('vdivpd'):3d}, escalares (vdivsd) {asm.count('vdivsd'):3d}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

What the reference-run output says, with N=1024N = 1024:

  • Compilation takes seconds; execution, milliseconds. The first call to njit took 1.59 s and the second 7.53 ms. The other two variants compiled faster (0.42 and 0.81 s), largely because the first compilation in a process also pays for starting the Numba compiler, which is not repeated: measurement order matters, another reason to declare how measurement was done.
  • Removing the interpreter gains two orders of magnitude. Pure Python took 402 ms, 384 ns per pair; njit took about fifty times less, and the 8-thread parallel version (0.71 ms), more than five hundred times less.
  • The result agrees. Without fastmath, the compiled version gives exactly the same bits as Python (error 0): it performs the same operations in the same order. With fastmath, relative error is 3.6×10−163.6 \times 10^{-16}, of order unit roundoff: the permissions of fastmath (fusing products and sums into an FMA, reordering operations) changed some rounding, as expected.
  • fastmath did not vectorize this loop. The assembly of both versions has one division, vdivsd, the double-precision scalar one, and no vdivpd, the vector one. With stride-three access in an (N, 3) array and the if j != i branch, LLVM’s vectorizer generated no SIMD code, and both serial versions take the same time within noise (7.53 and 4.96 ms in this run, one measurement each; reversed in other runs). General lesson: do not attribute a speedup to SIMD without looking at assembly, which inspect_asm gives in one line.
  • One signature per type combination. signatures shows the sole compiled specialization: a two-dimensional float64 array, C-contiguous ('C'). Calling it with a noncontiguous array or float32 would compile another.

The second cell shows two other behaviors you need to know: the compilation cache across processes and what happens when Numba cannot infer types.

[ ]Compilation cache and type errorsLocal GPU
import inspect, os, shutil, subprocess, sys, tempfile, warnings
from pathlib import Path
from numba import njit, errors

carpeta = Path(tempfile.gettempdir()) / "oryon-m09-l22" / "cache_demo"
carpeta.mkdir(parents=True, exist_ok=True)
fuente = "import time\nt0 = time.perf_counter()\nimport numpy as np\nfrom numba import njit, prange\nt1 = time.perf_counter()\n\n"
fuente += "@njit(parallel=True, fastmath=True, cache=True)\n" + inspect.getsource(cuerpo)    # el kernel de Lennard-Jones
fuente += "\ncuerpo(np.ones((8, 3)) * np.arange(8)[:, None])\nt2 = time.perf_counter()\nprint(f'{t1 - t0:.2f} {t2 - t1:.2f}')\n"
(carpeta / "kernel.py").write_text(fuente, encoding="utf-8")
entorno = {**os.environ, "NUMBA_CACHE_DIR": str(carpeta / "cache"), "PYTHONUTF8": "1"}
shutil.rmtree(carpeta / "cache", ignore_errors=True)
for intento in ("primer proceso (compila y guarda)", "segundo proceso (lee la caché)"):
    t_imp, t_llamada = subprocess.run([sys.executable, str(carpeta / "kernel.py")], capture_output=True, text=True, env=entorno).stdout.split()
    print(f"{intento:36s}: importar NumPy y Numba {t_imp} s, primera llamada {t_llamada} s")
print("ficheros de caché:", sorted(p.suffix for p in (carpeta / "cache").rglob("*.nb*")))

@njit
def raiz_o_aviso(x):
    if x >= 0:
        return x ** 0.5
    return "negativo"          # dos tipos de retorno: float64 y str
try:
    raiz_o_aviso(4.0)
except errors.TypingError as e:
    print("\nTypingError:", " ".join(str(e).split())[:230], "...")

@njit
def total(xs):
    s = 0.0
    for v in xs:
        s += v
    return s
with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    total([1.0, 2.0, 3.0])     # una lista de Python: Numba la «refleja» y avisa
print("\naviso al pasar una lista:", w[0].category.__name__ if w else "ninguno")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The cache works as promised, with caveats. The first process took 1.25 s on its first call (compiling the parallel kernel), and the second, reading it from files .nbi (the index) and .nbc (the code), 0.61 s: not zero, because loading code and starting Numba threads also costs time, but half as much, with larger savings the more expensive compilation is. Importing NumPy and Numba, about 0.7 s, is always paid. The function with two return types does not compile: Can't unify return type, an TypingError in type inference. Passing a Python list produces NumbaPendingDeprecationWarning: Numba converts it to a typed list and copies changes back to the original on return (“reflection”), an expensive behavior being phased out; use arrays or numba.typed.List.

Overview: other ways to compile Python

Numba is not the only way to remove the interpreter. Each tool compiles something different at a different time, and choosing poorly costs more than not compiling:

ToolWhen it compilesWhat it compilesWhere types come fromWhen to use it
Numbaon the first call for each combination of typesfunctions with loops over scalars and NumPy arraysinferred from argumentsnumerical loops not expressible as arrays
Cythonbefore execution: translates the module to C and compiles it as an extensiona superset of Python with C type declarationsfrom declarations (cdef, annotations)library extensions and wrapping existing C; used by SciPy, scikit-learn and pandas
mypycbefore executionordinary Python modules with type annotationsfrom annotations, checked at runtimeapplication code with classes and types; mypy is distributed compiled with mypyc
torch.compileat runtime, capturing each graphtensor-operation graphs captured from bytecodefrom example tensors: shapes, types and devicefuse operations in a PyTorch model: TorchInductor generates Triton kernels on GPU and C++ with OpenMP on CPU
jax.jitat runtime, tracing the functionpure array functions converted to a graph compiled by XLAfrom argument shapes and types (changing them recompiles)functional numerical programs on GPU or TPU, together with grad and vmap

What separates Numba from torch.compile and jax.jit is what they capture: Numba compiles scalar loops and optimizes them like a C compiler; the other two capture and fuse array-operation graphs, as seen in graph capture and operator fusion. An event-by-event backtest or search tree is not a tensor graph: use Numba or C++ for those.

pybind11 and nanobind: C++ as a Python module

Numba compiles a subset of Python. When you need more (C++ data structures, templates, an existing C++ library such as Eigen or an MCTS implementation, full control of memory and threads), write C++ and expose it as a Python module. In C++ compilation this is a shared library: an .so on Linux or an .pyd on Windows that the interpreter loads with import and which defines an initialization function with a module-determined name.

pybind11 (Wenzel Jakob and collaborators) has been the de facto standard for a decade; nanobind, by the same author, is its lighter successor. According to benchmarks in its documentation (Ryzen 9 7950X, Clang 15), nanobind compiles around 2.7 to 4.4 times faster, produces binaries 3 to 5 times smaller (when compiling for size), and has about 3 times less per-call overhead for simple functions and 10 times less when passing class objects. The API is almost the same: PYBIND11_MODULE versus NB_MODULE, py:: versus nb::.

What you need to know to write bindings that are not the bottleneck:

  • Three ways to pass data. The pybind11 documentation distinguishes: (1) a C++ type wrapped in a Python object (classes exposed with py::class_), crossing by reference, without copying; (2) a Python type manipulated from C++ (py::object, py::list, py::array), also not copied; and (3) a type caster between a native C++ and Python type, such as std::vector<double> and a list, which constructs a new object at each crossing. Converters are convenient and expensive.
  • Zero-copy arrays. py::array_t<double, flags> wraps a NumPy array (type 2). By default it carries the forcecast flag: if dtype is not float64, pybind11 converts (copying); py::array::c_style also requires C contiguity, again copying if necessary. In nanobind, nb::ndarray<double, nb::c_contig, nb::device::cpu> expresses the same restrictions with template parameters and accepts PyTorch, JAX or CuPy tensors as well as NumPy.
  • Exceptions. An std::invalid_argument thrown in C++ reaches Python as ValueError, std::out_of_range as IndexError, std::bad_alloc as MemoryError and the remaining std::exception as RuntimeError. Check array shapes in C++ and throw: an out-of-bounds access in C++ produces undefined behavior, not an error.
  • Object lifetime. When C++ returns a pointer or reference to something that already exists, pybind11 needs to know who frees it: return value policies (copy, reference, reference_internal, take_ownership…) and py::keep_alive specify this. For an array pointing to memory owned by a C++ object, the pattern is to provide that object as the array’s base; you will do this in an exercise. This is the Python version of what you learned about memory and RAII.
  • The GIL. The standard CPython interpreter has a global lock (global interpreter lock): only one thread executes Python code at a time. A C++ function called from Python holds it while running unless it releases it with py::gil_scoped_release (or nb::gil_scoped_release) during computation. With the GIL released you cannot touch any Python object, not even create an array or print with py::print: extract pointers and sizes first, release it, compute, and reacquire the GIL on leaving the block. A C++ exception can be thrown inside: on leaving the block, the gil_scoped_release destructor reacquires the GIL and then pybind11 translates it. This allows several Python threads to execute C++ in parallel; the parallelism lesson studies the GIL in depth, including free-threaded CPython (PEP 703), which began experimentally in Python 3.13.

Building: by hand and with scikit-build-core

An extension is a C++ file compiled as a shared library against Python and pybind11 or nanobind headers and linked (on Windows) with Python’s import library. The next cell does this by hand so you can see the compile command: it finds the compiler (on Windows, loads the Visual Studio environment with vcvars64.bat; on Linux uses c++), compiles with optimization /O2 or -O3, and loads the module with importlib. If you do not have pybind11 or nanobind, the cell installs them with pip the first time (requiring a connection), in a lesson-specific folder in the temporary directory, without touching your environment; in a real project declare them as build dependencies, as in your pyproject.toml. You need a C++ compiler (on Windows, Visual Studio Build Tools with the C++ workload; prepared when setting up the C++ toolchain).

[ ]The build toolchain: pybind11, nanobind and the compilerLocal GPU
import hashlib, importlib, importlib.util, os, platform, shutil, subprocess, sys, sysconfig, tempfile, time
from pathlib import Path

BUILD = Path(tempfile.gettempdir()) / "oryon-m09-l22"
BUILD.mkdir(parents=True, exist_ok=True)
WIN = platform.system() == "Windows"

def asegurar(paquete):
    """Importa el paquete; si falta, lo instala en una carpeta propia de la lección (sin tocar tu entorno)."""
    try:
        return importlib.import_module(paquete)
    except ImportError:
        destino = BUILD / "pip" / paquete                 # una carpeta por paquete: pip --target no fusiona carpetas
        if not (destino / paquete).is_dir():
            subprocess.run([sys.executable, "-m", "pip", "install", "-q", "--target", str(destino), paquete], check=True)
        sys.path.insert(0, str(destino))
        return importlib.import_module(paquete)

pybind11 = asegurar("pybind11")
nanobind = asegurar("nanobind")

def entorno_msvc():
    """En Windows, carga las variables de vcvars64.bat (PATH, INCLUDE, LIB) para poder llamar a cl.exe."""
    if shutil.which("cl"):
        return
    vswhere = Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Microsoft Visual Studio/Installer/vswhere.exe"
    vs = subprocess.run([str(vswhere), "-latest", "-products", "*", "-requires",
                         "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"],
                        capture_output=True, text=True).stdout.strip()
    salida = subprocess.run(f'"{Path(vs) / "VC/Auxiliary/Build/vcvars64.bat"}" >nul && set',
                            shell=True, capture_output=True, text=True).stdout
    for linea in salida.splitlines():
        if "=" in linea:
            k, v = linea.split("=", 1)
            os.environ[k] = v

if WIN:
    entorno_msvc()

def compilar(nombre, fuente, nb=False, rapido=False, openmp=False, ver=False):
    """Compila `fuente` (C++ con pybind11 o, si nb=True, con nanobind) como módulo de extensión y lo importa.
    rapido: fast-math y AVX2 (/fp:fast /arch:AVX2 o -ffast-math -march=native); openmp: hilos OpenMP."""
    h = hashlib.sha1(f"{fuente}{nb}{rapido}{openmp}".encode()).hexdigest()[:8]
    mod = f"{nombre}_{h}"                                   # un nombre por versión: un .pyd no se puede recargar
    destino = BUILD / (mod + sysconfig.get_config_var("EXT_SUFFIX"))
    if not destino.exists():
        cpp = BUILD / f"{mod}.cpp"
        cpp.write_text(fuente, encoding="utf-8")
        inc, srcs = [sysconfig.get_paths()["include"]], [str(cpp)]
        if nb:                                              # nanobind se compila junto con el módulo
            raiz = Path(nanobind.source_dir()).parent
            inc += [str(raiz / "include"), str(raiz / "ext/robin_map/include")]
            srcs.append(str(raiz / "src/nb_combined.cpp"))
        else:
            inc.append(pybind11.get_include())
        if WIN:
            cmd = ["cl", "/nologo", "/O2", "/EHsc", "/std:c++17", "/MD", "/LD", "/bigobj", "/DNDEBUG", f"/DMODNAME={mod}"]
            cmd += (["/fp:fast", "/arch:AVX2"] if rapido else []) + (["/openmp"] if openmp else [])
            cmd += [f"/I{d}" for d in inc] + srcs + ["/link", f"/LIBPATH:{Path(sys.base_prefix) / 'libs'}", f"/OUT:{destino}"]
        else:
            cmd = ["c++", "-O3", "-shared", "-fPIC", "-std=c++17", "-DNDEBUG", f"-DMODNAME={mod}"]
            cmd += (["-ffast-math", "-march=native"] if rapido else []) + (["-fopenmp"] if openmp else [])
            cmd += [f"-I{d}" for d in inc] + srcs + ["-o", str(destino)]
        if ver:
            print("$", " ".join(Path(c).name if os.sep in c or "/" in c else c for c in cmd))
        t0 = time.perf_counter()
        r = subprocess.run(cmd, cwd=BUILD, capture_output=True, text=True)
        if r.returncode != 0:
            raise RuntimeError(f"error de compilación:\n{r.stdout[-3000:]}{r.stderr[-3000:]}")
        print(f"compilado {mod} en {time.perf_counter() - t0:.1f} s")
    spec = importlib.util.spec_from_file_location(mod, destino)
    m = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(m)
    return m

print(f"pybind11 {pybind11.__version__}, nanobind {nanobind.__version__}, compilador:",
      shutil.which("cl") if WIN else shutil.which("c++"))

LJ_CPP = r'''
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <stdexcept>
namespace py = pybind11;
using Posiciones = py::array_t<double, py::array::c_style | py::array::forcecast>;

py::array_t<double> fuerzas(Posiciones Xa, int hilos) {
    if (Xa.ndim() != 2 || Xa.shape(1) != 3) throw std::invalid_argument("X debe tener forma (N, 3)");
    const py::ssize_t n = Xa.shape(0);
    py::array_t<double> Fa({n, py::ssize_t(3)});           // el resultado lo crea C++ y lo posee NumPy
    const double* X = Xa.data();
    double* F = Fa.mutable_data();
    {
        py::gil_scoped_release sin_gil;                     // desde aquí no se toca ningún objeto de Python
        #pragma omp parallel for num_threads(hilos) schedule(static)
        for (py::ssize_t i = 0; i < n; ++i) {
            const double xi = X[3 * i], yi = X[3 * i + 1], zi = X[3 * i + 2];
            double fx = 0, fy = 0, fz = 0;
            for (py::ssize_t j = 0; j < n; ++j) {
                if (j != i) {
                    const double dx = xi - X[3 * j], dy = yi - X[3 * j + 1], dz = zi - X[3 * j + 2];
                    const double inv2 = 1.0 / (dx * dx + dy * dy + dz * dz);
                    const double s6 = inv2 * inv2 * inv2;
                    const double c = 24.0 * inv2 * s6 * (2.0 * s6 - 1.0);
                    fx += c * dx; fy += c * dy; fz += c * dz;
                }
            }
            F[3 * i] = fx; F[3 * i + 1] = fy; F[3 * i + 2] = fz;
        }
    }
    return Fa;
}

PYBIND11_MODULE(MODNAME, m) {
    m.doc() = "Fuerzas de Lennard-Jones por pares";
    m.def("fuerzas", &fuerzas, py::arg("X"), py::arg("hilos") = 1, "Fuerzas sobre cada partícula (N x 3)");
}
'''
lj_cpp = compilar("lj", LJ_CPP, ver=True)
lj_cpp_rapido = compilar("lj", LJ_CPP, rapido=True)
lj_cpp_omp = compilar("lj", LJ_CPP, rapido=True, openmp=True)
X = red(1024)
print("error relativo frente a Python:", f"{np.abs(lj_cpp.fuerzas(X) - F_py).max() / np.abs(F_py).max():.1e}")
print(lj_cpp.fuerzas.__doc__.strip().splitlines()[0])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The compile command printed by the cell (abbreviated) follows the C++ compilation model: optimization /O2, C++ exceptions (/EHsc), C++17, the runtime library in a DLL (/MD), shared-library output (/LD), Python and pybind11 headers, and linking with python313.lib. Each pybind11 module took about 4 to 6 seconds to compile and each nanobind one, compiled with its own library, about 2 in the reference runs. The MODNAME macro gives each version a different module name derived from a hash of the code, because a process cannot load an extension module with the same name twice: changing the C++ changes the name and recompiles it; otherwise the already compiled .pyd is reused.

The three kernel versions are /O2 alone, one with /fp:fast /arch:AVX2 (MSVC’s equivalent of fastmath and compiling for the CPU with AVX2, which Numba always does), and another with that plus OpenMP. The signature receives py::array_t<double, c_style | forcecast>, checks shape and throws std::invalid_argument (arriving as ValueError) if it is not (N, 3), allocates the result while holding the GIL and releases it to compute. The result matches Python bit for bit. The signature printed by __doc__ was generated by pybind11 from the C++ types.

Building by hand is fine for experimentation; to distribute the extension (to yourself on another machine or to others), package it with scikit-build-core, an pyproject.toml build backend that calls CMake. With these two files and code in src/main.cpp, pip install . builds and installs the package, and pip wheel . generates a binary wheel; on the reference machine, building a test wheel this way took about 40 seconds including downloading build dependencies, and scikit-build-core found the Visual Studio compiler without loading vcvars64.bat.

# pyproject.toml
[build-system]
requires = ["scikit-build-core>=0.10", "pybind11>=2.13"]
build-backend = "scikit_build_core.build"

[project]
name = "ljfast"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = ["numpy"]
# CMakeLists.txt
cmake_minimum_required(VERSION 3.15...3.30)
project(${SKBUILD_PROJECT_NAME} LANGUAGES CXX)

set(PYBIND11_FINDPYTHON ON)
find_package(pybind11 CONFIG REQUIRED)
find_package(OpenMP)

pybind11_add_module(_core MODULE src/main.cpp)
target_compile_features(_core PRIVATE cxx_std_17)
if(OpenMP_CXX_FOUND)
  target_link_libraries(_core PRIVATE OpenMP::OpenMP_CXX)
endif()
install(TARGETS _core DESTINATION ljfast)
install(FILES src/ljfast/__init__.py DESTINATION ljfast)

With nanobind the dependency changes (nanobind instead of pybind11) and two CMake lines: find_package(nanobind CONFIG REQUIRED) and nanobind_add_module(...) instead of pybind11_add_module(...). Notice what the file does not say: it sets neither -O3 nor -march=native. CMake builds in Release mode by default with scikit-build-core, but architecture and fast-math flags are your decision and part of what you must declare when comparing.

Each extension call crosses the Python–C++ boundary, and that crossing has a fixed cost, as with NumPy. The cell measures a do-nothing function in four versions, and a sum of 1000 elements with two different C++ signatures.

[ ]The cost of crossing the boundaryLocal GPU
import timeit
import numpy as np
from numba import njit

NADA_PB = r'''
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <vector>
namespace py = pybind11;
double nada(double x) { return x; }
double suma_vector(const std::vector<double>& v) { double s = 0; for (double x : v) s += x; return s; }
double suma_array(py::array_t<double, py::array::c_style | py::array::forcecast> a) {
    auto r = a.unchecked<1>(); double s = 0;
    for (py::ssize_t i = 0; i < r.shape(0); ++i) s += r(i);
    return s;
}
PYBIND11_MODULE(MODNAME, m) {
    m.def("nada", &nada); m.def("suma_vector", &suma_vector); m.def("suma_array", &suma_array);
}
'''
NADA_NB = r'''
#include <nanobind/nanobind.h>
namespace nb = nanobind;
double nada(double x) { return x; }
NB_MODULE(MODNAME, m) { m.def("nada", &nada); }
'''
pb = compilar("nada_pb", NADA_PB)
nbm = compilar("nada_nb", NADA_NB, nb=True)

@njit
def nada_numba(x):
    return x
nada_numba(1.0)
def nada_py(x):
    return x

def ns(stmt, g):
    t = timeit.Timer(stmt, globals=g)
    number, _ = t.autorange()
    return min(t.repeat(7, number)) / number * 1e9
g = {"pb": pb, "nbm": nbm, "nada_numba": nada_numba, "nada_py": nada_py, "x": np.random.rand(1000), "np": np}
base = ns("pass", g)
print("una llamada que no hace nada (descontado el bucle de timeit):")
for nombre, s in (("función de Python", "nada_py(1.0)"), ("Numba (despachador)", "nada_numba(1.0)"),
                  ("pybind11", "pb.nada(1.0)"), ("nanobind", "nbm.nada(1.0)")):
    print(f"  {nombre:20s} {ns(s, g) - base:6.0f} ns")
print("\nsumar un array de 1000 float64 en C++:")
for nombre, s in (("std::vector<double>", "pb.suma_vector(x)"), ("py::array_t<double>", "pb.suma_array(x)"), ("np.sum (referencia)", "np.sum(x)")):
    print(f"  {nombre:20s} {ns(s, g) / 1e3:7.2f} µs por llamada")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The reference-run figures rank the boundaries. A Python function that does nothing costs 27 ns per call; the same function in nanobind, 34 ns; in Numba, 158 ns because the dispatcher examines each argument’s type to select a specialization; and in pybind11, 193 ns, about six times nanobind, on the scale of its own benchmark (about 3 times for simple functions, on a different machine and compiler). For kernels taking milliseconds it does not matter; for a function called a million times from a Python loop, that is 0.2 s purely crossing the boundary.

The second part shows the cost that really hurts. Summing 1000 elements received as std::vector<double> cost 49.4 µs per call; with py::array_t, 1.62 µs, thirty times less (and less than np.sum, 3.71 µs, with its own fixed ufunc cost). The std::vector converter traverses the array element by element as a Python sequence: requests each element (a new np.float64), converts it to double and appends it to the vector, about 50 ns per element. This is the difference between types 2 and 3 in the list above.

Crossing the boundary without copying

An array of one million float64 is 8 MB. If every call to your kernel copies it, at around 8 GB/s moved by one core from DRAM (measured in the memory hierarchy lesson), that is about a millisecond of copying; moreover, C++ writes go to the copy, not the array in Python. Good interoperability means both sides read and write the same buffer, which only requires agreeing how to describe it.

The buffer protocol has existed since Python 3.0. An object implementing it can fill an Py_buffer structure with pointer buf, length in bytes, itemsize, an struct-style format string ('d' is double), ndim, shape, strides in bytes, a read-only flag and an obj reference to the owner, kept alive until the consumer releases the buffer. bytes, bytearray, array.array, memoryview, NumPy arrays and PyTorch CPU tensors speak it, and py::array_t and py::buffer use it underneath. This is what we saw from NumPy’s side in inside ndarray: an array is a buffer plus shape and strides, and a view is another description of the same buffer.

The cell makes this explicit in your browser: it creates 48 anonymous bytes, interprets them as six float64 without copying and shows that common NumPy views (transpose, alternating columns) point to the same buffer with different strides.

[ ]The buffer protocol from PythonBrowser
import numpy as np

datos = bytearray(8 * 6)                          # 48 bytes que no sabe nadie que son números
v = np.frombuffer(datos, dtype=np.float64)        # una vista de NumPy sobre ese buffer, sin copiar
v[:] = np.arange(6)
print("bytes 8 a 16 del bytearray:", bytes(datos[8:16]).hex(), "=", np.frombuffer(datos[8:16], dtype=np.float64)[0])
m = memoryview(v)
print(f"memoryview: formato {m.format!r}, itemsize {m.itemsize}, forma {m.shape}, strides {m.strides}, C-contiguo {m.c_contiguous}")
A = np.arange(12.0).reshape(3, 4)
for nombre, x in (("A", A), ("A.T", A.T), ("A[:, ::2]", A[:, ::2])):
    d = x.__array_interface__
    print(f"{nombre:10s} desplazamiento del dato respecto de A: {d['data'][0] - A.__array_interface__['data'][0]:3d} B, "
          f"strides {x.strides}, comparte memoria con A: {np.shares_memory(x, A)}")
c = np.ascontiguousarray(A[:, ::2])
print("np.ascontiguousarray(A[:, ::2]) comparte memoria con A:", np.shares_memory(c, A))

Bytes 8 to 16 of bytearray contain 000000000000f03f: the IEEE 754 1.0 in little-endian order (biased exponent 0x3ff in the high bits), written by NumPy into memory it does not own. And np.ascontiguousarray on a strided view no longer shares memory: to provide a contiguous buffer it must copy.

That last detail decides what happens at the boundary. A C++ kernel written with an for (i...) x[i] loop assumes the array is contiguous and of float64. If the signature requires this and the incoming array does not satisfy it, the converter has three choices: reject it, pass the view unchanged (then the kernel must use strides), or copy it to a compliant buffer. The third is the default in pybind11 and nanobind, with a dangerous consequence: if the kernel writes its result to the argument, it writes to the copy and nothing changes in Python. The cell tests eight signatures with six inputs: each C++ function writes −1 to the first element and returns its received pointer; if it matches the Python array’s pointer, it is a view, and the cell checks that then, and only then, −1 appears in Python.

[ ]Copy or view? Signatures and inputs checkedLocal GPU
import json
import numpy as np
import torch

FIRMAS_PB = r'''
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <vector>
#include <cstdint>
namespace py = pybind11;
using P = std::uintptr_t;
P vec(std::vector<double> v) { v[0] = -1; return reinterpret_cast<P>(v.data()); }
template <class A> P marca(A a) { auto* p = const_cast<typename A::value_type*>(a.data()); p[0] = -1; return reinterpret_cast<P>(p); }
PYBIND11_MODULE(MODNAME, m) {
    m.def("vector", &vec);
    m.def("array_t", &marca<py::array_t<double>>);
    m.def("array_t_c", &marca<py::array_t<double, py::array::c_style | py::array::forcecast>>);
    m.def("array_t_sin_forcecast", &marca<py::array_t<double, py::array::c_style>>);
    m.def("array_t_noconvert", &marca<py::array_t<double>>, py::arg("a").noconvert());
}
'''
FIRMAS_NB = r'''
#include <nanobind/nanobind.h>
#include <nanobind/ndarray.h>
#include <cstdint>
namespace nb = nanobind;
using P = std::uintptr_t;
using Contig = nb::ndarray<double, nb::c_contig, nb::device::cpu>;
using Libre = nb::ndarray<double, nb::device::cpu>;
template <class A> P marca(A a) { a.data()[0] = -1; return reinterpret_cast<P>(a.data()); }
NB_MODULE(MODNAME, m) {
    m.def("ndarray_c", &marca<Contig>);
    m.def("ndarray_c_noconvert", &marca<Contig>, nb::arg("a").noconvert());
    m.def("ndarray_strides", &marca<Libre>);
}
'''
fpb = compilar("firmas_pb", FIRMAS_PB)
fnb = compilar("firmas_nb", FIRMAS_NB, nb=True)
firmas = [("vector", fpb.vector), ("array_t", fpb.array_t), ("array_t_c", fpb.array_t_c),
          ("array_t_sin_forcecast", fpb.array_t_sin_forcecast), ("array_t_noconvert", fpb.array_t_noconvert),
          ("ndarray_c", fnb.ndarray_c), ("ndarray_c_noconvert", fnb.ndarray_c_noconvert), ("ndarray_strides", fnb.ndarray_strides)]

def entradas():
    base = np.arange(1.0, 13.0).reshape(3, 4)
    return {"f64_c": base.copy(), "f64_t": base.copy().T, "f64_salto": base.copy()[:, ::2], "f32_c": base.astype(np.float32),
            "i64_c": np.arange(1, 13).reshape(3, 4), "torch_f64": torch.arange(1.0, 13.0, dtype=torch.float64).reshape(3, 4)}

tabla = {}
print(f"{'firma':22s}" + "".join(f"{k:>12s}" for k in entradas()))
for nombre, f in firmas:
    fila = {}
    for k, x in entradas().items():
        p = x.data_ptr() if isinstance(x, torch.Tensor) else x.ctypes.data
        try:
            q = f(x[0] if nombre == "vector" else x)       # std::vector<double> es 1D: le pasamos la primera fila
            primero = float(x[0, 0])
            fila[k] = "vista" if q == p else "copia"
            assert (primero == -1) == (q == p)       # en una vista, lo que escribe C++ se ve en Python
        except TypeError:
            fila[k] = "error"
    tabla[nombre] = fila
    print(f"{nombre:22s}" + "".join(f"{v:>12s}" for v in fila.values()))
print("\ndatos del interactivo:", json.dumps(tabla))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
InteractiveCopy or view at the boundary?
double f(py::array_t<double, py::array::c_style | py::array::forcecast> a)
Python: a.T (transpose, a view)159261037114812shape (4, 3), strides (8, 32)float64, 8 B per elementmemory buffer (actual byte order)123456789101112✓ type float64 (requires float64)✗ contiguity Fortran (requires C)↑ C++ receives: a copy, 12 contiguous float64 values-159261037114812
Copy: the converter creates a new contiguous float64 array and copies (and converts) the 12 elements. C++ works on that copy. If the function writes its result to the argument, Python will not see it: the error is silent. The usual kernel signature: guarantees a contiguous float64 buffer, copying if needed.
Input
4. C++ writes −1
Measured resultcopy
Bytes copied in this example96 B
With 10⁶ elements8 MB per call
Does Python see −1?no
A 3 × 4 array crosses to C++ with your chosen signature. Above, the array as Python sees it and its buffer in actual byte order; below, what C++ receives. Results are measured in the previous cell. Start with the transpose and the usual kernel signature (c_style | forcecast): play the call and see whether −1 reaches Python. Try the same input with plain py::array_t<double>, with noconvert() and with nanobind. Which signatures accept a PyTorch tensor without copying it?

The cell’s table has more surprises than it first appears:

  • No array signature (py::array_t or nb::ndarray) copies a contiguous float64, and every one that permits conversion copies an float32 or an int64. Converting float32 to float64 inevitably copies (each element’s size changes). std::vector always copies.
  • Plain py::array_t<double> accepts the transpose and strided view without copying: it only requires the type. If your kernel uses a.data()[i] assuming contiguity, these inputs make it read the wrong elements without error. With py::array::c_style it copies; with nb::ndarray without c_contig it passes the view and you must use strides.
  • Without forcecast, pybind11 still converts float32 and int64: the flag only enables conversions NumPy considers unsafe (lossy), and these two are safe.
  • A PyTorch tensor arrives as a view to py::array_t (NumPy converts it via the tensor’s __array__ method, which returns a view of its memory) and to nb::ndarray (via DLPack), but noconvert() in pybind11 rejects it because it is not a NumPy ndarray, whereas nanobind accepts it without copying. std::vector rejects it: for pybind11 a tensor is not a sequence it knows how to convert.
  • noconvert() turns every silent copy into an TypeError. This is what you want in a function that writes to its argument: a call-time error is better than a result that never arrives.

DLPack: the same tensor in NumPy, PyTorch and C++

The buffer protocol knows nothing about GPUs, and its type format is struct’s, without bfloat16 or other deep-learning types. DLPack is the common structure adopted by array frameworks to exchange tensors on any device. Its core is a C structure, DLTensor, with data pointer, device (type and number: CPU, CUDA, ROCm…), number of dimensions, data type (code, bits and lanes), shape, strides in elements, not bytes (or a null pointer, meaning C-contiguous), and a byte offset. It is inside an DLManagedTensor adding a pointer to producer context and an deleter function the consumer calls when it no longer needs the tensor: lifetime management is thus transferred without either side knowing the other.

In Python, an exportable object has two methods: __dlpack_device__() returns the pair (device type, number), and __dlpack__(stream=None) returns a Python capsule containing the DLManagedTensor; the consumer renames the capsule as used so it cannot be consumed twice. np.from_dlpack(x), torch.from_dlpack(x) and equivalent JAX and CuPy functions accept any object with those methods. nanobind speaks DLPack directly: that is why nb::ndarray accepts PyTorch tensors without copying, as in the table. The cell checks both directions between NumPy and PyTorch and what happens with a tensor living on the GPU.

[ ]DLPack and the buffer protocol between NumPy and PyTorchLocal GPU
import numpy as np
import torch

a = np.arange(6.0)
t = torch.from_dlpack(a)                      # NumPy -> PyTorch por DLPack
b = np.from_dlpack(t)                         # y de vuelta
t[0] = 100.0
print("torch.from_dlpack(a) comparte memoria:", t.data_ptr() == a.ctypes.data, "| a[0] =", a[0])
print("np.from_dlpack(t) comparte memoria:   ", np.shares_memory(a, b))
print("torch.from_numpy y Tensor.numpy:       ", np.shares_memory(torch.from_numpy(a).numpy(), a))
m = memoryview(a)                             # el protocolo de buffer (PEP 3118), sin NumPy de por medio
print(f"memoryview: formato {m.format!r}, itemsize {m.itemsize}, forma {m.shape}, strides {m.strides}, solo lectura {m.readonly}")
v = memoryview(np.arange(12.0).reshape(3, 4).T)
print("memoryview de una traspuesta: strides", v.strides, "| C-contiguo:", v.c_contiguous, "| F-contiguo:", v.f_contiguous)
print("t.__dlpack_device__():", t.__dlpack_device__(), "(1 = CPU)")
if torch.cuda.is_available():
    g = torch.arange(6.0, device="cuda")
    print("tensor en la GPU, __dlpack_device__():", g.__dlpack_device__(), "(2 = CUDA, dispositivo 0)")
    try:
        np.from_dlpack(g)
    except Exception as e:
        print("np.from_dlpack(tensor CUDA):", type(e).__name__, "-", str(e)[:90])
    print("copia explícita a la CPU y vista:", np.from_dlpack(g.cpu()).sum())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The output confirms the three properties that matter. torch.from_dlpack and np.from_dlpack share memory in both directions: PyTorch’s t[0] = 100.0 appears in a[0]. Buffer-protocol strides are in bytes, (8, 32) for the transpose, which is Fortran-contiguous, not C-contiguous. A tensor living on the GPU announces its device, (kDLCUDA, 0), and NumPy, which can only read CPU memory, rejects it with BufferError instead of silently copying: crossing GPU to CPU is always an explicit copy, .cpu().

Lab: a zero-copy extension that releases the GIL

Now put the pieces together. The cell’s nanobind extension has a purely computational kernel (kk steps of recurrence v←v2+1−0.5v \leftarrow \sqrt{v^2 + 1} - 0.5 per element; v+1/2=v2+1v + 1/2 = \sqrt{v^2 + 1} gives its fixed point, v∗=3/4v^* = 3/4, and one step from v=1v = 1 gives 2−0.5=0.9142…\sqrt{2} - 0.5 = 0.9142\ldots, printed by the first two lines) in two versions, with and without the GIL. The signature requires a contiguous 1D float64 CPU array and forbids conversion (noconvert()): it either receives the real buffer or fails. First it checks that it receives the same pointer from a NumPy array and a PyTorch tensor and modifies them in place; then it launches 1 to 8 Python threads, each with its own array, and measures total time.

[ ]Lab: zero-copy extension releasing the GILLocal GPU
import time
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import torch

GIL_NB = r'''
#include <nanobind/nanobind.h>
#include <nanobind/ndarray.h>
#include <cmath>
#include <cstdint>
namespace nb = nanobind;
using Vec = nb::ndarray<double, nb::ndim<1>, nb::c_contig, nb::device::cpu>;

static void trabajo(double* x, size_t n, int k) {         // k pasos de una recurrencia por elemento: puro cálculo
    for (size_t i = 0; i < n; ++i) {
        double v = x[i];
        for (int j = 0; j < k; ++j) v = std::sqrt(v * v + 1.0) - 0.5;
        x[i] = v;
    }
}
std::uintptr_t con_gil(Vec a, int k) { trabajo(a.data(), a.shape(0), k); return reinterpret_cast<std::uintptr_t>(a.data()); }
std::uintptr_t sin_gil(Vec a, int k) {
    double* p = a.data(); size_t n = a.shape(0);          // todo lo que toca objetos de Python, antes
    {
        nb::gil_scoped_release suelta;
        trabajo(p, n, k);
    }
    return reinterpret_cast<std::uintptr_t>(p);
}
NB_MODULE(MODNAME, m) {
    m.def("con_gil", &con_gil, nb::arg("a").noconvert(), nb::arg("k"));
    m.def("sin_gil", &sin_gil, nb::arg("a").noconvert(), nb::arg("k"));
}
'''
ext = compilar("gil", GIL_NB, nb=True)

a = np.ones(5); t = torch.ones(5, dtype=torch.float64)
print("NumPy: mismo puntero", ext.sin_gil(a, 1) == a.ctypes.data, "| modificado en su sitio:", a[0])
print("PyTorch (DLPack): mismo puntero", ext.sin_gil(t, 1) == t.data_ptr(), "| modificado en su sitio:", float(t[0]))
try:
    ext.sin_gil(np.ones(5, dtype=np.float32), 1)
except TypeError:
    print("float32 con noconvert(): TypeError, en lugar de una copia silenciosa")

n, k = 200_000, 100
print(f"\n{'hilos':>5s} {'con GIL':>10s} {'sin GIL':>10s}   (cada hilo procesa su propio array de {n} elementos)")
escala = {}
for hilos in (1, 2, 4, 8):
    fila = []
    for f in (ext.con_gil, ext.sin_gil):
        trozos = [np.random.default_rng(h).random(n) for h in range(hilos)]
        mejores = []
        for _ in range(3):
            t0 = time.perf_counter()
            with ThreadPoolExecutor(hilos) as ex:
                list(ex.map(lambda x: f(x, k), trozos))
            mejores.append(time.perf_counter() - t0)
        fila.append(min(mejores))
    escala[hilos] = fila
    print(f"{hilos:5d} {1e3 * fila[0]:8.0f} ms {1e3 * fila[1]:8.0f} ms   aceleración sin GIL: {hilos * escala[1][1] / fila[1]:.1f}x")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Both identity checks pass: the pointer C++ receives is that of the NumPy array and the PyTorch tensor, and both are modified in place with 2−0.5\sqrt{2} - 0.5. The float32 with noconvert() gives TypeError. The thread table is a textbook GIL example. With the GIL, time grows with thread count (181, 316, 643 and 1275 ms for 1, 2, 4 and 8): threads take turns and total work, proportional to threads, is done serially. Without the GIL, time stays flat (153 to 161 ms): eight threads do eight times the work in the same time, a 7.9 speedup with 8 threads. Both versions perform exactly the same computation; the only difference is the three lines of the gil_scoped_release block.

PyTorch extensions in C++

If your data are already PyTorch tensors, the natural route is torch.utils.cpp_extension rather than plain pybind11. It compiles C++ against PyTorch’s tensor library (ATen) and generates pybind11 bindings for you. It has three forms: load_inline accepts code as a string and compiles it with ninja on first call (reusing it later); load does the same with files; and CppExtension or CUDAExtension for setup.py distributes it. Code receives and returns torch::Tensor, checks assumptions with TORCH_CHECK (which throws a readable Python exception), and can use at::parallel_for to distribute a range among PyTorch’s own threads.

The cell fuses relu(a·x + y) in one pass. In ordinary PyTorch there are three operations reading and writing entire arrays (2 * x, + y and relu), with two temporaries: the same array-expression traffic problem studied with NumPy.

[ ]A PyTorch extension with load_inlineLocal GPU
import os, time
from pathlib import Path
import torch
ninja = asegurar("ninja")                        # load_inline compila con ninja
os.environ["PATH"] = os.pathsep.join([ninja.BIN_DIR, str(Path(ninja.__file__).parents[1] / "bin"), os.environ["PATH"]])
from torch.utils.cpp_extension import load_inline

AXPY_RELU = r'''
#include <torch/extension.h>
torch::Tensor axpy_relu(torch::Tensor x, torch::Tensor y, double a) {
    TORCH_CHECK(x.device().is_cpu() && x.scalar_type() == torch::kFloat64 && x.is_contiguous(), "x: float64 contiguo en CPU");
    TORCH_CHECK(y.sizes() == x.sizes() && y.scalar_type() == x.scalar_type() && y.is_contiguous(), "y: como x");
    auto out = torch::empty_like(x);
    const double* px = x.data_ptr<double>(); const double* py = y.data_ptr<double>(); double* po = out.data_ptr<double>();
    at::parallel_for(0, x.numel(), 1 << 14, [&](int64_t b, int64_t e) {    // el pool de hilos de PyTorch
        for (int64_t i = b; i < e; ++i) { const double v = a * px[i] + py[i]; po[i] = v > 0 ? v : 0; }
    });
    return out;
}
'''
torch.set_num_threads(HILOS)                     # los mismos hilos para las dos versiones
t0 = time.perf_counter()
ext_t = load_inline(name="l22_axpy_relu", cpp_sources=AXPY_RELU, functions=["axpy_relu"], build_directory=str(BUILD),
                    extra_cflags=["/O2", "/openmp"] if WIN else ["-O3", "-fopenmp"])   # sin OpenMP, at::parallel_for va en serie
print(f"load_inline: {time.perf_counter() - t0:.1f} s (la segunda vez reutiliza lo compilado)")
x = torch.randn(10**7, dtype=torch.float64); y = torch.randn(10**7, dtype=torch.float64)
print("coincide con torch.relu(2x + y):", torch.equal(ext_t.axpy_relu(x, y, 2.0), torch.relu(2 * x + y)))
def mejor(f, rep=10):
    f(); ts = []
    for _ in range(rep):
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return min(ts)
print(f"fusionado en C++: {1e3 * mejor(lambda: ext_t.axpy_relu(x, y, 2.0)):.1f} ms;  "
      f"tres operaciones de PyTorch: {1e3 * mejor(lambda: torch.relu(2 * x + y)):.1f} ms  ({torch.get_num_threads()} hilos)")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The first call to load_inline took 30 s (PyTorch headers are huge); later ones, finding the library already compiled in the build folder, took under a second. With the same 8 threads, the fused version took 5.1 ms and the three PyTorch operations 13.3 ms, 2.6 times more, for 10710^7 elements. Traffic predicts that ratio: with write-allocate, the fused version moves 32 bytes per element (reads x and y, fetches and writes output) and the three operations 80 (24 for the first, 32 for the second and 24 for the third), a ratio of 2.5.

One hard-to-find detail is useful to know: at::parallel_for distributes work among threads only if the extension is built with OpenMP (/openmp in MSVC, -fopenmp in GCC and Clang). Without the flag it compiles and works, but on one thread: in an initial lab run without it, the fused version was twice as slow as PyTorch (27.7 ms versus 13.7 ms, with PyTorch also using all its threads). This is exactly the unfair comparison of the next section, detected only by asking why a result contradicts the traffic prediction.

A function built this way is invisible to the rest of PyTorch: torch.compile does not know what it does and autograd cannot differentiate it. To make it a first-class operation, register it with TORCH_LIBRARY and provide an implementation per device and, if needed, a derivative; this is custom operator registration in the deep-learning part, and the next step, the CUDA kernel, is covered in the GPU lessons.

Fair comparisons

You now have five ways to execute the same computation. “Which is faster?” seems simple and is where most misleading claims occur, often unintentionally. In 1991 David Bailey published a satire in Supercomputing Review listing the twelve most effective ways to mislead an audience with parallel-computer performance results. All twelve still apply; adapted to your situation:

  1. Give only 32-bit results without saying so and compare them with other systems’ 64-bit results.
  2. Measure an inner kernel and present it as whole-application performance.
  3. Use assembly and low-level constructs without mentioning it.
  4. Scale problem size with processor count without saying so.
  5. Present projected results for a complete system that was not used.
  6. Compare against scalar, unoptimized code on the rival machine (in 1991, Cray systems).
  7. Compare against old code on an obsolete system.
  8. Count the inflated parallel implementation’s flops instead of those of the best sequential implementation.
  9. Give performance as processor utilization, parallel speedup or flops per dollar.
  10. Mutilate the algorithm to fit the architecture, even if solving the problem takes longer.
  11. Measure the parallel version on a dedicated machine and the conventional version on a loaded one.
  12. If all else fails, show pretty pictures and do not discuss performance.

Torsten Hoefler and Roberto Belli wrote the serious version in 2015. They reviewed a stratified sample of 120 papers from three major conferences (ten at random from each edition of HPDC, SC and PPoPP from 2011 to 2014). Of the 95 reporting measurements from real experiments, only 17 included any measure of variation, and of the 39 reporting speedups, 15 (38%) did not give absolute baseline performance. They proposed twelve rules; the most relevant here are:

  • Rule 1. When reporting a speedup, state the baseline (a parallel run with one process or the best serial run) and give its absolute time too. More generally: never give a ratio without absolute values.
  • Rules 3 and 4. Use the arithmetic mean only for costs (times); for rates (flops per second), use the harmonic mean. Do not summarize ratios: summarize their underlying costs or rates and, only if there is no alternative, use the geometric mean.
  • Rules 5 to 8. State whether measurements are deterministic; if not, give confidence intervals, do not assume normality without checking, compare using statistical methods and consider whether mean or median matters (sometimes a high percentile does).
  • Rule 9. Document all varying factors and the full setup: hardware, software, versions, flags.
  • Rule 11. If possible, show an upper performance bound (such as the roofline) so the result can be interpreted.

Lab: the eight-version benchmark

The lab applies the definition to the Lennard-Jones kernel. All versions compute the same N(N−1)N(N-1) interactions (none uses Newton’s third law, which would save half but complicate parallelism), receive the same (N, 3) array and are compared with pure Python. Parallel versions use the same 8 threads (of 32 possible: the reference machine is shared). Array versions (NumPy and PyTorch) traverse rows in blocks of bb rows, and the block is chosen for each: the “best reasonable version” of point 3, with the exploration printed by the cell. The GPU is measured with data already on it and separately with round-trip positions and forces; float32 is different precision and is reported separately, as Bailey’s first point requires. C++ versions are the modules built by hand above; if you prefer the distribution route, package the same main.cpp with the previous section’s scikit-build-core files and import it instead: machine code is the same with the same flags. This is the lesson’s long cell: a few minutes.

[ ]Lab: the eight-version benchmarkLocal GPU
import json, time
import numpy as np
import torch

torch.set_num_threads(HILOS)
torch.backends.cuda.matmul.allow_tf32 = False

def lj_numpy(X, b=None):
    """Por bloques de b filas: los temporales de b x N caben en la L2. B_NP = 2**15 elementos por temporal es el mejor de los probados."""
    n = len(X); b = b or max(1, B_NP // n); F = np.empty_like(X)
    x, y, z = X[:, 0], X[:, 1], X[:, 2]
    for i0 in range(0, n, b):
        i1 = min(i0 + b, n)
        dx = x[i0:i1, None] - x; dy = y[i0:i1, None] - y; dz = z[i0:i1, None] - z
        r2 = dx * dx + dy * dy + dz * dz
        r2[np.arange(i1 - i0), np.arange(i0, i1)] = np.inf          # j = i no cuenta: 1/inf = 0
        inv2 = 1.0 / r2
        s6 = inv2 * inv2 * inv2
        c = 24.0 * inv2 * s6 * (2.0 * s6 - 1.0)
        F[i0:i1, 0] = (c * dx).sum(1); F[i0:i1, 1] = (c * dy).sum(1); F[i0:i1, 2] = (c * dz).sum(1)
    return F

def lj_torch(X, b):
    n = X.shape[0]; F = torch.empty_like(X)
    x, y, z = X[:, 0], X[:, 1], X[:, 2]
    idx = torch.arange(n, device=X.device)
    for i0 in range(0, n, b):
        i1 = min(i0 + b, n)
        dx = x[i0:i1, None] - x; dy = y[i0:i1, None] - y; dz = z[i0:i1, None] - z
        r2 = dx * dx + dy * dy + dz * dz
        r2[idx[: i1 - i0], idx[i0:i1]] = float("inf")
        inv2 = 1.0 / r2
        s6 = inv2 * inv2 * inv2
        c = 24.0 * inv2 * s6 * (2.0 * s6 - 1.0)
        F[i0:i1, 0] = (c * dx).sum(1); F[i0:i1, 1] = (c * dy).sum(1); F[i0:i1, 2] = (c * dz).sum(1)
    return F

def mejor(f, presupuesto=1.0, minrep=3, maxrep=30):
    """Calienta, repite hasta gastar el presupuesto y devuelve (mínimo, mediana) en segundos."""
    f(); ts = []; t_ini = time.perf_counter()
    while len(ts) < minrep or (time.perf_counter() - t_ini < presupuesto and len(ts) < maxrep):
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return min(ts), float(np.median(ts))

# 1. la mejor versión de cada opción: el tamaño de bloque importa mucho, y no es el mismo para NumPy y para PyTorch
X = red(4096); Xt = torch.from_numpy(X)
print("NumPy, N = 4096:  ", ", ".join(f"b={b}: {1e3 * mejor(lambda: lj_numpy(X, b), 0.5, 2, 3)[0]:.0f} ms" for b in (2, 8, 32, 128)))
print("PyTorch, N = 4096:", ", ".join(f"b={b}: {1e3 * mejor(lambda: lj_torch(Xt, b), 0.5, 2, 3)[0]:.0f} ms" for b in (8, 32, 128, 512)))
if torch.cuda.is_available():
    Xg = Xt.cuda()
    print("GPU, N = 4096:    ", ", ".join(f"b={b}: {1e3 * mejor(lambda: (lj_torch(Xg, b), torch.cuda.synchronize()), 0.5, 2, 3)[0]:.0f} ms" for b in (64, 256, 1024)))
    del Xg
B_NP, B_TORCH, B_GPU = 2**15, 2**19, 2**20     # elementos por temporal de b x N: los mejores de los probados en cada caso

# 2. exactitud: todas las versiones contra Python puro
X = red(512); ref = lj_python(X)
cuda = torch.cuda.is_available()
dev = torch.device("cuda" if cuda else "cpu")
versiones = {
    "numpy": lambda X: lj_numpy(X), "numba": lj_numba, "numba_par": lj_numba_par,
    "cpp": lambda X: lj_cpp.fuerzas(X), "cpp_omp": lambda X: lj_cpp_omp.fuerzas(X, HILOS),
    "torch_cpu": lambda X: lj_torch(torch.from_numpy(X), max(1, B_TORCH // len(X))).numpy(),
}
if cuda:
    versiones["torch_gpu"] = lambda X: lj_torch(torch.from_numpy(X).to(dev), max(1, B_GPU // len(X))).cpu().numpy()
    versiones["torch_gpu32"] = lambda X: lj_torch(torch.from_numpy(X).float().to(dev), max(1, B_GPU // len(X))).double().cpu().numpy()
print("error relativo máximo frente a Python (N = 512):",
      ", ".join(f"{k} {np.abs(f(X) - ref).max() / np.abs(ref).max():.0e}" for k, f in versiones.items()))

# 3. tiempos: datos ya en su sitio (la GPU, aparte, también con la ida y vuelta de los datos)
res = {}
for N in (64, 256, 1024, 4096, 16384):
    X = red(N); Xt = torch.from_numpy(X)
    pruebas = {k: (lambda f=f: f(X)) for k, f in versiones.items() if not k.startswith("torch_gpu")}
    if N <= 1024:
        pruebas["python"] = lambda: lj_python(X)
    if cuda:
        bg = max(1, B_GPU // N); Xg = Xt.to(dev); Xg32 = Xg.float()
        def g64(): lj_torch(Xg, bg); torch.cuda.synchronize()
        def g32(): lj_torch(Xg32, bg); torch.cuda.synchronize()
        def gtr(): lj_torch(Xt.to(dev), bg).cpu()
        pruebas.update(torch_gpu=g64, torch_gpu_tr=gtr, torch_gpu32=g32)
    res[N] = {k: mejor(f) for k, f in pruebas.items()}   # todos los mínimos van en la última línea de la salida

# 4. tabla en la mayor N con rendimiento, techo de cómputo y dispersión
A = np.ones((4096, 4096)); pico = 2 * 4096**3 / mejor(lambda: A @ A, 2.0, 3, 5)[0] / 1e9; del A
N = 16384; pares = N * (N - 1)
print(f"\nN = {N}, {pares:.3g} pares, 22 flops por par; pico práctico np.matmul float64: {pico:.0f} GFLOP/s")
print(f"{'versión':14s} {'mínimo':>10s} {'mediana':>10s} {'Gpares/s':>9s} {'GFLOP/s':>8s} {'% pico':>7s} {'vs numba':>9s}")
for k, (tmin, tmed) in res[N].items():
    print(f"{k:14s} {1e3 * tmin:8.1f} ms {1e3 * tmed:8.1f} ms {pares / tmin / 1e9:9.2f} {22 * pares / tmin / 1e9:8.1f} "
          f"{100 * 22 * pares / tmin / 1e9 / pico:6.1f}% {res[N]['numba'][0] / tmin:8.2f}x")
if cuda:   # la versión eager de PyTorch en la GPU: cada una de sus operaciones lee y escribe arrays de b x N
    M = 2**26; a_, b_, c_ = (torch.ones(M, device=dev) for _ in range(3))
    Bg = 12 * M / mejor(lambda: (torch.add(b_, c_, alpha=3.0, out=a_), torch.cuda.synchronize()), 1.0, 5, 20)[0] / 1e9
    del a_, b_, c_; torch.cuda.empty_cache()
    print(f"\nGPU: ancho de banda de la DRAM (triad float32) {Bg:.0f} GB/s; si los 400 B por par de la versión eager en float64 "
          f"fueran todos a la DRAM: {1e3 * 400 * pares / (Bg * 1e9):.0f} ms; medido {1e3 * res[N]['torch_gpu'][0]:.0f} ms "
          f"(temporales de {8 * max(1, B_GPU // N) * N / 2**20:.0f} MiB: parte del tráfico se queda en la L2 de la GPU)")
print("\ndatos del interactivo:", json.dumps({N: {k: round(v[0], 7) for k, v in r.items()} for N, r in res.items()}))

# 5. el roofline de la CPU con las versiones medidas (la figura aparece en tu cuaderno)
import matplotlib.pyplot as plt
from numba import njit, prange
@njit(parallel=True)
def _triad(a, b, c):
    for i in prange(a.size):
        a[i] = b[i] + 3.0 * c[i]
M = 2**25; a_, b_, c_ = np.empty(M), np.ones(M), np.ones(M)     # 256 MiB por array, muy por encima de la L3
B_cpu = 32 * M / mejor(lambda: _triad(a_, b_, c_), 1.0, 5, 20)[0] / 1e9     # GB/s con write-allocate
del a_, b_, c_
I_comp = 22 * pares / (48 * N)     # bucles compilados: de la DRAM solo leen posiciones y escriben fuerzas (48 B por partícula)
I_eager = 22 / 400                 # NumPy y PyTorch eager: 400 B de temporales por par (sirven la L2 o la DRAM)
Is = np.logspace(-2, 4, 200)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.loglog(Is, np.minimum(pico, Is * B_cpu), "k-", lw=2, label=f"techo CPU: min({pico:.0f} GFLOP/s, I·{B_cpu:.0f} GB/s)")
for k in ("numpy", "numba", "numba_par", "cpp", "cpp_omp", "torch_cpu"):
    I = I_eager if k in ("numpy", "torch_cpu") else I_comp
    ax.loglog(I, 22 * pares / res[N][k][0] / 1e9, "o", label=k)
ax.set_xlabel("intensidad aritmética (flops por byte movido)"); ax.set_ylabel("GFLOP/s")
ax.set_title(f"Lennard-Jones, N = {N}"); ax.legend(fontsize=7)
plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Before reading the table, a warning that is part of the result: this cell ran on a machine shared with other processes using CPU and GPU simultaneously, and load was especially high in this run (pure Python took 618 ms with N=1024N = 1024, 590 ns per pair, versus 373 ms in another run of the same cell). The figure below uses this run’s data. What follows relies only on differences large compared with that variation.

  • The best version of each option matters more than the option. With N=4096N = 4096, NumPy took 355 ms with 8-row blocks and 1303 ms with 32-row blocks: a factor of 3.7 from one parameter. PyTorch’s best CPU block is different (128 rows: 131 ms versus 612 with 8), because each operation has more fixed cost and uses multiple threads; the GPU’s differs again (256 rows: 39 ms versus 189 with 64). Comparing NumPy with a poor block against Numba would have inflated Numba’s advantage almost fourfold.
  • All versions compute the same thing. Relative error versus Python is at most 10−1510^{-15} in float64, and 3×10−63 \times 10^{-6} in float32, as expected with 24 mantissa bits: single precision is not the same answer.
  • With N=16384N = 16384, blocked NumPy took 2.95 s; serial Numba, 1.26 s (2.3 times less); Numba with 8 threads, 209 ms; C++ with OpenMP, 141 ms. Parallelizing with 8 threads gave a factor of 6.0 in Numba and 5.5 in C++.
  • Serial Numba and C++ cannot be ranked from these data. C++ had a minimum of 780 ms with N=16384N = 16384 and Numba 1259 ms, but the C++ median was 1391 ms, and with N=4096N = 4096 the order reverses (121 versus 57 ms). Both versions generate similar code (a scalar loop with one division per pair), and variation on a loaded machine exceeds their difference. This is Hoefler and Belli’s rule 7 in action: without a statistical comparison there is no winner.
  • Compared with the ceiling, the best result is modest: 41.9 GFLOP/s with C++ and OpenMP, 15.7% of the practical np.matmul peak in float64 (267 GFLOP/s, all cores). The roofline explains why below.
  • The GPU does not always win. With N≤1024N \le 1024 it takes 0.6 to 1.3 ms barely depending on NN: fixed cost, and with N=64N = 64 it is 111 times slower than C++ with OpenMP. With N=4096N = 4096, the GPU in float64 (13.8 ms) and 8-thread CPU (15.7 ms) tie within noise; with N=16384N = 16384 the CPU won (141 versus 311 ms). In float32, the GPU was fastest from N=4096N = 4096 (6.8 ms and 125 ms), but that is different precision. Data round trips barely change anything in this kernel: O(N)\bigO(N) bytes (about 800 KB with N=16384N = 16384) for O(N2)\bigO(N^2) work, and differences between the table’s two GPU measurements are noise (with N=16384N = 16384 they differ by 134 ms, when copying 800 KB over PCIe costs around a tenth of a millisecond; with N=4096N = 4096 the measurement with copying was even faster). In an O(N)\bigO(N) kernel such as triad, copying would be the same order as computation and decisive.
InteractiveThe speedup ladder
1 µs100 µs10 ms1 s100 sPyTorch GPU13.8 msC++ with OpenMP (8 threads)15.7 msParallel Numba (8 threads)15.9 msNumba njit56.9 msC++ with pybind11120.7 msPyTorch CPU (8 threads)174.3 msBlocked NumPy257.7 msPure Python (extrapolated)9.90 s
Time versus N (log–log scale): crossings indicate changes in the best option.
6425610244096163841 µs10 µs100 µs1 ms10 ms100 ms1 s10 s100 s1000 sparticles N
  • Python
  • NumPy
  • Numba
  • Numba parallel
  • C++
  • C++ OpenMP
  • PyTorch CPU
  • PyTorch GPU
At N = 4096, float64 GPU and C++ OpenMP tie within measurement noise: 13.8 ms versus 15.7 ms.
Particles N
Metric
Your results
Datareference run
Fastest: PyTorch GPU13.8 ms
Pure Python (extrapolated)9.90 s
Maximum speedup versus Python717×
GPU / best CPU0.88× the time
Lennard-Jones kernel time in each version, measured in the lab reference run (minimum of repetitions), on a logarithmic scale. Start at N = 4096 and drop to N = 64: who wins now, and what happens to the GPU? Enable data round trips and float32. The chart below plots time against N: find the crossovers. Paste the last line of your lab into «Tus resultados» to see yours.

The roofline as arbiter

The table’s peak percentages look disappointing: no version exceeds a small fraction of what np.matmul gets from the same CPU. The roofline model explains why, and also what happens to the array versions.

The algorithm is compute-bound. Each pair performs 22 flops and reads 24 bytes of positions that, for N=16384N = 16384 (384 KB of positions), are in L2: arithmetic intensity relative to DRAM is enormous. The ceiling is compute, but not a matmul’s: this kernel has one division per pair, and a CPU division unit has much lower throughput than addition and multiplication units; assembly also showed the loop was not vectorized. Williams, Waterman and Patterson propose precisely this: draw additional ceilings below peak (without SIMD, with the actual instruction mix) to explain the gap.

The array versions turn it into a memory-bound kernel. NumPy and PyTorch in eager mode execute the expression operation by operation, each reading and writing b×Nb \times N temporary arrays. Counting the 22 operations in the body of lj_torch (3 broadcast subtractions that only write, 5 for r2r^2, division, 2 for the power, 5 for the coefficient and 3 products with their 3 row sums) gives 31 reads and 19 writes of 8 bytes per pair: about 400 B per pair in float64, for 22 flops, an intensity of 22/400≈0.05522/400 \approx 0.055 flops per byte, on the order of a dot product. On the GPU, at its measured bandwidth (226 GB/s), that gives the estimate in the output’s last line: 476 ms if all traffic went to DRAM. The measurement was lower, 311 ms, because with 64-row blocks each temporary occupies 8 MiB and GPU L2 serves some traffic; the order of magnitude is nevertheless a memory-bound kernel’s, not the 0.03 s its 5.9×1095.9 \times 10^9 flops would cost at this GPU’s float64 matmul rate (about 0.2 TFLOP/s in the roofline lesson).

The lab cell’s last part plots that roofline in your notebook with your measurements: the CPU ceiling with the np.matmul peak and parallel triad bandwidth, compiled loops on the right (from DRAM they only read positions and write forces, 48 bytes per particle for 22N(N−1)22N(N-1) flops), and eager versions on the left at 22/40022/400 flops per byte. Compiled versions appear far below their compute ceiling because of division and lack of SIMD, and eager versions on the ramp, sometimes even above the DRAM ramp: with blocks fitting in L2, their traffic is served by faster memory with its own higher ceiling.

This is the general case: an array expression with many elementary operations over large temporaries remains at the memory ceiling even if the underlying algorithm has much arithmetic per datum. Compiled loops (Numba, C++) keep everything in registers and read only positions; a hand-written GPU kernel would do the same and be compute-bound, the reason for the GPU lessons.

When the GPU wins. GPU time has a large fixed cost (launching dozens of kernels from Python, synchronization and, for external data, copying) and a per-pair cost that may be lower; the parallel CPU has a small fixed cost. A two-parameter model for each yields the crossover size:

tG(N)=L+a N2,tC(N)=ℓ+c N2t_{\text{G}}(N) = L + a\,N^2, \quad t_{\text{C}}(N) = \ell + c\,N^2
G is the GPU and C the CPU: fixed cost per call plus cost per pair, with L>ℓ≥0L > \ell \ge 0 and a,c>0a, c > 0. There are N(N−1)N(N - 1) pairs, approximately N2N^2 for large NN.
1/4

Using the table’s data: GPU fixed cost is L≈0.8L \approx 0.8 ms (the mean of its times with N=64N = 64 and 256256), and per-pair costs with N=4096N = 4096 are a≈0.82a \approx 0.82 ns on the GPU in float64 and c≈0.94c \approx 0.94 ns in C++ with 8 threads. The formula gives N∗≈2700N^* \approx 2700, but notice how fragile it is: c−a=0.11c - a = 0.11 ns is a 12% difference, on the order of measurement noise, and with N=16384N = 16384 the CPU measured 0.52 ns per pair, below the GPU. When options have similar per-element costs, the crossover is poorly defined and decided by noise and details. In float32, with a≈0.41a \approx 0.41 ns, the difference is clear and N∗≈1200N^* \approx 1200. General lesson: below a few thousand work elements per call, GPU fixed cost dominates; above that, the lower per-element cost wins, depending on how the kernel is written.

Fusion means moving fewer bytes

The roofline also predicts the gain from compiling a kernel already memory-bound. Take triad, ai=bi+q cia_i = b_i + q\,c_i, with 256 MiB arrays. NumPy’s best version (without allocating) makes two passes: np.multiply(c, q, out=tmp) and np.add(b, tmp, out=a). Counting x86 write-allocate (writing a line requires reading it first), the first moves 3 arrays (read c, read and write tmp), the second 4 (read b and tmp, read and write a): 7 arrays, 56 bytes per element. A fused loop moves 4: 32 bytes. If both run at the same memory speed, the speedup must be 56/32=1.7556/32 = 1.75: compilation cannot gain more than the bytes it saves.

[ ]The roofline as arbiter: fusing triadLocal GPU
import numpy as np
from numba import njit, prange

def triad(a, b, c, q):
    for i in prange(a.size):
        a[i] = b[i] + q * c[i]
triad_1 = njit(triad)                          # un hilo, como NumPy
triad_par = njit(parallel=True)(triad)         # HILOS hilos

N = 2**25                                      # 256 MiB por array: muy por encima de la L3
a, b, c = np.empty(N), np.ones(N), np.ones(N); tmp = np.empty(N)
def numpy_dos_pasadas():
    np.multiply(c, 3.0, out=tmp); np.add(b, tmp, out=a)   # la mejor versión de NumPy: sin reservar memoria
t_np = mejor(numpy_dos_pasadas, 1.0, 5, 20)[0]
t_1 = mejor(lambda: triad_1(a, b, c, 3.0), 1.0, 5, 20)[0]
t_p = mejor(lambda: triad_par(a, b, c, 3.0), 1.0, 5, 20)[0]
# bytes con write-allocate: NumPy lee c, escribe tmp (x2), lee b y tmp, escribe a (x2) = 7 arrays de 8 B; fusionado: 4
print(f"NumPy, dos pasadas, 1 hilo:    {1e3 * t_np:5.0f} ms  ({56 * N / t_np / 1e9:4.1f} GB/s con 56 B por elemento)")
print(f"Numba fusionado, 1 hilo:       {1e3 * t_1:5.0f} ms  ({32 * N / t_1 / 1e9:4.1f} GB/s con 32 B por elemento)")
print(f"Numba fusionado, {HILOS} hilos:     {1e3 * t_p:5.0f} ms  ({32 * N / t_p / 1e9:4.1f} GB/s)")
print(f"con un hilo: aceleración medida {t_np / t_1:.2f}x; la que predice el tráfico, 56/32 = 1.75x")
del a, b, c, tmp
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The prediction holds: in the reference run, two-pass NumPy took 152 ms and the single-thread fused Numba loop 85 ms, a ratio of 1.79 versus the 1.75 predicted by traffic. Both run at the same memory speed (12.4 and 12.7 GB/s with actual traffic): neither computes faster, one moves less. With 8 threads the fused loop reached 50.8 GB/s. In another run with far less load, single-thread versions were nearly three times faster (NumPy 54 ms, single-thread Numba 30 ms, 34.5 and 35.3 GB/s, and 89.5 GB/s with 8 threads), but the ratio was exactly the same, 1.79. The methodological lesson: absolute bandwidth depends on concurrent memory traffic from other processes (so your memory hierarchy lesson figures may differ), while the ratio between versions measured at the same time is set by the traffic each moves. With 8 threads the fused loop climbs as far as memory permits, and no compiler can lift it beyond that ceiling. Also consider comparing single-thread NumPy with eight-thread Numba: a “speedup” between 4.5 and 7 depending on machine load, unrelated to compilation.

From diagnosis to decision

With all this, the workflow for accelerating a numerical Python program has five steps, each of which may finish the job:

  1. Profile. A profiler shows where time goes. If the hot function is 60% of the total, Amdahl’s law limits total speedup to 1/0.4=2.51/0.4 = 2.5 even if it becomes infinitely fast: sometimes continuing is not worthwhile.
  2. Classify the bottleneck, as in bottleneck classification: interpreter (many small operations), memory (few large operations on large arrays), compute (much arithmetic per datum), input and output.
  3. Calculate the bound. Algorithmic arithmetic intensity, roofline ceiling and minimum time. If the current implementation is already close, compilation has nothing to gain; otherwise the gap says how much can be gained.
  4. Choose the minimum tool that solves it:
SituationToolWhy
Few large array operations already near the memory ceilingNumPy as iscompilation cannot reduce already mandatory bytes
Array expression with many temporariesNumPy with out= and blocks, or fusion (Numba, torch.compile)excess traffic is the issue; fusion removes it
Loop with dependencies, branches or irregular structures over arrays and scalarsNumba (@njit, prange)removes the interpreter without leaving Python
C++ data structures, existing libraries, fine memory and thread control, a library to distributeC++ with nanobind or pybind11all C++ available, with a cheap boundary if designed well
New operation inside a PyTorch modelPyTorch extension (and operator registration)autograd, torch.compile and devices understand it
Much data parallelism and enough size to amortize launch and copiesGPU, with a non-eager kernelmore bandwidth and flops if the kernel is not memory-bound
  1. Measure fairly and compare with the bound: result, reference and percentage of the ceiling.

For the two motivating examples, step 4 gives different answers. The trailing-stop backtest is a stateful loop over an array: Numba, or C++ if the event engine is already a large codebase (such as the backtesting project’s event engine). AlphaZero search traverses a tree with variable-size nodes and calls a neural network in batches: the tree in C++ with nanobind or Numba, the network in PyTorch on GPU, and a zero-copy boundary between them.

Common mistakes

Exercises

NumericWhen call cost stops mattering
Each call to a NumPy function has a fixed cost of 1 µs and the compiled loop costs 1 ns per element. Beyond what number of elements nn is fixed cost less than 10% of total time? Give the boundary value.
QuizThe first call
A function decorated with @njit takes 1.2 s on its first call and 6 ms on later calls with the same arguments. What explains the difference, and what do you do in a production service frequently starting new processes?
QuizA million calls with std::vector
A pybind11 function with signature double f(const std::vector<double>& v) is called a million times from a Python loop, each time with the same 1000-element NumPy array. What hidden cost does it have and what is the best fix?
QuizWith the GIL released
Inside a nanobind function receiving nb::ndarray<double, nb::c_contig, nb::device::cpu> a, you release the GIL with nb::gil_scoped_release before a long loop. Which statements are true?

More than one answer may be correct.

NumericAveraging rates
You run the same kernel twice, each performing 101110^{11} flops. The first run achieves 50 GFLOP/s and the second 200 GFLOP/s. What is their average performance in GFLOP/s, defined as total flops divided by total time?
NumericCompiling the hot function
The profiler says 80% of your backtest time is in one function. You compile it with Numba and it becomes 100 times faster; the rest is unchanged. What is the program's total speedup?
NumericThe crossover size
For an O(N2)\bigO(N^2) kernel, the GPU has a fixed cost of 1 ms per call and 2 ns per pair; the CPU, 10 µs fixed and 10 ns per pair. With the model t=fijo+coste por pareja⋅N2t = \text{fijo} + \text{coste por pareja}\cdot N^2, above what NN does the GPU win? Give the boundary value (no rounding necessary).
QuizA performance report
A colleague claims: “My C++ kernel with OpenMP is 350 times faster than the Python version.” Setup: Python is a pure double loop measured at N=1024N = 1024 and extrapolated to N=16384N = 16384; C++ uses 32 threads, -O3 -march=native -ffast-math and float32; they report the best of 20 C++ times and one Python run; they do not compare results. What changes are essential for a fair comparison?

More than one answer may be correct.

Code2D convolution with Numba
Implement with Numba the complete 2D convolution of scipy.signal.convolve2d(img, k) (full mode, zero padding): output shape is (H+kh−1)×(W+kw−1)(H + k_h - 1) \times (W + k_w - 1) and out[m,n]=∑a,bimg[m−a,n−b] k[a,b]\text{out}[m, n] = \sum_{a, b} \text{img}[m - a, n - b]\,k[a, b] over valid indices. It must match SciPy up to rounding and be faster on a 512×512512 \times 512 image and 5×55 \times 5 filter (tests call your function once before timing to exclude compilation).
import numpy as np
from numba import njit

@njit
def conv2d(img, k):
  """Convolución 2D completa, como scipy.signal.convolve2d(img, k)."""
  H, W = img.shape
  kh, kw = k.shape
  out = np.zeros((H + kh - 1, W + kw - 1))
  # tu código
  return out
Shift+Enter to run
CodeA view over C++ memory
The C++ class Bloque stores its data in a std::vector<double>. Complete the vista method so it returns a NumPy array viewing that data without copying and keeps the `Bloque` alive while the view exists (and only then). Use compilar from the build-toolchain cell (run it first). The counter vivos() says how many Bloque objects exist; tests use it to detect both access to freed memory and leaks. py::module_local() prevents two extension versions clashing when registering the same class in one process.
FUENTE = r'''
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <vector>
namespace py = pybind11;

static int vivos = 0;                       // cuántos Bloque existen ahora mismo
struct Bloque {
  std::vector<double> datos;
  explicit Bloque(py::ssize_t n) : datos(n, 0.0) { ++vivos; }
  ~Bloque() { --vivos; }
};

PYBIND11_MODULE(MODNAME, m) {
  py::class_<Bloque>(m, "Bloque", py::module_local())
      .def(py::init<py::ssize_t>())
      .def("get", [](const Bloque& b, py::ssize_t i) { return b.datos.at(i); })
      .def("vista", [](Bloque& b) {
          // TODO: una vista sin copia sobre b.datos que mantenga vivo el Bloque
          return py::array_t<double>(b.datos.size(), b.datos.data());
      });
  m.def("vivos", [] { return vivos; });
}
'''
ext = compilar("bloque", FUENTE)
Bloque, vivos = ext.Bloque, ext.vivos
Shift+Enter to run

Summary

Key idea
Compilation gains only what it removes: the interpreter in loops that do not vectorize, temporary bytes in array expressions, copies at the boundary. Measure which is your bottleneck, compare with the roofline bound and choose the minimum tool that removes it.
  • The interpreter spends tens of nanoseconds per operation dispatching bytecode, resolving types and creating objects. Each NumPy call has fixed cost t0t_0 of a few hundred nanoseconds and per-element cost cc below a nanosecond: fixed cost drops below 10% from n∗=9 t0/cn^* = 9\,t_0/c, around ten thousand elements.
  • Numba compiles numerical functions to machine code with LLVM on the first call for each type combination. prange parallelizes, fastmath permits reassociation (and vectorizing reductions when the loop allows), and cache=True saves compilation across processes. What it cannot type fails with TypingError.
  • pybind11 and nanobind expose C++ as Python modules. Wrapped classes and arrays cross without copying; STL containers copy. py::array_t and nb::ndarray silently copy if type or contiguity does not match, except with noconvert(). To run C++ on multiple threads simultaneously, release the GIL.
  • The buffer protocol (strides in bytes, CPU only) and DLPack (strides in elements, any device, with an deleter for lifetime) allow NumPy, PyTorch and C++ to share memory without copying.
  • A fair comparison uses the same algorithm, inputs and freedoms for all options, in their best reasonable versions; excludes and reports compilation; verifies accuracy; provides absolute values with statistic and dispersion; and is interpreted against a bound. Bailey listed twelve ways not to do it in 1991, and Hoefler and Belli twelve rules for doing it in 2015.

What follows connects directly: the next lesson studies threads, processes, the GIL and parallel speedup laws; GPU lessons write the fused kernels you only estimated with the roofline here. Elsewhere, this lesson’s tools accelerate AlphaZero self-play in reinforcement learning, event-by-event backtests in quantitative finance, and custom PyTorch C++ and CUDA operators in deep learning, always starting with profiling in the benchmarking methodology.