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
- 09Memory layout: row-major and column-majorCache lines and localityLoop tiling (blocking)Arithmetic intensityRoofline modelMemory microbenchmarks: pointer chasing and STREAMFlop countingBanded and tridiagonal solversCatastrophic cancellationRecursive and pairwise summation
- 00ndarray memory modelStrides and contiguityViews versus copiesBroadcasting rulesufuncs, reductions and accumulations along axesVectorization
- 08Parallel prefix scanScans over associative operators
Motivation: the same calculation at very different speeds
You have four arrays of prices and weights and want for each , 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.
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*dtraverses 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. 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 of a 2D array is at address
where 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.Ttraversed 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.
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 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 with one rounding in one step. A P-core of this CPU has two 256-bit FMA units, so every cycle it can perform
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 iterations it will merge do not influence one another. There are five usual obstacles.
- Dependencies between iterations. If iteration needs what wrote, lanes cannot work simultaneously. The proposition below makes this precise.
- Branches. An
ifin 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. - Aliasing. If
yandxcan overlap in memory, writing anyblock can change the nextxblock. C promises this does not happen withrestrict; NumPy checks at runtime and, if overlap exists, works on a copy. - 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. - 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 reads . In the scalar version, iteration reads after iteration may have written it. If , every iteration with in the block satisfies : 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 , iteration is in the same block as : the vector version reads old and scalar reads what just wrote. Take , all initial equal to , all equal to , and : scalar writes and vector .
∎In particular, a first-order recurrence, , allows no width above 1 as written. It must be reformulated, the subject of the recurrence section.
The interactive’s model counts loop-body iterations, and ratio is ideal speedup: at most 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 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.
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 . The last two lines show NumPy aliasing. v[1:] += v[:-1] looks like recurrence , but NumPy detects overlapping input and output, reads everything before writing (vector semantics with infinite ), and gives . The actual recurrence is np.cumsum, that is, np.add.accumulate, a C loop that does not vectorize by lanes.
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 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 float64s, each occupies 800 MB: no cache retains it between passes.
For a*b + c*d: passes, each with , and , so versus . With a chain of binary operations over distinct variables, the ratio is , tending to 3. With a chain over one variable and scalars, such as ((x + 1) * 2 - 3) / 4, it is : 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 flops per byte and fused . The roofline model says attainable performance is , with compute peak and bandwidth. This machine’s balance point is a few flops per byte (measured in the local lab), so the expression lies tens of times below it: time is 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.
numexprevaluates the expression in cache-fitting blocks and with multiple threads; Numba, covered in the compiled extensions lesson, compiles the fused loop;torch.compiledoes 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.
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 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.
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,
is time-series simple exponential smoothing, and a case of the first-order linear recurrence
with and (and ). 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 are constant.
2. Cumulative products. Unrolling the recurrence, with ,
which are an cumprod and an cumsum: two vectorized passes. The problem is . With constant , and grows exponentially: it overflows the largest float64 (, with logarithm ) as soon as
For this is about 1024 steps; for , 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 and, if ,
where is cumulative log-sum-exp (np.logaddexp.accumulate). Nothing overflows now, but the exponent sums two enormous numbers of opposite sign, and , approximately , to yield a small result of size . This is catastrophic cancellation in the exponent: each term has absolute error around , with unit roundoff, and absolute error in the exponent is relative error in . Thus
an error growing linearly with (with a larger constant as approaches 1, because other rounding errors matter more). With points and it is : 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 , represented by pair . Applying first and afterward gives , that is, the pair
Proof
Associativity is that of function composition: pair represents affine map , and represents , “first , then ”. Function composition is associative. It can also be checked by hand: both groupings of three pairs give . Pair is identity. By induction, is the map “perform steps ”, and evaluated at gives . Any associative operator admits m08’s associative-operator scan algorithms with the stated depth.
∎The easiest scan to vectorize is Hillis–Steele: at level , each position combines with , all at once:
After level , position summarizes steps , so after levels everything is final. Each level is one vectorized operation over shifted slices. The price is work: level performs combinations, in total, versus the recurrence’s . Blelloch scan, with an up-sweep and down-sweep over a tree, performs only combinations at depth ; it is used on GPU, where total work matters.
For EWMA with constant , everything is simpler: after level , for every , a scalar.
The recurrence in matrix form is , so the theorem gives an algorithm: apply the factors to , each with one instruction, y[k:] += a**k * y[:-k] for After factor , the weight of in is for every . Since becomes tiny quickly, one can stop when nothing changes in float64: with 6 passes suffice for , and with , 19 (if the series has at least points). You reconstruct the proof (a one-line telescoping product) in a guided exercise. The key is that only powers appear: nothing can overflow, and rounding errors are those of a bounded-weight sum.
The next cell compares the four methods on the first cell’s price-series EWMA.
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 because does not overflow, but give nonfinite values from , and for , and : a few steps before (70 625, 6 737 and 1 024), because prices are around 100 and the cumulative sum exceeds somewhat before . The log version never overflows, but its error grows with , which at the series end is : , and , versus , and . Doubling scan remains at except with , where weights are close to 1 and its 18 passes accumulate rounding to , 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 with .
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 and matches the recurrence to . Even with extra work , 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 , just when crosses : overflows. Before breaking, error rises from at the start to at the end, order predicted by the analysis.
Vectorizing without losing accuracy: pairwise distances
To calculate distances between points and points in , the direct broadcasting form, ((X[:, None] - Y[None]) ** 2).sum(-1), creates a temporary of elements. The fast form uses
with which the whole matrix is two norm vectors plus a matrix product, : a GEMM, the fastest operation in the stack, as you will soon see. This is what scikit-learn and almost all implementations of neighbors or -means do.
The price is subtraction. If and are close to each other but far from the origin, and are two nearly equal large numbers. Each is computed with error around (plus a factor of order in the worst case), and subtraction retains that entire error:
When the ratio exceeds , 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.
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 on these very small distances ( versus ): the bound’s ratio is about and multiplying by gives . Each 100-fold offset multiplies the ratio and error by : with , with and pure noise with , including 19 negative distances. Centering brings error back to 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 is . - 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 (GEMM, general matrix multiply) with and performs flops on data. With , ideal intensity is on the order of 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 tile of in registers for steps. At each step it loads a column of ( numbers, broadcast individually to a register) and a row of ( numbers, registers), and performs FMA instructions: a rank-1 update. Data are reused and times without leaving registers.
- Why in float32 with AVX2. Accumulators occupy registers, the row of another , and broadcast of 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 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): latency × units. BLIS kernels for Haswell, the generation introducing AVX2 and FMA, are exactly in float32 and 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.
- sets how long each tile stays in registers: the larger it is, the more loading and storing is amortized. Its limit is fitting the micro-panel, , into L1 along with circulating data. makes fit L2 and makes fit L3. Goto’s central observation was that the block should live in L2, not L1, which is too small.
Proof
is read only during packing, and each block is packed once because the two outer loops visit each pair once. is packed inside loop 3, executed for each pair : block of is packed once per , or times. Each tile is loaded into registers and stored once per corresponding microkernel execution, occurring once per : 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 in float32 and the interactive’s block rules, is reread 11 times, yet intensity is about 85 flops per byte, far above balance: GEMM is compute-bound, the desired result.
The interactive’s size rules are an explicit simplified model: the micro-panel occupies half L1, half L2 and half L3. With 48 KiB L1, 2 MiB L2 and 36 MiB L3 in float32 this gives , and . 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.
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:
| Level | Operation | Flops | Bytes (each datum once) | Intensity |
|---|---|---|---|---|
| 1 | dot de longitud | |||
| 2 | gemv | |||
| 3 | gemm |
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 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.
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 Tmnpm 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.libsandscipy.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 confirmsX86_V3and no AVX-512. - BLAS levels.
dotandgemvdo 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 threadsdotandgemvgain 2 to 3.5 times over one thread and stop at the memory roof. A 1024gemmgains 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,gemmperforms 5 to 20 times better thangemv. On the roofline,dotandgemvfall on or just below the diagonal memory roof,gemmbelow the horizontal roof (by construction their best) and far right, and measured balance is a few flops per byte: any kernel below it, such asa*b + c*dwith to , is memory-bound. - Against peak. A P-core at 5.8 GHz, its maximum turbo frequency, peaks at GFLOP/s in float64 and in float32. With one thread, 256 float64
gemmreaches 40 to 60 GFLOP/s in our runs and 4096sgemm30 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 thanout=, around the 1.8 predicted by ratio , 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 versus flops;np.linalg.solveperforms the same LU with the other OpenBLAS copy, so time need not match. Withassume_a=None, SciPy detects structure and approaches Cholesky. All-thread figures are noisier. For 2000 systems of , NumPy’s batched version is 40 to 80 times faster than a loop of calls, while removing structure detection andcheck_finitechanges the loop little (sometimes 30% shorter, sometimes below noise): cost lies in 2000 Python calls, not checks.solve_bandedsolves the tridiagonal more than a thousand times faster than densesolve: versus .
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_THREADSorOMP_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, andthreadpool_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 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:
| Need | Routine | Cost |
|---|---|---|
| General system | solve(A, b, assume_a="gen") (LU, gesv) | |
| Symmetric positive definite | solve(A, b, assume_a="pos") (Cholesky, posv) | |
| Triangular | solve_triangular(T, b, lower=...) (trtrs) | |
| Banded or tridiagonal | solve_banded((l, u), ab, b) (gbsv) | |
| Same matrix, many | lu_factor and lu_solve, or cho_factor and cho_solve | factor once |
| Many small matrices | np.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 ; if you know the structure, state it. Three more options remove 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
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?More than one answer may be correct.
gemv with in float64 and all threads stays well below gemm with the same cores and library. What is the main reason?Step 1 of 4. Which property of will complete the argument?
ewma(x, alpha) with and , 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 on series of prices for between and . 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^sSummary
- An AVX2 register has 8 float32 lanes or 4 float64 lanes, and an FMA performs 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*dmoves bytes with temporaries and fused.out=does not reduce traffic but avoids allocating new memory; fusion and float32 do reduce it. - is a scan of the associative operation , with depth . The cumulative-product shortcut overflows around and in log scale loses of precision.
- is fast and suffers cancellation: center the data, clip at 0 or recompute small distances.
- A Goto-style GEMM packs for L3, for L2, traverses L1 microstrips and keeps an tile of in 12 registers.
- BLAS 1 and 2 are memory-bound at every size and BLAS 3 is not. Control threads with
threadpoolctland choose thescipy.linalgroutine according to matrix structure.