Module contents
Lesson 20 of 26Core 105 min

Vectorization in depth: SIMD, memory traffic, recurrences and the BLAS stack

Explore why vectorized code is fast and when it stops being so from the hardware perspective. Building on NumPy's memory model from m00, study SIMD instructions and barriers to their use, memory traffic from expression temporaries, vectorization of seemingly sequential recurrences, and the high-performance GEMM anatomy and BLAS and LAPACK stack beneath NumPy and SciPy.

After this lesson you can

  • Explain SIMD, how many elements AVX2 processes per instruction and what prevents loop vectorization.
  • Predict array-expression cost with the roofline model by counting temporary bytes, and reduce it using out=, in-place operations or fusion.
  • Vectorize linear recurrences with lfilter, cumulative products or associative scans and compare their stability.
  • Describe the loops, packing and microkernel of a Goto-style GEMM and measure performance against peak.
  • Choose the appropriate scipy.linalg routine for matrix structure and control BLAS threads.

Before you start

Motivation: the same calculation at very different speeds

You have four arrays of prices and weights and want aibi+cidia_i b_i + c_i d_i for each ii, then an exponentially weighted moving average (EWMA) of a price series. In a Python loop, every element goes through the interpreter: decoding bytecode, looking up objects, checking types, creating a new float. With NumPy, one compiled loop traverses memory. The first cell measures both in your browser.

[ ]The same calculation, three speedsBrowser
import time
import numpy as np
from scipy.signal import lfilter

def mejor(f, rep=3):
    """Mejor de rep ejecuciones, en segundos: el mínimo es el estimador menos ruidoso."""
    ts = []
    for _ in range(rep):
        t0 = time.perf_counter()
        f()
        ts.append(time.perf_counter() - t0)
    return min(ts)

rng = np.random.default_rng(0)
n = 200_000
a, b, c, d = (rng.random(n) for _ in range(4))
la, lb, lc, ld = (v.tolist() for v in (a, b, c, d))

t_bucle = mejor(lambda: [la[i] * lb[i] + lc[i] * ld[i] for i in range(n)], rep=2)
t_numpy = mejor(lambda: a * b + c * d, rep=10)
print(f"a*b + c*d con n = {n}: bucle {t_bucle * 1e3:.0f} ms, NumPy {t_numpy * 1e3:.2f} ms "
      f"({t_bucle / t_numpy:.0f} veces más rápido)")

precio = 100 * np.exp(np.cumsum(0.01 * rng.standard_normal(n)))   # paseo aleatorio geométrico

def ewma_bucle(x, alfa):
    y = np.empty_like(x)
    y[0] = x[0]
    for t in range(1, len(x)):
        y[t] = (1 - alfa) * y[t - 1] + alfa * x[t]
    return y

def ewma_lfilter(x, alfa):
    # y_t - (1 - alfa) y_{t-1} = alfa x_t, con y_0 = x_0 metido como estado inicial
    y, _ = lfilter([alfa], [1.0, -(1 - alfa)], x[1:], zi=[(1 - alfa) * x[0]])
    return np.concatenate([x[:1], y])

alfa = 0.05
t_rec = mejor(lambda: ewma_bucle(precio, alfa), rep=2)
t_lf = mejor(lambda: ewma_lfilter(precio, alfa), rep=10)
dif = np.max(np.abs(ewma_bucle(precio, alfa) - ewma_lfilter(precio, alfa)))
print(f"EWMA con n = {n}: bucle {t_rec * 1e3:.0f} ms, lfilter {t_lf * 1e3:.2f} ms "
      f"({t_rec / t_lf:.0f} veces), diferencia máxima {dif:.1e}")

In our runs, NumPy computes the expression around 50 times faster than the list comprehension, and lfilter computes EWMA around 100 times faster than the loop with exactly zero difference, because it performs the same operations in the same order. Neither fast version uses multiple cores or SIMD instructions here: the entire gain comes from moving the loop out of the interpreter.

That is the story you already know from NumPy vectorization. This lesson begins where it ends, because “vectorized” does not mean “optimal”, and there are three common ways to waste machine capacity even without Python loops:

  • Expressions with temporaries. a*b + c*d traverses memory three times and creates two intermediate arrays. For large arrays time is governed by bytes moved, not operations, and a fused version moves almost half.
  • Recurrences written as loops. yt=atyt−1+xty_t = a_t y_{t-1} + x_t looks inherently sequential, and the algebraic shortcut that “vectorizes” it overflows float64 after a few thousand steps. Formulations exist that do not overflow and are the same ones used to train linear sequence models in parallel.
  • Vectorized formulas losing precision. The Gram-matrix trick for distances turns a calculation into a very fast matrix product and simultaneously catastrophic subtraction.

Underneath are two layers to understand: SIMD instructions, which perform eight operations in one, and the BLAS and LAPACK stack, what actually executes A @ B or np.linalg.solve. We finish by opening up a high-performance GEMM to see why it approaches CPU peak when almost nothing else does.

Cells python run run in Pyodide in your browser: one thread and NumPy compiled for WebAssembly without SIMD dispatch. Hardware-dependent measurements (multithreaded BLAS, AVX2, DRAM bandwidth) are in the stack section’s local lab on the course laptop: an Intel Core i9-14900HX with 8 performance (P) and 16 efficiency (E) cores, 32 threads, 36 MiB L3 and dual-channel DDR5-5600.

Review: ndarray as a memory access pattern

A NumPy array is a memory block plus a recipe for reading it: the ndarray memory model. Element (i,j)(i, j) of a 2D array is at address

base+i s0+j s1,\text{base} + i\, s_0 + j\, s_1,

where (s0,s1)(s_0, s_1) are strides in bytes. A view changes the recipe, not the data (views versus copies), and broadcasting is a stride of 0: the same datum read many times. In m00 this concerned semantics (do I modify the original?). Here we read it as an access pattern, because memory moves in 64-byte lines rather than elements (cache lines and locality):

  • Stride equal to element size (contiguous): each fetched line carries 8 useful float64s, the prefetcher predicts the next and the loop can load whole registers at once. This is the case everything is designed for.
  • Large stride (x[:, ::2], x.T traversed by rows, a column of a C array): each line provides one or a few useful elements, and in the limit 64 bytes are fetched to use 8. This is the previous lesson’s memory layout.
  • Stride 0 (broadcasting): the value stays in a register. Adding a scalar or row to a matrix costs no extra bandwidth.
  • Advanced indexing (x[[0, 2]], Boolean masks): this is a copy made with indirect accesses rather than a view. It costs one read pass plus one write pass, and the result is contiguous.
[ ]Views and strides as access patternsBrowser
import numpy as np

x = np.arange(12.0).reshape(3, 4)
vistas = {
    "x": x,
    "x.T": x.T,
    "x[:, ::2]": x[:, ::2],
    "broadcast de x[0] a 3x4": np.broadcast_to(x[0], (3, 4)),
    "x[[0, 2]] (indexado avanzado)": x[[0, 2]],
}
for nombre, v in vistas.items():
    print(f"{nombre:30s} forma {str(v.shape):7s} strides {str(v.strides):9s} "
          f"C-contiguo {str(v.flags['C_CONTIGUOUS']):5s} comparte memoria {np.shares_memory(v, x)}")

# mismo número de elementos sumados, distinto número de líneas de caché tocadas
z = np.random.default_rng(1).random(8 * 2**20)            # 64 MiB
m = z.size // 8
t_cont = t_paso = float("inf")
for _ in range(15):                  # rondas intercaladas: el ruido afecta a las dos por igual
    t_cont = min(t_cont, mejor(lambda: z[:m].sum(), rep=1))
    t_paso = min(t_paso, mejor(lambda: z[::8].sum(), rep=1))
print(f"\nsuma de {m} float64: contiguos {t_cont * 1e3:.2f} ms, con paso 8 (uno por línea) "
      f"{t_paso * 1e3:.2f} ms: {t_paso / t_cont:.1f} veces más lento")

The table shows the recipes: x.T swaps strides, x[:, ::2] doubles the second, broadcast has stride 0 in the first dimension, and only advanced indexing does not share memory. Summing 2202^{20} float64s at stride 8 is several times slower than summing as many contiguous float64s (2 to 8 times in our runs depending on machine load). It pays twice: touches 8 times more cache lines and the strided loop cannot load whole registers.

SIMD: one instruction, eight lanes

A modern core does not add one number at a time. It has wide registers and units operating on all their elements at once.

The x86 family has widened registers over time: SSE (128 bits, 1999), AVX (256 bits, 2011), AVX2 (256-bit integers and FMA, 2013), and AVX-512 (512 bits). The i9-14900HX is a hybrid Raptor Lake processor and does not have AVX-512: its E-cores do not implement it and Intel also disabled it on P-cores. That is why NumPy in the local lab reports found: ['X86_V3']: x86-64-v3, grouping AVX, AVX2 and FMA, rather than v4, which is AVX-512.

The key instruction is FMA (fused multiply-add): it computes a⋅b+ca \cdot b + c with one rounding in one step. A P-core of this CPU has two 256-bit FMA units, so every cycle it can perform

2 unidades×8 carriles×2 flops=32 flops en float32(16 en float64).2 \text{ unidades} \times 8 \text{ carriles} \times 2 \text{ flops} = 32 \text{ flops en float32} \quad (16 \text{ en float64}).

E-cores execute each 256-bit instruction split into two 128-bit halves, with half the peak per cycle. That factor of 8 (or 16 counting both units) over scalar addition separates a well-compiled loop from one that is not, and explains why float32 delivers twice float64’s performance when compute-bound.

What prevents vectorization

The compiler vectorizes only if the WW iterations it will merge do not influence one another. There are five usual obstacles.

  1. Dependencies between iterations. If iteration ii needs what i−1i - 1 wrote, lanes cannot work simultaneously. The proposition below makes this precise.
  2. Branches. An if in the loop cannot “jump” in one lane but not another. The solution, if-conversion, computes both branches in all lanes and selects with a mask. It works but discards some work.
  3. Aliasing. If y and x can overlap in memory, writing an y block can change the next x block. C promises this does not happen with restrict; NumPy checks at runtime and, if overlap exists, works on a copy.
  4. Floating-point reductions. Vectorizing s += x[i] requires adding in a different order, and floating-point addition is not associative. A compiler does not do it without explicit permission (-ffast-math); NumPy deliberately reorders because its sum is pairwise summation with blocks of 128 elements and 8 accumulators, which is also more accurate.
  5. Noncontiguous or indirect accesses. Gather instructions load lanes from arbitrary addresses, but are much slower than a contiguous load.

Alignment, a major concern fifteen years ago, matters less: on current x86 cores an unaligned load costs the same as an aligned one unless it crosses a cache line. Contiguity is what matters.

Proof

The vector step covering iterations i0,…,i0+W−1i_0, \dots, i_0 + W - 1 reads ai0,…,ai0+W−1a_{i_0}, \dots, a_{i_0 + W - 1}. In the scalar version, iteration ii reads aia_i after iteration i−di - d may have written it. If W≤dW \le d, every iteration i−di - d with ii in the block satisfies i−d≤i0+W−1−d<i0i - d \le i_0 + W - 1 - d < i_0: it belongs to an earlier step that already wrote. Thus each lane reads exactly the value the scalar version would read, and induction over steps makes everything match. If W>dW > d, iteration i0+di_0 + d is in the same block as i0i_0: the vector version reads old ai0+da_{i_0 + d} and scalar reads what f(ai0,bi0)f(a_{i_0}, b_{i_0}) just wrote. Take f(u,v)=u+vf(u, v) = u + v, all initial aia_i equal to α\alpha, all bib_i equal to β≠0\beta \neq 0, i0=0i_0 = 0 and n>2dn > 2d: scalar writes a2d=α+2βa_{2d} = \alpha + 2\beta and vector α+β\alpha + \beta.

∎

In particular, a first-order recurrence, d=1d = 1, allows no width above 1 as written. It must be reformulated, the subject of the recurrence section.

InteractiveSIMD lanes
x[0:21] in rows of 8 (one row = 32 bytes of float32)00.441−0.922−0.093−0.8540.535−0.046−0.037−0.688−0.4790.1110−0.6111−0.83120.4313−0.05140.59150.7616−0.35170.3818−0.43190.34200.05Scalar instruction: one lanex[20]
for i in range(0, 16, 8):  # 2 iterations of 8 lanes
    y[i:i+8] = sqrt(x[i:i+8]) if x[i:i+8] > t else 0
for i in range(16, 21):  # tail: 5 scalar
    y[i] = sqrt(x[i]) if x[i] > t else 0
  • full vector iteration
  • masked tail
  • scalar iteration
  • false condition: square root computed and discarded
Loop
Registers
21
Tail
0.00
instruction 7 of 7
Loop-body instructions7 (scalar: 21)
Vector · scalar2 · 5
Ideal speedup versus scalar3.00× (max. 8×)
Useful / computed square roots9 / 19 (47 %)
The vector version does not branch: it computes x\sqrt{x} in all 8 lanes and a mask chooses between x\sqrt{x} and 00. 10 of 19 computed roots are discarded.
Each cell is an array element, in rows of 8 (32 bytes of float32). Play execution instruction by instruction. In the initial state, with a branch and n=21n = 21, observe three things: the two complete vector iterations, the 5-element remainder going to a scalar loop, and square roots computed and discarded (crossed out) in lanes where the condition is false. Set the remainder to “Masked”, change nn to 24 and raise the threshold. Finally choose “Dependency”: the loop no longer vectorizes.

The interactive’s model counts loop-body iterations, and ratio n/(iteraciones)n / (\text{iteraciones}) is ideal speedup: at most 88 with 8 lanes, less with a remainder. With a branch, each vector iteration computes square roots in all 8 lanes even though only those satisfying x>tx > t use them: “utilization” falls with the fraction of true conditions. The scalar version wastes no square roots, but pays on each if the risk of branch prediction failure, frequent with random data. The next two cells check the proposition and if-conversion in NumPy.

[ ]Dependencies: when a loop permits lanesBrowser
import numpy as np

def escalar(a, b, d):
    """a[i + d] = a[i] + b[i], un elemento detrás de otro."""
    a = a.copy()
    for i in range(len(a) - d):
        a[i + d] = a[i] + b[i]
    return a

def vectorial(a, b, d, W):
    """El mismo bucle con registros de W carriles: carga W valores, suma y guarda W."""
    a = a.copy()
    for i0 in range(0, len(a) - d, W):
        i1 = min(i0 + W, len(a) - d)
        a[i0 + d:i1 + d] = a[i0:i1] + b[i0:i1]   # se lee el bloque entero antes de escribir
    return a

a0, b0 = np.ones(40), np.arange(1.0, 41.0)
print("distancia d   W = 4    W = 8")
for d in (1, 2, 4, 6, 8, 16):
    ok = [np.array_equal(vectorial(a0, b0, d, W), escalar(a0, b0, d)) for W in (4, 8)]
    print(f"{d:11d}   {str(ok[0]):6s}   {str(ok[1]):6s}")

v = np.ones(8)
v[1:] += v[:-1]                 # parece la recurrencia v[i] += v[i-1] ...
print("\nv[1:] += v[:-1] ->", v)
print("np.cumsum        ->", np.cumsum(np.ones(8)))

The table confirms the proposition: block execution matches scalar exactly when W≤dW \le d. The last two lines show NumPy aliasing. v[1:] += v[:-1] looks like recurrence vi+=vi−1v_i \mathrel{+}= v_{i-1}, but NumPy detects overlapping input and output, reads everything before writing (vector semantics with infinite WW), and gives [1,2,2,… ][1, 2, 2, \dots]. The actual recurrence is np.cumsum, that is, np.add.accumulate, a C loop that does not vectorize by lanes.

[ ]Branches: np.where computes bothBrowser
import numpy as np

x = np.random.default_rng(2).standard_normal(10**6)
with np.errstate(invalid="ignore"):
    rama_si = np.sqrt(x)                                       # np.where necesita la rama entera
    y = np.where(x > 0, rama_si, 0.0)
print(f"sqrt se calculó en los {x.size} elementos: {np.isnan(rama_si).sum()} NaN que np.where descartó")

y1 = np.where(x > 0, np.sqrt(np.abs(x)), 0.0)                 # las dos ramas, sin avisos
y2 = np.sqrt(x, out=np.zeros_like(x), where=x > 0)            # máscara: solo donde x > 0
print("mismo resultado:", np.array_equal(y1, y2))
t1 = mejor(lambda: np.where(x > 0, np.sqrt(np.abs(x)), 0.0), rep=10)
t2 = mejor(lambda: np.sqrt(x, out=np.zeros_like(x), where=x > 0), rep=10)
t3 = mejor(lambda: np.sqrt(np.maximum(x, 0.0)), rep=10)       # sin rama: sqrt(max(x, 0))
print(f"np.where {t1 * 1e3:.2f} ms, where= {t2 * 1e3:.2f} ms, sqrt(maximum(x, 0)) {t3 * 1e3:.2f} ms")

np.where(cond, A, B) is if-conversion: it needs both full arrays A and B, so it computes the square root even where x≤0x \le 0 and produces NaNs from the discarded branch. With your machine’s NumPy those NaNs trigger an invalid-value RuntimeWarning; Pyodide does not deliver the warning because WebAssembly has no floating-point exception flags. The branch is paid for as work. np.sqrt(x, where=...) computes only masked elements, and np.sqrt(np.maximum(x, 0)) removes the branch by transforming data. All three variants take similar time: in such a traversal memory passes, not square roots, dominate.

Memory traffic of an array expression

A NumPy expression is evaluated operation by operation. a*b + c*d is literally:

t1 = np.multiply(a, b)   # lee a y b, escribe t1
t2 = np.multiply(c, d)   # lee c y d, escribe t2
y = np.add(t1, t2)       # lee t1 y t2, escribe y

Each ufunc (ufuncs and reductions) is a full memory traversal, and each intermediate result is a new array of the same size. With n=108n = 10^8 float64s, each occupies 800 MB: no cache retains it between passes.

For a*b + c*d: P=3P = 3 passes, each with rp=2r_p = 2, and v=4v = 4, so Q=9snQ = 9sn versus 5sn5sn. With a chain of kk binary operations over k+1k + 1 distinct variables, the ratio is 3k/(k+2)3k/(k + 2), tending to 3. With a chain over one variable and scalars, such as ((x + 1) * 2 - 3) / 4, it is 2k/2=k2k / 2 = k: the fewer variables and more operations, the greater fusion’s benefit.

Does traffic matter? It depends on arithmetic intensity. a*b + c*d performs 3 flops per element: with temporaries that is 3/72≈0.043/72 \approx 0.04 flops per byte and fused 3/40=0.0753/40 = 0.075. The roofline model says attainable performance is min⁡(π,Iβ)\min(\pi, I \beta), with π\pi compute peak and β\beta bandwidth. This machine’s balance point π/β\pi/\beta is a few flops per byte (measured in the local lab), so the expression lies tens of times below it: time is Q/βQ/\beta and operations are free. Move half the bytes and take half the time.

There are three levers, which should not be confused.

  • out= and in-place operations (np.multiply(a, b, out=t1), t1 += t2): they make the same passes, so modeled traffic does not change. They avoid requesting new memory. The operating system supplies a hundreds-of-MB temporary in new pages, and the first write to each page causes a page fault and zeroing. Reusing buffers saves that cost, fragmentation and peak memory.
  • Fusion: one pass. numexpr evaluates the expression in cache-fitting blocks and with multiple threads; Numba, covered in the compiled extensions lesson, compiles the fused loop; torch.compile does the same with PyTorch graphs (operator fusion). Manually, without compiling, you can fuse by blocks: evaluate the expression in chunks of a few hundred KiB so each chunk’s temporaries stay in L2.
  • Smaller types: if float32 suffices, each pass moves half the bytes and a memory-bound kernel takes half the time. This is the cheapest common error to fix.
InteractiveTemporaries counter
ab×t1cd×t2+t3e−y
t1 = a × b reads 2n, writes 1n
t2 = c × d reads 2n, writes 1n
t3 = t1 + t2 reads 2n, writes 1n
y = t3 − e reads 2n, writes 1n
NumPy: new temporaries9.60 GB · 384 msWith out= (reused buffers)9.60 GB · 384 msFused: one pass4.80 GB · 192 ms
  • bytes read
  • bytes written
  • temporary
  • result
100 M
Type
25
Memory passes (ufuncs)4
With temporaries: reads · writes8n · 4n
Fused: reads · writes5n · 1n
Traffic with temporaries / fused2.00×
New arrays alive at once (peak)3 (2.40 GB)
Enter an array expression. Above, the tree NumPy evaluates: each operation with an array operand is a pass creating a temporary (t1,t2,…t_1, t_2, \dots, in magenta). Below, bytes moved by NumPy, the out= version (same bytes, zero new memory), and fused version, and time predicted by the model with chosen bandwidth. Try 2*a + 3*b (constants do not touch memory), (a - m)/s and sqrt(a*a + b*b) (how many times does the fused version read variable a?). Lower nn until everything fits in L3: the DRAM model stops applying.

The interactive defaults to 25 GB/s, roughly the bandwidth one core achieves traversing large arrays: dot with one thread in the local lab reads 20 to 30 GB/s. Notice the write-allocate switch: when writing a line not in cache, the processor normally reads it first to modify it, so each write costs an extra read. Large copies use non-temporal stores that bypass this, so the one-read and one-write-per-access model, used in the definition and previous lesson’s STREAM kernels, is a useful convention rather than a law. The ratio between strategies is almost always preserved.

[ ]Expression traffic: temporaries, out= and blocksBrowser
import numpy as np

n = 4 * 10**6                       # 32 MB por array float64
rng = np.random.default_rng(3)
a, b, c, d = (rng.random(n) for _ in range(4))
t1, t2, r = np.empty(n), np.empty(n), np.empty(n)
B = 2**14                           # bloque de 128 KiB: cabe en L2
buf = np.empty(B)

def ingenua():
    return a * b + c * d            # dos temporales y un resultado nuevos

def con_out():
    np.multiply(a, b, out=t1)
    np.multiply(c, d, out=t2)
    return np.add(t1, t2, out=t1)   # mismas pasadas, sin pedir memoria

def por_bloques():
    for i in range(0, n, B):
        s = slice(i, i + B)
        m = min(B, n - i)
        np.multiply(a[s], b[s], out=r[s])
        np.multiply(c[s], d[s], out=buf[:m])
        np.add(r[s], buf[:m], out=r[s])   # buf y r[s] siguen en caché
    return r

# ¿memoria o cómputo? El mismo trabajo sobre arrays de 128 KiB, que no salen de la caché
mc = 2**14
sa, sb, sc, sd = (v[:mc].copy() for v in (a, b, c, d))
o1, o2 = np.empty(mc), np.empty(mc)
def en_cache():
    for _ in range(n // mc):
        np.multiply(sa, sb, out=o1)
        np.multiply(sc, sd, out=o2)
        np.add(o1, o2, out=o1)

a32, b32, c32, d32 = (v.astype(np.float32) for v in (a, b, c, d))
def ingenua_f32():
    return a32 * b32 + c32 * d32

ref = ingenua()
assert np.allclose(con_out(), ref) and np.allclose(por_bloques(), ref)
tiempos = {}
for _ in range(6):                  # rondas intercaladas: el ruido afecta a todas por igual
    for f in (ingenua, con_out, por_bloques, en_cache, ingenua_f32):
        tiempos[f.__name__] = min(tiempos.get(f.__name__, 1e9), mejor(f, rep=1))
bytes_modelo = {"ingenua": 9 * 8 * n, "con_out": 9 * 8 * n, "por_bloques": 5 * 8 * n}
for k, Q in bytes_modelo.items():
    print(f"{k:12s} {tiempos[k] * 1e3:6.1f} ms   bytes según el modelo {Q / 1e6:5.0f} MB   "
          f"{Q / tiempos[k] / 1e9:5.2f} GB/s efectivos")
print(f"\nmismas operaciones con los datos en caché: {tiempos['en_cache'] * 1e3:.1f} ms "
      f"({tiempos['en_cache'] / tiempos['con_out']:.0%} del tiempo de con_out)")
print(f"float32: {tiempos['ingenua_f32'] * 1e3:.1f} ms; float64/float32 = "
      f"{tiempos['ingenua'] / tiempos['ingenua_f32']:.2f}")
print("SIMD de este NumPy:", np.show_config(mode="dicts").get("SIMD Extensions", "ninguna"))

In Pyodide figures change considerably across runs and the pattern differs from the model. The out= version barely beats naive: WebAssembly reuses its own heap and there are no new OS pages to pay for. The blocked version gains much less than the 1.8 byte ratio. The cache line explains why: the same work with all data in L2 costs a substantial part of con_out time (between a third and half in our runs). If time is the sum of compute and a memory part proportional to bytes, removing 4 of every 9 bytes shortens only the latter, as observed. This NumPy has no SIMD (last line) and traverses each array with a scalar WebAssembly loop: its compute roof is so low that the expression is no longer clearly memory-bound, and removing bytes helps little. This is roofline working: the byte model predicts time only for a kernel well below its balance point. In the local AVX2 lab the same expression is memory-bound and the model works.

Linear recurrences: vectorizing what looks sequential

The exponentially weighted moving average of a price series,

y0=x0,yt=(1−α) yt−1+α xt,y_0 = x_0, \qquad y_t = (1 - \alpha)\, y_{t-1} + \alpha\, x_t,

is time-series simple exponential smoothing, and a case of the first-order linear recurrence

yt=at yt−1+xt,y_t = a_t\, y_{t-1} + x_t,

with at=1−αa_t = 1 - \alpha and x~t=αxt\tilde x_t = \alpha x_t (and x~0=x0\tilde x_0 = x_0). IIR filters, AR models, and state updates of linear RNNs and state-space models have this form. Dependency distance is 1, so the previous proposition prohibits vectorizing the loop as written. Vectorizing linear recurrences computes the same sequence without a Python loop or lost accuracy, and there are four paths.

1. A compiled linear filter. scipy.signal.lfilter(b, a, x) applies an IIR filter with a C loop. With constant coefficients it is exactly the recurrence: same operations in the same order, which is why the first cell had difference 0 from the loop. It parallelizes nothing but removes the interpreter. It works only if coefficients ata_t are constant.

2. Cumulative products. Unrolling the recurrence, with Pt=∏s=1tasP_t = \prod_{s=1}^{t} a_s,

yt=∑s=0t(∏r=s+1tar)x~s=Pt∑s=0tx~sPs,y_t = \sum_{s=0}^{t} \Big(\prod_{r=s+1}^{t} a_r\Big) \tilde x_s = P_t \sum_{s=0}^{t} \frac{\tilde x_s}{P_s},

which are an cumprod and an cumsum: two vectorized passes. The problem is 1/Ps1/P_s. With constant at=a<1a_t = a < 1, Ps=asP_s = a^s and 1/Ps=a−s1/P_s = a^{-s} grows exponentially: it overflows the largest float64 (1.8×103081.8 \times 10^{308}, with logarithm 709.78709.78) as soon as

s ∣ln⁡a∣>709.78,es decir,s>709.78∣ln⁡a∣.s \,\abs{\ln a} > 709.78, \qquad \text{es decir,} \qquad s > \frac{709.78}{\abs{\ln a}}.

For α=0.5\alpha = 0.5 this is about 1024 steps; for α=0.01\alpha = 0.01, about 70,600. Before overflow there is already a subtler problem: the sum accumulates terms of very different magnitudes.

3. The same trick on a logarithmic scale. With Lt=ln⁡Pt=∑s=1tln⁡asL_t = \ln P_t = \sum_{s=1}^{t} \ln a_s and, if x~s>0\tilde x_s > 0,

yt=exp⁡(Lt+LSE⁡s≤t(ln⁡x~s−Ls)),y_t = \exp\Big(L_t + \operatorname{LSE}_{s \le t}\big(\ln \tilde x_s - L_s\big)\Big),

where LSE⁡\operatorname{LSE} is cumulative log-sum-exp (np.logaddexp.accumulate). Nothing overflows now, but the exponent sums two enormous numbers of opposite sign, Lt≈−t∣ln⁡a∣L_t \approx -t\abs{\ln a} and LSE⁡\operatorname{LSE}, approximately −Lt-L_t, to yield a small result of size ln⁡yt\ln y_t. This is catastrophic cancellation in the exponent: each term has absolute error around u∣Lt∣u\abs{L_t}, with u=2−53u = 2^{-53} unit roundoff, and absolute error δ\delta in the exponent is relative error eδ−1≈δe^{\delta} - 1 \approx \delta in yty_t. Thus

∣y^t−yt∣yt≈u ∣Lt∣≈u t ∣ln⁡a∣,\frac{\abs{\hat y_t - y_t}}{y_t} \approx u\, \abs{L_t} \approx u\, t\, \abs{\ln a},

an error growing linearly with tt (with a larger constant as aa approaches 1, because other rounding errors matter more). With 10610^6 points and α=0.5\alpha = 0.5 it is u⋅6.9×105≈8×10−11u \cdot 6.9 \times 10^5 \approx 8 \times 10^{-11}: five orders of magnitude worse than the recurrence. This is the same issue as the log-space linear recurrence in gated RNNs.

4. An associative scan. The idea is structural rather than algebraic. Each recurrence step is affine function y↦aty+xty \mapsto a_t y + x_t, represented by pair (at,xt)(a_t, x_t). Applying (a1,x1)(a_1, x_1) first and (a2,x2)(a_2, x_2) afterward gives y↦a2(a1y+x1)+x2y \mapsto a_2(a_1 y + x_1) + x_2, that is, the pair

(a1,x1)∘(a2,x2)=(a2a1,  a2x1+x2).(a_1, x_1) \circ (a_2, x_2) = (a_2 a_1,\; a_2 x_1 + x_2).
Proof

Associativity is that of function composition: pair (ai,xi)(a_i, x_i) represents affine map gi(y)=aiy+xig_i(y) = a_i y + x_i, and (a1,x1)∘(a2,x2)(a_1, x_1) \circ (a_2, x_2) represents y↦g2(g1(y))y \mapsto g_2(g_1(y)), “first g1g_1, then g2g_2”. Function composition is associative. It can also be checked by hand: both groupings of three pairs give (a3a2a1,  a3a2x1+a3x2+x3)(a_3 a_2 a_1,\; a_3 a_2 x_1 + a_3 x_2 + x_3). Pair (1,0)(1, 0) is identity. By induction, (At,Xt)(A_t, X_t) is the map “perform steps 0,…,t0, \dots, t”, and evaluated at y−1=0y_{-1} = 0 gives At⋅0+Xt=Xt=ytA_t \cdot 0 + X_t = X_t = y_t. Any associative operator admits m08’s associative-operator scan algorithms with the stated depth.

∎

The easiest scan to vectorize is Hillis–Steele: at level ℓ=1,2,…\ell = 1, 2, \dots, each position t≥k=2ℓ−1t \ge k = 2^{\ell - 1} combines with t−kt - k, all at once:

Xt←AtXt−k+Xt,At←AtAt−k.X_t \leftarrow A_t X_{t-k} + X_t, \qquad A_t \leftarrow A_t A_{t-k}.

After level ℓ\ell, position tt summarizes steps max⁡(0,t−2ℓ+1),…,t\max(0, t - 2^\ell + 1), \dots, t, so after ⌈log⁡2n⌉\lceil\log_2 n\rceil levels everything is final. Each level is one vectorized operation over shifted slices. The price is work: level ℓ\ell performs n−2ℓ−1n - 2^{\ell-1} combinations, n⌈log⁡2n⌉−(2⌈log⁡2n⌉−1)n \lceil \log_2 n\rceil - (2^{\lceil \log_2 n \rceil} - 1) in total, versus the recurrence’s n−1n - 1. Blelloch scan, with an up-sweep and down-sweep over a tree, performs only 2(n−1)2(n - 1) combinations at depth 2log⁡2n2\log_2 n; it is used on GPU, where total work matters.

For EWMA with constant at=aa_t = a, everything is simpler: after level ℓ\ell, At=a2ℓA_t = a^{2^\ell} for every t≥2ℓt \ge 2^\ell, a scalar.

The recurrence in matrix form is (I−aS)y=x~(\mat{I} - a\mat{S})\vb{y} = \tilde{\vb{x}}, so the theorem gives an algorithm: apply the mm factors to x~\tilde{\vb{x}}, each with one instruction, y[k:] += a**k * y[:-k] for k=1,2,4,…k = 1, 2, 4, \dots After factor jj, the weight of x~t−i\tilde x_{t-i} in yty_t is aia^i for every i<2j+1i < 2^{j+1}. Since a2ja^{2^j} becomes tiny quickly, one can stop when nothing changes in float64: with a=0.5a = 0.5 6 passes suffice for a2j<10−17a^{2^j} < 10^{-17}, and with a=0.9999a = 0.9999, 19 (if the series has at least 2182^{18} points). You reconstruct the proof (a one-line telescoping product) in a guided exercise. The key is that only powers ak≤1a^k \le 1 appear: nothing can overflow, and rounding errors are those of a bounded-weight sum.

InteractiveA recurrence as a scan
inputlevel 1level 2level 31.011.822.473.013.423.764.034.27
After level 3, node ii summarizes inputs max⁡(0,i−7),…,i\max(0, i - 7), \dots, i. The first 8 (aquamarine) already equal yiy_i: for example, y7=4.27y_{7} = 4.27.
Relative difference from the sequential recurrence, at=0.900a_t = 0.900 (zeros plotted at 10−1710^{-17})
  • logarithmic trick
  • Hillis–Steele scan
  • prediction u·|L_t|
  • final output
  • partial summary
  • combination at current level
Diagram length
level 3 of 3
0.900
8000
Depth: sequential · scan7 · 3 levels
Combinations ∘ through this level17 (sequential: 7)
Outputs already final8 of 8
Logarithmic trick: first non-finite t…
Trick error immediately before…
Maximum scan error…
Above, Hillis–Steele scan on pairs (at,xt)(a_t, x_t): advance level by level and watch each diagonal arrow combine two summaries and how, after level ℓ\ell, the first 2ℓ2^\ell outputs are final (aquamarine). Depth falls from n−1n - 1 chained steps to log⁡2n\log_2 n levels. Below, computed live in float64 with constant at=aa_t = a and positive prices: relative difference between trick yt=eLt∑sxse−Lsy_t = e^{L_t}\sum_s x_s e^{-L_s} and the recurrence grows with tt, following prediction u∣Lt∣u\abs{L_t}, until e−Lte^{-L_t} overflows (vertical line). The scan remains at rounding level. Lower aa toward 0.5 and watch overflow approach.

The next cell compares the four methods on the first cell’s price-series EWMA.

[ ]Four ways to compute an EWMABrowser
import numpy as np

def ewma_cumprod(x, alfa):
    """y_t = a^t [x_0 + sum_s alfa x_s / a^s]: productos acumulados sin proteger."""
    a = 1 - alfa
    xt = alfa * x
    xt[0] = x[0]
    P = a ** np.arange(len(x))
    with np.errstate(all="ignore"):
        return P * np.cumsum(xt / P)

def ewma_log(x, alfa):
    """El mismo truco en escala logarítmica, con logaddexp.accumulate (x > 0)."""
    a = 1 - alfa
    xt = alfa * x
    xt[0] = x[0]
    L = np.arange(len(x)) * np.log(a)                         # log a^t
    return np.exp(L + np.logaddexp.accumulate(np.log(xt) - L))

def ewma_duplicando(x, alfa, tol=1e-17):
    """Scan por duplicación: tras la pasada j, y_t acumula los pesos a^k con k < 2^(j+1)."""
    a = 1 - alfa
    y = alfa * x
    y[0] = x[0]
    k, w = 1, a                                               # w = a^k
    while k < len(y) and w > tol:
        y[k:] += w * y[:-k]                                   # el lado derecho se evalúa antes
        k, w = 2 * k, w * w
    return y

n = 200_000
x = precio[:n]
print(f"{'alfa':>6s} {'método':>12s} {'error relativo máx.':>20s} {'primer no finito':>17s} {'tiempo':>9s}")
for alfa in (1e-4, 0.01, 0.1, 0.5):
    ref = ewma_bucle(x, alfa) if alfa == 0.01 else ewma_lfilter(x, alfa)
    for nombre, f in (("lfilter", ewma_lfilter), ("cumprod", ewma_cumprod),
                      ("log", ewma_log), ("duplicando", ewma_duplicando)):
        t = mejor(lambda: f(x, alfa), rep=3)
        y = f(x, alfa)
        malos = np.flatnonzero(~np.isfinite(y))
        err = np.max(np.abs(y - ref) / ref) if malos.size == 0 else np.nan
        print(f"{alfa:6g} {nombre:>12s} {err:20.1e} {(malos[0] if malos.size else '-'):>17} {t * 1e3:7.1f} ms")

Results match the analysis. lfilter matches the recurrence to the last bit. Cumulative products work with α=10−4\alpha = 10^{-4} because a−t=0.9999−200000≈5×108a^{-t} = 0.9999^{-200000} \approx 5 \times 10^{8} does not overflow, but give nonfinite values from t=70299t = 70299, 66886688 and 10181018 for α=0.01\alpha = 0.01, 0.10.1 and 0.50.5: a few steps before 709.78/∣ln⁡a∣709.78/\abs{\ln a} (70 625, 6 737 and 1 024), because prices are around 100 and the cumulative sum exceeds 1.8×103081.8 \times 10^{308} somewhat before a−ta^{-t}. The log version never overflows, but its error grows with ∣Lt∣\abs{L_t}, which at the series end is 2×105∣ln⁡a∣2 \times 10^5 \abs{\ln a}: 1.8×10−121.8 \times 10^{-12}, 1.1×10−111.1 \times 10^{-11} and 3.9×10−113.9 \times 10^{-11}, versus u∣Lt∣≈2×10−13u\abs{L_t} \approx 2 \times 10^{-13}, 2×10−122 \times 10^{-12} and 1.5×10−111.5 \times 10^{-11}. Doubling scan remains at 10−1510^{-15} except with α=10−4\alpha = 10^{-4}, where weights are close to 1 and its 18 passes accumulate rounding to 2.4×10−132.4 \times 10^{-13}, and in Pyodide it is faster than cumulative products and the log trick.

With variable coefficients, as in gated linear RNNs, lfilter no longer works and scan is the tool. The cell uses gates at=σ(zt)∈(0,1)a_t = \sigma(z_t) \in (0, 1) with zt∼N(2,1)z_t \sim \Normal(2, 1).

[ ]An associative scan with variable coefficientsBrowser
import numpy as np

def scan_afin(A, X):
    """Hillis-Steele sobre pares (a, x): devuelve los y_t de y_t = a_t y_{t-1} + x_t con y_{-1} = 0."""
    A, X = A.astype(float), X.astype(float)
    k, pasadas = 1, 0
    while k < len(X):
        X[k:] = A[k:] * X[:-k] + X[k:]      # (A_izq, X_izq) ∘ (A, X) = (A·A_izq, A·X_izq + X)
        A[k:] = A[k:] * A[:-k]
        k, pasadas = 2 * k, pasadas + 1
    return X, pasadas

def recurrencia(A, X):
    y, out = 0.0, np.empty(len(X))
    for t in range(len(X)):
        y = A[t] * y + X[t]
        out[t] = y
    return out

rng = np.random.default_rng(4)
T = 50_000
A = 1 / (1 + np.exp(-rng.normal(2.0, 1.0, T)))      # puertas en (0, 1), como en una RNN lineal
X = rng.standard_normal(T)
y_ref = recurrencia(A, X)
y_scan, pasadas = scan_afin(A, X)
print(f"T = {T}: {pasadas} pasadas, error máximo del scan {np.max(np.abs(y_scan - y_ref)):.1e}")
print(f"tiempo: recurrencia {mejor(lambda: recurrencia(A, X), 1) * 1e3:.0f} ms, "
      f"scan {mejor(lambda: scan_afin(A, X), 3) * 1e3:.1f} ms")

# el truco logarítmico con a_t variables: y_t = e^{L_t} sum_s x_s e^{-L_s}, L_t = sum log a_s
L = np.cumsum(np.log(A))
with np.errstate(all="ignore"):
    y_log = np.exp(L) * np.cumsum(X * np.exp(-L))
malos = np.flatnonzero(~np.isfinite(y_log))
print(f"truco logarítmico: L_t baja hasta {L[-1]:.0f}; primer valor no finito en t = {malos[0]}, "
      f"donde L_t = {L[malos[0]]:.1f}")
bien = np.arange(malos[0])
err = np.abs(y_log[bien] - y_ref[bien]) / np.maximum(np.abs(y_ref[bien]), 1e-300)
print(f"antes de romperse, error relativo mediano {np.median(err[:100]):.1e} en t < 100 "
      f"y {np.median(err[-100:]):.1e} justo antes")

The scan needs 16 passes for T=50000T = 50000 and matches the recurrence to 3×10−153 \times 10^{-15}. Even with extra work nlog⁡2nn\log_2 n, in Pyodide it is clearly faster than the loop (1.7 to 3 times in our runs), because each pass is vectorized. The log trick breaks at t=3864t = 3864, just when LtL_t crosses −709.7-709.7: e−Lte^{-L_t} overflows. Before breaking, error rises from 5×10−165 \times 10^{-16} at the start to 4.6×10−144.6 \times 10^{-14} at the end, order u∣Lt∣≈7.9×10−14u\abs{L_t} \approx 7.9 \times 10^{-14} predicted by the analysis.

Vectorizing without losing accuracy: pairwise distances

To calculate distances between nn points xi\vb{x}_i and mm points yj\vb{y}_j in Rd\R^d, the direct broadcasting form, ((X[:, None] - Y[None]) ** 2).sum(-1), creates a temporary of n×m×dn \times m \times d elements. The fast form uses

∥x−y∥2=∥x∥2+∥y∥2−2 x⊤y,\norm{\vb{x} - \vb{y}}^2 = \norm{\vb{x}}^2 + \norm{\vb{y}}^2 - 2\,\vb{x}\T\vb{y},

with which the whole matrix is two norm vectors plus a matrix product, −2XY⊤-2\mat{X}\mat{Y}\T: a GEMM, the fastest operation in the stack, as you will soon see. This is what scikit-learn and almost all implementations of kk neighbors or kk-means do.

The price is subtraction. If x\vb{x} and y\vb{y} are close to each other but far from the origin, ∥x∥2+∥y∥2\norm{\vb{x}}^2 + \norm{\vb{y}}^2 and 2x⊤y2\vb{x}\T\vb{y} are two nearly equal large numbers. Each is computed with error around u(∥x∥2+∥y∥2)u(\norm{\vb{x}}^2 + \norm{\vb{y}}^2) (plus a factor of order dd in the worst case), and subtraction retains that entire error:

∣d2^−d2∣d2≲c u ∥x∥2+∥y∥2∥x−y∥2.\frac{\abs{\widehat{d^2} - d^2}}{d^2} \lesssim c\, u\, \frac{\norm{\vb{x}}^2 + \norm{\vb{y}}^2}{\norm{\vb{x} - \vb{y}}^2}.

When the ratio exceeds 1/u1/u, the result is noise and may be negative: square root returns NaN. The sklearn.metrics.pairwise.euclidean_distances documentation warns that the formula may suffer catastrophic cancellation and is therefore not the most accurate way to compute it.

[ ]Pairwise distances and cancellationBrowser
import numpy as np
from scipy.spatial.distance import cdist

def dist2_gram(X, Y):
    """||x||^2 + ||y||^2 - 2 x·y: un GEMM y dos sumas."""
    return (X * X).sum(1)[:, None] + (Y * Y).sum(1)[None, :] - 2 * X @ Y.T

rng = np.random.default_rng(5)
print(f"{'desplazamiento':>14s} {'negativas':>9s} {'mínimo':>10s} {'error rel. mediano':>19s} {'centrado':>9s}")
for off in (0.0, 1e2, 1e4, 1e6):
    X = rng.standard_normal((300, 3)) + off
    Y = X[:200] + 1e-3 * rng.standard_normal((200, 3))      # vecinos muy cercanos
    D = dist2_gram(X, Y)
    ref = cdist(X, Y, "sqeuclidean")                          # diferencias directas
    i = np.arange(200)
    rel = np.abs(D[i, i] - ref[i, i]) / ref[i, i]
    mu = X.mean(0)
    Dc = dist2_gram(X - mu, Y - mu)
    relc = np.abs(Dc[i, i] - ref[i, i]) / ref[i, i]
    print(f"{off:14g} {np.sum(D < 0):9d} {D.min():10.1e} {np.median(rel):19.1e} {np.median(relc):9.1e}")

With points near the origin, the Gram formula has relative error 10−1010^{-10} on these very small distances (d2≈3×10−6d^2 \approx 3 \times 10^{-6} versus ∥x∥2≈3\norm{\vb{x}}^2 \approx 3): the bound’s ratio is about 2×1062 \times 10^6 and multiplying by uu gives 2×10−102 \times 10^{-10}. Each 100-fold offset multiplies the ratio and error by 10410^4: 10−610^{-6} with 100100, 2×10−22 \times 10^{-2} with 10410^4 and pure noise with 10610^6, including 19 negative distances. Centering brings error back to 10−1010^{-10} in every case.

Corrections, from cheapest to most expensive:

  • Clip at 0 (np.maximum(D, 0)) avoids NaNs but does not fix small values, still noise. scikit-learn always does this and also zeros the diagonal when X\mat{X} is Y\mat{Y}.
  • Center data by subtracting the mean before GEMM. Distances do not change and norms become of order data dispersion. It is free and, as the last column shows, restores almost all accuracy.
  • Accumulate in higher precision: scikit-learn computes in float64 blocks for float32 data because in float32 the problem appears at much smaller offsets.
  • Recompute directly distances below a relative threshold with explicit differences, or use scipy.spatial.distance.cdist, which always works with differences.

Anatomy of a high-performance GEMM

Matrix multiplication C+=AB\mat{C} \mathrel{+}= \mat{A}\mat{B} (GEMM, general matrix multiply) with A∈Rm×k\mat{A} \in \R^{m \times k} and B∈Rk×n\mat{B} \in \R^{k \times n} performs 2mnk2mnk flops on mk+kn+2mnmk + kn + 2mn data. With m=n=k=Nm = n = k = N, ideal intensity is on the order of NN flops per datum: unlike everything above, it can be compute-bound. Achieving that depends on reusing each datum many times while near compute units, and the previous lesson showed the principle with tiling. Real libraries apply it to every hierarchy level at once.

Each piece addresses a specific problem.

  • The microkernel keeps an mr×nrm_r \times n_r tile of C\mat{C} in registers for kck_c steps. At each pp step it loads a column of A~\tilde{\mat{A}} (mrm_r numbers, broadcast individually to a register) and a row of B~\tilde{\mat{B}} (nrn_r numbers, nr/Wn_r/W registers), and performs mrnr/Wm_r n_r / W FMA instructions: a rank-1 update. Data are reused nrn_r and mrm_r times without leaving registers.
  • Why 6×166 \times 16 in float32 with AVX2. Accumulators occupy mrnr/Wm_r n_r / W registers, the row of B~\tilde{\mat{B}} another nr/Wn_r / W, and broadcast of A~\tilde{\mat{A}} at least one, with only 16 available. An FMA also takes around 4 cycles to produce its result and two issue per cycle, so at least 4×2=84 \times 2 = 8 independent FMAs must be in flight to keep units busy (Little’s law: concurrency = latency × throughput). This is the analytic criterion of Low et al. (2016): mrnr/W≥m_r n_r / W \ge latency × units. BLIS kernels for Haswell, the generation introducing AVX2 and FMA, are exactly 6×166 \times 16 in float32 and 6×86 \times 8 in float64.
  • Packing copies blocks into contiguous buffers in exactly the order the microkernel reads them. It costs one data pass but turns strided accesses to a large matrix into contiguous, aligned traversals without associativity conflicts or TLB misses, amortized by subsequent reuse.
  • kck_c sets how long each C\mat{C} tile stays in registers: the larger it is, the more loading and storing C\mat{C} is amortized. Its limit is fitting the B~\tilde{\mat{B}} micro-panel, kc×nrk_c \times n_r, into L1 along with circulating data. mcm_c makes A~\tilde{\mat{A}} fit L2 and ncn_c makes B~\tilde{\mat{B}} fit L3. Goto’s central observation was that the A\mat{A} block should live in L2, not L1, which is too small.
Proof

B\mat{B} is read only during packing, and each block (pc,jc)(p_c, j_c) is packed once because the two outer loops visit each pair once. A\mat{A} is packed inside loop 3, executed for each pair (jc,pc)(j_c, p_c): block (ic,pc)(i_c, p_c) of A\mat{A} is packed once per jcj_c, or ⌈n/nc⌉\lceil n/n_c \rceil times. Each C\mat{C} tile is loaded into registers and stored once per corresponding microkernel execution, occurring once per pcp_c: ⌈k/kc⌉\lceil k/k_c \rceil times. Everything else is read from packed buffers, assumed cached.

∎

The “Goto in miniature” cell below implements the five loops with packing and counts reads: they match the proposition. With N=4096N = 4096 in float32 and the interactive’s block rules, C\mat{C} is reread 11 times, yet intensity is about 85 flops per byte, far above balance: GEMM is compute-bound, the desired result.

InteractiveHigh-performance GEMM loops
A (4096 × 4096)B (4096 × 4096)Cjc = 0 · pc = 2 · ic = 1jr = 0 · ir = 0C has been read and written3 of 11 times
Microkernel 6×166 \times 16: for p=0,…,383p = 0, \dots, 383, cij+=a~ip b~pjc_{ij} \mathrel{+}= \tilde a_{ip}\,\tilde b_{pj}. Each box is a ymm register of 8 float32 values: at each pp, one FMA per C\mat{C} box.
  • B~\tilde{\mat{B}} packed: L3
  • A~\tilde{\mat{A}} packed: L2
  • micro-panel of B~\tilde{\mat{B}}: L1
  • C tile: registers (darker means more accumulated passes)
Model block rules: the B~\tilde{\mat{B}} micro-panel occupies half of L1, A~\tilde{\mat{A}} half of L2 and B~\tilde{\mat{B}} half of L3.
Loop to advance
pc = 0 of 11
Type (microkernel)
48
2048
36
4096
Blocks kc⋅mc⋅nck_c \cdot m_c \cdot n_c384 · 678 · 12288
B~\tilde{\mat{B}} (kc×nck_c \times n_c) in L318.0 MiB of 36 MiB
A~\tilde{\mat{A}} (mc×kcm_c \times k_c) in L21017 KiB of 2.00 MiB
Micro-panel of B~\tilde{\mat{B}} (kc×nrk_c \times n_r) in L124.0 KiB of 48 KiB
Memory accesses per elementA 1 · B 1 · C 11 + 11
Intensity: this scheme · ideal85 · 512 flop/B
Microkernel ymm registers15 of 16
B\mat{B} above, A\mat{A} on the left and C\mat{C} lower right, to scale. Choose a loop to advance and play it: loop 4 shows each kk slice packing a new B~\tilde{\mat{B}} panel (aquamarine, L3) and C\mat{C} darkening as it receives another contribution, meaning another read and write; loop 3 shows A~\tilde{\mat{A}} blocks (orange, L2); loops 2 and 1 show the L1 micro-panel (purple) and register tile (magenta). Below is the microkernel with its registers. Shrink L1 or L2 and see kck_c and mcm_c fall and rereads of C\mat{C} rise.

The interactive’s size rules are an explicit simplified model: the B~\tilde{\mat{B}} micro-panel occupies half L1, A~\tilde{\mat{A}} half L2 and B~\tilde{\mat{B}} half L3. With 48 KiB L1, 2 MiB L2 and 36 MiB L3 in float32 this gives kc=384k_c = 384, mc=678m_c = 678 and nc=12288n_c = 12288. Real libraries tune more finely (associativity, TLB, L3 sharing between cores and loop 3 or 5 distributed among threads), but this is the structure, and Low et al.’s analytic model reproduces sizes formerly found by blind search using rules like these.

[ ]Goto in miniature: five loops with packingBrowser
import numpy as np

def gemm_goto(A, B, mc, kc, nc, mr, nr):
    """C = A B con los bucles de Goto y BLIS. Cuenta las lecturas de A, B y C en 'memoria principal'."""
    m, k = A.shape
    n = B.shape[1]
    C = np.zeros((m, n))
    lect = {"A": 0, "B": 0, "C": 0}
    for jc in range(0, n, nc):                          # bucle 5: panel de columnas de B y C
        for pc in range(0, k, kc):                      # bucle 4: rebanada de k
            Bp = B[pc:pc + kc, jc:jc + nc].copy()       # empaquetar B~ (kc x nc): vive en L3
            lect["B"] += Bp.size
            for ic in range(0, m, mc):                  # bucle 3: bloque de filas de A
                Ap = A[ic:ic + mc, pc:pc + kc].copy()   # empaquetar A~ (mc x kc): vive en L2
                lect["A"] += Ap.size
                for jr in range(0, Bp.shape[1], nr):    # bucle 2: microtira de B~ (kc x nr): L1
                    for ir in range(0, Ap.shape[0], mr):    # bucle 1: microtira de A~ (mr x kc)
                        c = C[ic + ir:ic + ir + mr, jc + jr:jc + jr + nr]
                        lect["C"] += c.size
                        acc = c.copy()                  # la tesela de C, en registros
                        a, bb = Ap[ir:ir + mr], Bp[:, jr:jr + nr]
                        for p in range(a.shape[1]):     # micronúcleo: kc actualizaciones de rango 1
                            acc += np.outer(a[:, p], bb[p])
                        C[ic + ir:ic + ir + mr, jc + jr:jc + jr + nr] = acc
    return C, lect

rng = np.random.default_rng(6)
m = n = k = 96
A, B = rng.standard_normal((m, k)), rng.standard_normal((k, n))
mc, kc, nc, mr, nr = 24, 32, 48, 6, 8
C, lect = gemm_goto(A, B, mc, kc, nc, mr, nr)
print("error frente a A @ B:", np.max(np.abs(C - A @ B)))
cd = lambda p, q: -(-p // q)
pred = {"A": m * k * cd(n, nc), "B": k * n, "C": m * n * cd(k, kc)}
for M in "ABC":
    print(f"{M}: {lect[M]} lecturas = {lect[M] / (A.size if M == 'A' else B.size if M == 'B' else C.size):.0f} "
          f"por elemento (modelo: {pred[M]})")

BLIS (Van Zee and van de Geijn, 2015) went further: it wrote the five loops and packing in portable C, leaving the microkernel as the only architecture-specific assembly piece. Porting a complete level-3 BLAS to a new processor thus reduces to writing dozens of assembly lines and choosing five numbers.

The stack: BLAS, LAPACK and what lies beneath NumPy

When you write A @ B or np.linalg.solve(A, b), NumPy does not multiply or factor anything itself: it calls a BLAS or LAPACK library.

The division into levels is by arithmetic intensity. In float64:

LevelOperationFlopsBytes (each datum once)Intensity
1dot de longitud nn2n2n16n16n1/81/8
2gemv n×nn \times n2n22n^28n28n^21/41/4
3gemm n×nn \times n2n32n^324n224n^2n/12n/12

Levels 1 and 2 remain in the roofline’s memory region at any size: multiplying threads helps only while one core cannot saturate bandwidth alone. Only level 3 has enough intensity to approach peak, so LAPACK is written to send it almost all work: blocked LU (getrf) performs almost all 2n3/32n^3/3 flops (flop count) in calls to gemm and trsm.

The local lab inspects the installed stack, measures all three levels with one and all threads, compares strategies for a*b + c*d and solve routines. It measures the minimum of interleaved repetitions, as in m00’s benchmarking methodology: the laptop is shared and exact numbers change between runs, so focus on ratios. At the end of the second part it plots all three levels on a roofline with roofs measured in the cell. numexpr does not come with NumPy: if installed (pip install numexpr), the cell measures it; otherwise Numba, studied in lesson 22, represents fusion.

[ ]Inside the BLAS and LAPACK stackLocal GPU
import time
import numpy as np
import scipy
import scipy.linalg as sla
import matplotlib.pyplot as plt
from threadpoolctl import threadpool_info, threadpool_limits

def mejor(f, rep=5):
    ts = []
    for _ in range(rep):
        t0 = time.perf_counter()
        f()
        ts.append(time.perf_counter() - t0)
    return min(ts)

def carrera(fs, rondas=5):
    """Mínimo de cada función en rondas intercaladas: el ruido de la máquina afecta a todas por igual."""
    T = {k: float("inf") for k in fs}
    for _ in range(rondas):
        for k, f in fs.items():
            T[k] = min(T[k], mejor(f, 1))
    return T

rng = np.random.default_rng(0)

# 1. Qué hay debajo de NumPy y SciPy
cfg = np.show_config(mode="dicts")
print(f"NumPy {np.__version__}, SciPy {scipy.__version__}")
print("BLAS de NumPy:", cfg["Build Dependencies"]["blas"]["name"], "| SIMD:", cfg["SIMD Extensions"])
for lib in threadpool_info():
    print(f"  {lib['user_api']}: {lib['internal_api']} {lib['version']}, núcleos {lib.get('architecture')}, "
          f"{lib['num_threads']} hilos, {lib['filepath'].split('site-packages')[-1]}")
H = threadpool_info()[0]["num_threads"]

# 2. Los niveles de BLAS en GFLOP/s, con 1 hilo y con todos
casos = [
    ("dot    n = 10^7", lambda: (rng.random(10**7), rng.random(10**7)), 2 * 10**7, 16 * 10**7),
    ("gemv   n = 4096", lambda: (rng.random((4096, 4096)), rng.random(4096)), 2 * 4096**2, 8 * 4096**2),
    ("gemm   n = 256", lambda: (rng.random((256, 256)), rng.random((256, 256))), 2 * 256**3, 3 * 8 * 256**2),
    ("gemm   n = 1024", lambda: (rng.random((1024, 1024)), rng.random((1024, 1024))), 2 * 1024**3, 3 * 8 * 1024**2),
    ("gemm   n = 4096", lambda: (rng.random((4096, 4096)), rng.random((4096, 4096))), 2 * 4096**3, 3 * 8 * 4096**2),
]
print("\nfloat64            I (flop/B)   GFLOP/s 1 hilo   GFLOP/s todos   GB/s todos")
puntos = []
for nombre, prep, flops, byts in casos:
    X, Y = prep()
    g = []
    for h in (1, H):
        with threadpool_limits(h, user_api="blas"):
            X @ Y
            g.append(flops / mejor(lambda: X @ Y, 3) / 1e9)
    print(f"{nombre:18s} {flops / byts:10.2f} {g[0]:16.1f} {g[1]:15.1f} {g[1] * byts / flops:12.1f}")
    puntos.append((nombre, flops / byts, g[1], g[1] * byts / flops))
X32 = rng.random((4096, 4096), dtype=np.float32)
for h in (1, H):
    with threadpool_limits(h, user_api="blas"):
        X32 @ X32
        print(f"sgemm  n = 4096 float32, {h:2d} hilos: {2 * 4096**3 / mejor(lambda: X32 @ X32, 3) / 1e9:.1f} GFLOP/s")
del X, Y, X32

# El roofline con techos medidos aquí: beta = mayor ancho de banda implícito de dot y gemv, pi = mayor gemm
beta = max(p[3] for p in puntos[:2])
pi_ = max(p[2] for p in puntos[2:])
I = np.logspace(-1.5, 3, 200)
plt.loglog(I, np.minimum(pi_, beta * I), color="gray", label=f"techo medido: min({pi_:.0f}, {beta:.0f}·I)")
for nombre, i_, g, _ in puntos:
    plt.loglog(i_, g, "o", label=nombre)
plt.xlabel("intensidad aritmética (flop/byte)")
plt.ylabel("GFLOP/s con todos los hilos")
plt.legend(fontsize=8)
plt.show()
print(f"punto de equilibrio medido: {pi_ / beta:.1f} flop/byte")

# 3. a*b + c*d con n = 2·10^7: temporales, out=, bloques y fusión compilada
n = 2 * 10**7
a, b, c, d = (rng.random(n) for _ in range(4))
t1, t2, r = np.empty(n), np.empty(n), np.empty(n)
B = 2**15
buf = np.empty(B)
def por_bloques():
    for i in range(0, n, B):
        s = slice(i, i + B)
        m = min(B, n - i)
        np.multiply(a[s], b[s], out=r[s])
        np.multiply(c[s], d[s], out=buf[:m])
        np.add(r[s], buf[:m], out=r[s])
fs = {
    "ingenua": lambda: a * b + c * d,
    "con out=": lambda: (np.multiply(a, b, out=t1), np.multiply(c, d, out=t2), np.add(t1, t2, out=t1)),
    "por bloques": por_bloques,
    "una pasada (multiply, out=)": lambda: np.multiply(a, b, out=r),
    "una pasada (a * b, nuevo)": lambda: a * b,
}
try:
    import numba
    @numba.njit
    def fusionada(a, b, c, d, r):
        for i in range(a.size):
            r[i] = a[i] * b[i] + c[i] * d[i]
    fusionada(a, b, c, d, r)
    fs["fusionada (Numba)"] = lambda: fusionada(a, b, c, d, r)
except ImportError:
    print("Numba no está instalado: se omite la versión compilada")
try:
    import numexpr as ne
    fs["numexpr"] = lambda: ne.evaluate("a * b + c * d", out=r)
except ImportError:
    print("numexpr no está instalado (pip install numexpr): se omite")
a32, b32, c32, d32 = (v.astype(np.float32) for v in (a, b, c, d))
fs["ingenua float32"] = lambda: a32 * b32 + c32 * d32
T = carrera(fs, 7)
print(f"\na*b + c*d, n = 2·10^7 (modelo: 9n·8 B = {72 * n / 1e9:.2f} GB con temporales, 5n·8 B = {40 * n / 1e9:.2f} GB fusionada)")
for k, t in T.items():
    print(f"  {k:28s} {t * 1e3:7.1f} ms")
del a, b, c, d, t1, t2, r, a32, b32, c32, d32

# 4. numpy.linalg frente a scipy.linalg en un sistema SPD
n = 3000
M = rng.standard_normal((n, n))
A = M @ M.T + n * np.eye(n)
bv = rng.standard_normal(n)
del M
fs = {
    "np.linalg.solve": lambda: np.linalg.solve(A, bv),
    "sla.solve (assume_a=None)": lambda: sla.solve(A, bv),
    "sla.solve gen (LU)": lambda: sla.solve(A, bv, assume_a="gen"),
    "sla.solve pos (Cholesky)": lambda: sla.solve(A, bv, assume_a="pos"),
}
print(f"\nSistema SPD n = {n}, ms:")
for h in (1, H):
    with threadpool_limits(h, user_api="blas"):
        T = carrera(fs, 3)
    print(f"  {h:2d} hilos: " + ", ".join(f"{k} {v * 1e3:.0f}" for k, v in T.items()))

# los costes O(n^2) pesan en sistemas pequeños: muchos 8x8 y una tridiagonal
As = rng.standard_normal((2000, 8, 8)) + 8 * np.eye(8)
bs = rng.standard_normal((2000, 8))
T = carrera({
    "bucle sla.solve": lambda: [sla.solve(As[i], bs[i]) for i in range(2000)],
    "bucle, gen y check_finite=False": lambda: [sla.solve(As[i], bs[i], assume_a="gen", check_finite=False) for i in range(2000)],
    "np.linalg.solve por lotes": lambda: np.linalg.solve(As, bs[..., None]),
}, 3)
print("\n2000 sistemas 8x8, ms: " + ", ".join(f"{k} {v * 1e3:.1f}" for k, v in T.items()))
nb = 4000
diag, sub = 4 + rng.random(nb), -np.ones(nb - 1)
Tm = np.diag(diag) + np.diag(sub, 1) + np.diag(sub, -1)
ab = np.zeros((3, nb))
ab[0, 1:], ab[1], ab[2, :-1] = sub, diag, sub
rhs = rng.standard_normal(nb)
T = carrera({"solve denso": lambda: sla.solve(Tm, rhs, assume_a="gen"),
             "solve_banded": lambda: sla.solve_banded((1, 1), ab, rhs)}, 3)
print(f"tridiagonal n = {nb}: denso {T['solve denso'] * 1e3:.1f} ms, solve_banded {T['solve_banded'] * 1e3:.3f} ms, "
      f"misma solución: {np.allclose(sla.solve_banded((1, 1), ab, rhs), np.linalg.solve(Tm, rhs))}")
del Tm
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Numbers change between runs because the laptop is shared, but the pattern is stable in all runs we performed.

  • The stack. NumPy and SciPy each bring their own OpenBLAS copy, of different versions, in numpy.libs and scipy.libs: two libraries that can perform differently with the same routine. Both start 24 threads, one per physical core, and use Haswell compute kernels: OpenBLAS has no Raptor Lake microkernels and chooses those of the first AVX2 and FMA generation, all this CPU offers. NumPy confirms X86_V3 and no AVX-512.
  • BLAS levels. dot and gemv do not exceed about 20 GFLOP/s even with all threads, and the last column says why: that is 45 to 75 GB/s read, around the DRAM roof (dual-channel DDR5-5600, 89.6 GB/s theoretical). With all threads dot and gemv gain 2 to 3.5 times over one thread and stop at the memory roof. A 1024 gemm gains 3.5 to 7 times, limited not by memory (needing only a few GB/s, last column) but by sharing cores with other machine processes. On the same cores, gemm performs 5 to 20 times better than gemv. On the roofline, dot and gemv fall on or just below the diagonal memory roof, gemm below the horizontal roof (by construction their best) and far right, and measured balance is a few flops per byte: any kernel below it, such as a*b + c*d with 0.040.04 to 0.0750.075, is memory-bound.
  • Against peak. A P-core at 5.8 GHz, its maximum turbo frequency, peaks at 16×5.8=92.816 \times 5.8 = 92.8 GFLOP/s in float64 and 185.6185.6 in float32. With one thread, 256 float64 gemm reaches 40 to 60 GFLOP/s in our runs and 4096 sgemm 30 to 100: between one third and somewhat over half a core’s theoretical peak. The gap is not from the algorithm: sustained AVX2 load lowers frequency below 5.8 GHz, Windows can move the thread to an E-core with half the peak, and the rest of the machine was busy. Goto and van de Geijn show near-peak performance on diverse architectures when the core works in isolation.
  • The expression. Naive takes 1.4 to 2.5 times as long as out=: the byte model says both move the same, and the difference is the cost of new temporaries (compare the two “one pass” lines). Numba fusion is 1.5 to 1.9 times faster than out=, around the 1.8 predicted by ratio 9sn/5sn9sn / 5sn, with the blocked version between. In float32, naive takes about half the time.
  • The routines. With one thread, assume_a="pos" (Cholesky) takes half to two thirds of SciPy LU time, consistent with n3/3n^3/3 versus 2n3/32n^3/3 flops; np.linalg.solve performs the same LU with the other OpenBLAS copy, so time need not match. With assume_a=None, SciPy detects structure and approaches Cholesky. All-thread figures are noisier. For 2000 systems of 8×88 \times 8, NumPy’s batched version is 40 to 80 times faster than a loop of calls, while removing structure detection and check_finite changes the loop little (sometimes 30% shorter, sometimes below noise): cost lies in 2000 Python calls, not checks. solve_banded solves the tridiagonal more than a thousand times faster than dense solve: O(n)\bigO(n) versus O(n3)\bigO(n^3).

BLAS threads and oversubscription

OpenBLAS and MKL launch one thread per physical core by default: 24 in the lab, versus 32 logical threads. They are controlled in two ways:

  • Environment variables, before importing NumPy: OPENBLAS_NUM_THREADS, MKL_NUM_THREADS or OMP_NUM_THREADS. After import they no longer take effect.
  • At runtime, with threadpoolctl: with threadpool_limits(1, user_api="blas"): ... limits all loaded BLAS libraries, and threadpool_info() lists them.

Oversubscription arises when combining your own parallelism with multithreaded BLAS: an multiprocessing.Pool of 8 processes where each performs matrix products with 24 threads puts 192 threads competing for 32 logical cores. Context switches, caches interfering with one another and threads waiting at barriers can make the whole thing slower than one process. The rule: if parallelizing outside (processes, joblib, a server with multiple requests), limit BLAS to ⌊nuˊcleos/trabajadores⌋\lfloor \text{núcleos} / \text{trabajadores} \rfloor threads inside each worker. CPU parallelism and its laws are the subject of threads, processes and the GIL.

scipy.linalg versus numpy.linalg

numpy.linalg covers the basics with a batched interface (operating on matrix stacks). scipy.linalg wraps much more of LAPACK and lets you choose the cost:

NeedRoutineCost
General systemsolve(A, b, assume_a="gen") (LU, gesv)2n3/32n^3/3
Symmetric positive definitesolve(A, b, assume_a="pos") (Cholesky, posv)n3/3n^3/3
Triangularsolve_triangular(T, b, lower=...) (trtrs)n2n^2
Banded or tridiagonalsolve_banded((l, u), ab, b) (gbsv)O(n(l+u)2)\bigO(n(l + u)^2)
Same matrix, many bblu_factor and lu_solve, or cho_factor and cho_solvefactor once
Many small matricesnp.linalg.solve with a stack (lote, n, n)a C loop

In SciPy 1.18, assume_a=None (the default) inspects the matrix to select the routine, costing a pass O(n2)\bigO(n^2); if you know the structure, state it. Three more options remove O(n2)\bigO(n^2) costs noticeable on small matrices: overwrite_a=True lets LAPACK factor your array rather than copy it, check_finite=False skips checking for NaNs and infinities (if present, the result may be garbage or the process may hang), and for the low-level version scipy.linalg.get_blas_funcs and get_lapack_funcs return the appropriate precision routine without intermediate layers. You saw banded systems with the Thomas algorithm: solve_banded is its LAPACK version.

Common mistakes

Connections

Exercises

NumericThe bytes in two temporaries
Arrays aa, bb, cc and dd are float64 with 10810^8 elements and NumPy evaluates a*b + c*d as three ufuncs with two temporaries. Counting each read and write of an element once, how many GB does the whole evaluation move?
NumericMicrokernel registers
A 6×166 \times 16 float32 GEMM microkernel with AVX2 keeps the whole C\mat{C} tile in 256-bit ymm registers. How many registers do the accumulators occupy?
NumericThe largest microkernel that fits
You design an mr×16m_r \times 16 float32 microkernel with AVX2: the tile accumulators, the row of 16 B~\tilde{\mat{B}} elements and a register to broadcast the A~\tilde{\mat{A}} element must fit in the 16 ymm registers. What is the largest possible mrm_r?
NumericWhen the shortcut overflows
The cumulative-product trick with constant at=0.9a_t = 0.9 contains 0.9−t0.9^{-t}. What is the smallest tt for which 0.9−t0.9^{-t} is no longer representable in float64, whose largest finite value is 1.797×103081.797 \times 10^{308}?
NumericThe cost of a scan
How many ∘\circ combinations does the Hillis–Steele scan perform in total on n=1000n = 1000 pairs?
QuizWhich loops allow 8 lanes?
Which of these loops over float32 can a compiler vectorize with AVX2 (8 lanes) while guaranteeing the same bit-for-bit result as the scalar version? Arrays do not overlap except when the same array is indexed.

More than one answer may be correct.

QuizAll cores and far from peak
In the lab, gemv with n=4096n = 4096 in float64 and all threads stays well below gemm with the same cores and library. What is the main reason?
QuizNegative squared distances
You compute squared distances between map points in projected coordinates in meters (values of order 10610^6) using ∥x∥2+∥y∥2−2XY⊤\norm{\vb{x}}^2 + \norm{\vb{y}}^2 - 2\mat{X}\mat{Y}\T, in float64, and small negative values appear. What happens and what fixes it best?
ProofThe inverse by doubling
Prove: If S\mat{S} is the n×nn \times n shift and 2m≥n2^m \ge n, then (I−aS)−1=∏j=0m−1(I+a2jS2j)(\mat{I} - a\mat{S})^{-1} = \prod_{j=0}^{m-1}(\mat{I} + a^{2^j}\mat{S}^{2^j}) for every a∈Ra \in \R.
0
S\mat{S} has ones on the subdiagonal and zeros elsewhere: (Sx)t=xt−1(\mat{S}\vb{x})_t = x_{t-1} and (Sx)0=0(\mat{S}\vb{x})_0 = 0.

Step 1 of 4. Which property of S\mat{S} will complete the argument?

CodeA loop-free EWMA that does not break
Implement ewma(x, alpha) with y0=x0y_0 = x_0 and yt=(1−α) yt−1+α xty_t = (1 - \alpha)\,y_{t-1} + \alpha\,x_t, without Python loops over elements (a loop of a few dozen vectorized passes is allowed) and without lfilter. It must match the sequential recurrence with relative error below 10−1210^{-12} on series of 10610^6 prices for α\alpha between 10−410^{-4} and 0.50.5. The starter code uses the cumulative-product trick: run the tests and see why it fails.
import numpy as np

def ewma(x, alpha):
  """y_0 = x_0, y_t = (1 - alpha) y_{t-1} + alpha x_t."""
  x = np.asarray(x, dtype=float)
  a = 1 - alpha
  xt = alpha * x
  xt[0] = x[0]
  P = a ** np.arange(len(x))      # a^t
  return P * np.cumsum(xt / P)    # y_t = a^t * sum_s xt_s / a^s
Shift+Enter to run

Summary

Key idea
Good vectorization means moving few bytes and filling the lanes: an array expression costs as much as its memory passes, a recurrence is parallelized as a scan of pairs (a,x)(a, x) without ever dividing by small powers, and only BLAS level 3, thanks to packing by cache level and a register microkernel, has enough intensity to approach the peak.
  • An AVX2 register has 8 float32 lanes or 4 float64 lanes, and an FMA performs ab+ca b + c with one rounding. A loop vectorizes if it has no dependencies shorter than the width, branches that cannot become masks, aliasing or scattered accesses.
  • Each ufunc is one memory pass: a*b + c*d moves 9sn9sn bytes with temporaries and 5sn5sn fused. out= does not reduce traffic but avoids allocating new memory; fusion and float32 do reduce it.
  • yt=atyt−1+xty_t = a_t y_{t-1} + x_t is a scan of the associative operation (a1,x1)∘(a2,x2)=(a2a1,a2x1+x2)(a_1, x_1) \circ (a_2, x_2) = (a_2 a_1, a_2 x_1 + x_2), with depth log⁡2n\log_2 n. The cumulative-product shortcut overflows around t≈709.78/∣ln⁡a∣t \approx 709.78/\abs{\ln a} and in log scale loses u∣Lt∣u\abs{L_t} of precision.
  • ∥x∥2+∥y∥2−2x⊤y\norm{\vb{x}}^2 + \norm{\vb{y}}^2 - 2\vb{x}\T\vb{y} is fast and suffers cancellation: center the data, clip at 0 or recompute small distances.
  • A Goto-style GEMM packs B~\tilde{\mat{B}} for L3, A~\tilde{\mat{A}} for L2, traverses L1 microstrips and keeps an 6×166 \times 16 tile of C\mat{C} in 12 registers.
  • BLAS 1 and 2 are memory-bound at every size and BLAS 3 is not. Control threads with threadpoolctl and choose the scipy.linalg routine according to matrix structure.