Broadcasting and vectorization
Broadcasting rules allow operations on arrays of different shapes without copying, while vectorization moves loops from the interpreter to compiled code. Learn to think in shapes, rewrite nested-loop algorithms as array operations (pairwise distances, stable softmax and log-sum-exp, particle simulations), and control the memory explosion of naive vectorization by processing blocks.
After this lesson you can
- Apply broadcasting rules to predict the result shape or error of any operation.
- Rewrite nested loops as vectorized operations using new axes (None) and reductions with keepdims.
- Vectorize pairwise distances and reason about their memory cost compared with the dot-product identity.
- Use ufuncs, reductions, and accumulations (sum, argmax, cumsum, maximum.accumulate, logaddexp) with the correct axis.
- Bound the memory of a vectorized computation by processing blocks and measure the speedup with %timeit.
Before you start
Motivation: the same physics, two speeds
A hundred particles in the plane attract each other by gravity. The force particle exerts on points from to and decays with the square of the distance; summing over all the others,
where is a softening term that avoids division by zero when two particles nearly coincide. The formula calls for a double loop, and that is the first thing one writes. The following cell calculates forces three ways: with that double loop indexing the ndarray element by element, with the same double loop over Python lists and floats, and without any loop, operating on arrays of shape containing all pairs at once.
import math, time
import numpy as np
def medir(f, *args, minimo=0.2):
"""Tiempo medio por llamada: repite f hasta acumular `minimo` segundos (el reloj del navegador es grueso)."""
reps, t0 = 0, time.perf_counter()
while True:
f(*args)
reps += 1
dt = time.perf_counter() - t0
if dt >= minimo:
return dt / reps
EPS2 = 0.05 ** 2 # suavizado ε²
def fuerzas_npbucle(pos, masa):
"""Doble bucle que indexa el ndarray elemento a elemento: el primer código que se suele escribir."""
n = len(pos)
F = np.zeros((n, 2))
for i in range(n):
for j in range(n):
if i != j:
d = pos[j] - pos[i]
r2 = d @ d + EPS2
F[i] += masa[i] * masa[j] * d / r2 ** 1.5
return F
def fuerzas_bucles(pos, masa):
"""El mismo doble bucle sobre listas y floats de Python: sin crear un ndarray por operación."""
p, m = pos.tolist(), masa.tolist()
n = len(p)
F = []
for i in range(n):
xi, yi = p[i]
fx = fy = 0.0
for j in range(n):
if i != j:
dx, dy = p[j][0] - xi, p[j][1] - yi
r2 = dx * dx + dy * dy + EPS2
s = m[j] / (r2 * math.sqrt(r2))
fx += s * dx
fy += s * dy
F.append([m[i] * fx, m[i] * fy])
return np.array(F)
def fuerzas_vec(pos, masa):
"""Sin bucles: todas las parejas (i, j) a la vez."""
x, y = pos[:, 0], pos[:, 1] # (N,)
dx = x[None, :] - x[:, None] # (N, N): dx[i, j] = x_j - x_i
dy = y[None, :] - y[:, None] # (N, N)
r2 = dx * dx + dy * dy + EPS2 # (N, N)
w = masa[None, :] / (r2 * np.sqrt(r2)) # (N, N): m_j / r_ij³
np.fill_diagonal(w, 0.0) # sin autointeracción
return masa[:, None] * np.stack([(w * dx).sum(axis=1), (w * dy).sum(axis=1)], axis=1) # (N, 2)
rng = np.random.default_rng(0)
N = 100
pos = rng.standard_normal((N, 2)) # (N, 2)
masa = rng.uniform(0.5, 1.5, N) # (N,)
F = fuerzas_vec(pos, masa)
print("las tres coinciden:", np.allclose(fuerzas_npbucle(pos, masa), F), np.allclose(fuerzas_bucles(pos, masa), F))
print("fuerza total (tercera ley de Newton):", np.abs(F.sum(axis=0)).max())
t = {f.__name__: medir(f, pos, masa) for f in (fuerzas_npbucle, fuerzas_bucles, fuerzas_vec)}
for nombre, s in t.items():
print(f"{nombre:16s} {s * 1e3:8.2f} ms x{t['fuerzas_npbucle'] / s:5.0f}")All three versions give the same forces (and their sum is zero except for rounding, as Newton’s third law requires), but they take different times. In the browser, the loop-free version is several hundred times faster than the loop indexing the ndarray, and 15 to 30 times faster than the pure Python loop (exact figures vary between runs; the order of magnitude does not). Notice the middle detail: the list loop comfortably beats the array loop, because each pos[j] - pos[i] creates a new two-element ndarray, and creating tiny arrays is expensive. NumPy speeds up code that gives it a lot of work per call.
That is what we need to learn to do:
The word has a second meaning at processor level: SIMD instructions that operate on several numbers at once. The two are related (NumPy’s compiled loops use SIMD when possible), but here we mean the first; the second is studied in SIMD vectorization.
There is no loop in fuerzas_vec, yet the expression x[None, :] - x[:, None] subtracts a vector of shape and one of shape and obtains a matrix . The rules deciding what happens when operating on arrays of different shapes are broadcasting, half of this lesson. The other half is learning to think about algorithms in terms of whole arrays, understanding their memory cost, and knowing when they are not worthwhile.
The three broadcasting rules
Start with the smallest case: a column of shape plus a row of shape .
col = np.arange(3.0).reshape(3, 1) # (3, 1)
fila = 10.0 * np.arange(4) # (4,)
print(col + fila) # (3, 4): una tabla de sumas
v = np.broadcast_to(col, (3, 4)) # la columna "estirada" a (3, 4), sin copiar
print("strides de col:", col.strides, " strides de la vista (3, 4):", v.strides)
print("¿comparte memoria?", np.shares_memory(v, col), " ¿escribible?", v.flags.writeable)
print("bytes reales:", col.nbytes, " bytes de una copia con np.tile:", np.tile(col, (1, 4)).nbytes)
print(np.broadcast_shapes((8, 1, 6, 1), (7, 1, 5)))
try:
np.ones((3, 1)) + np.ones((1, 4)) + np.ones(5)
except ValueError as e:
print("ValueError:", e)The result is the table : the column has been repeated across four columns and the row across three rows. But nothing has been copied. np.broadcast_to returns a view whose stride on the stretched axis is zero: advancing one column does not move the pointer, so the same number is read again. This is the mechanism seen in strides and contiguity, taken to the extreme, and that is why the view is read-only: writing to one cell would write to every cell in its row at once.
Three observations that separate knowing the rule from understanding it:
- The resulting size is not the maximum. It is “the one that is not 1.” They almost always agree except with empty axes: with gives , not . This seems like a toy detail until an empty batch at the end of an epoch passes through your code.
- Rule 1 is a convention with consequences. Padding on the left means a vector of shape behaves as a row , never as a column. To make it act as a column, say so:
v[:, None]. - The index is exactly what zero strides do. The memory address of is ; with coordinate disappears from the sum, the same as replacing it with . The formula and implementation are the same thing.
With three or more operands, apply the rule to all at once (np.broadcast_shapes), or pairwise in expression evaluation order. The last line of the cell shows a nuance: in a + b + c NumPy first computes a + b, of shape , and the error message mentions that intermediate shape, which does not appear in your code. That the two interpretations (all at once or pairwise, in any order) agree whenever defined is a small theorem: the operation on shapes is commutative and associative. You prove it in the exercises.
What you should have seen:
- Padding ones appear only on the left. With and , the aligns with width , not the channel. This is the most frequent mistake when normalizing images by channel; fix it by giving shape , or , which is the same after padding.
- Each zero stride is an axis that occupies no memory. In the documentation example, the result has elements and the operands store and .
- The map shows the formula. Result cell reads row of an operand of shape but column , whatever is.
- The most dangerous broadcasting raises no error. A prediction minus a target produces a matrix of all 25 cross-differences. Both operands have 5 elements and the result 25: if that was not intended, nobody will warn you.
Thinking in shapes
The rules are mechanical; the hard part is using them deliberately. Three tools suffice for almost everything:
None(ornp.newaxis) in an index adds a size-1 axis without copying anything: ifvhas shape ,v[:, None]is andv[None, :]is . This says “this dimension will be stretched.”keepdims=Truein reductions keeps the reduced axis at size 1, so the result aligns with the original array without further thought:X.sum(axis=1, keepdims=True)has shape and can be subtracted from or divided intoX.- Annotate each variable’s shape in a comment,
# (n, m), or in its type, using shape annotations. In array code, shape is the type that matters, and annotating it makes every line a check you perform mentally.
The general pattern for vectorizing a nested loop is to assign one axis to each loop index. The force formula has two indices, and ; therefore fuerzas_vec puts on axis 0 (x[:, None]) and on axis 1 (x[None, :]), operates on arrays, and ends with a .sum(axis=1) reduction, the formula’s . Free index, surviving axis; summed index, reduced axis. If you know Einstein notation, this is exactly the idea behind einsum, covered two lessons from now.
The other side: broadcasting does not warn when you use it unintentionally.
rng = np.random.default_rng(1)
n = 5
y = rng.standard_normal(n) # (n,) objetivos
pred = (y + 0.1 * rng.standard_normal(n)).reshape(n, 1) # (n, 1): salida de una capa con una neurona
print("forma de pred - y:", (pred - y).shape) # (n, n), sin error
print("MSE con broadcasting silencioso:", np.mean((pred - y) ** 2))
print("MSE correcto: ", np.mean((pred[:, 0] - y) ** 2))
X = rng.standard_normal((4, 4)) # cuadrada: el caso traicionero
normas = np.linalg.norm(X, axis=1) # (4,)
mal = X / normas # divide la COLUMNA j por la norma de la FILA j
bien = X / normas[:, None] # (4, 4) / (4, 1): cada fila por su norma
print("normas de las filas, mal: ", np.linalg.norm(mal, axis=1).round(3))
print("normas de las filas, bien:", np.linalg.norm(bien, axis=1).round(3))The first failure is classic in training: the loss is finite, decreases, and is incorrect because it measures each prediction against all targets. Here the actual error is about 600 times smaller than the calculated one. The second is worse: with a rectangular matrix, X / normas would have raised an error, but with a square one shapes and fit and each column is divided by a row’s norm. The remedy in both cases is the same: know each operand’s shape before writing the operator, and distrust square matrices in tests, which hide these errors. A matrix in the test would have failed immediately.
ufuncs, reductions, and accumulations
The engine behind all of the above is a type of NumPy function.
Common reductions (sum, mean, max, min, argmax, std, any, all) accept axis as an integer, a tuple of integers, or None (all axes), and keepdims. The shape rule is always the same: reduced axes disappear, or remain size 1 if keepdims=True. What is not always the same is the intuition for what “reduce axis 1” means in a three-dimensional array. This cube is drawn as NumPy prints it: axis 0 is blocks (depth), axis 1 rows, and axis 2 columns.
What you should have seen:
- Reducing axis collapses cells along , not “in direction ” in a mental table: with
axis=1each output combines the 3 rows of one column within a block. One output per combination of the axes that remain. - Without
keepdims,x - ronly does the right thing if the reduced axes are the first ones. Withaxis=0, the result aligns on the right with and broadcasting puts it back. Withaxis=1oraxis=2, the vanished axis displaces all those to its left and the error appears on the next line, far from its cause (or does not appear if displaced sizes happen to match, as in square matrices).keepdims=Truealways works. argmaxreturns positions, not values, and only accepts one axis. Withaxis=Noneit returns an index on the flattened array, whichnp.unravel_indexconverts to coordinates.- In the image batch, the mean per channel is
x.mean(axis=(0, 2, 3)), of shape , which aligns with width . Withkeepdims=Trueit is and normalization(x - mu) / sdis correct. This is what a batch normalization layer computes; layer norm, instance norm, and group norm are the same operation with other axis tuples, as covered in the taxonomy of normalization axes.
Accumulations are reductions that save history, yielding loop-free patterns that are not obvious:
x = np.arange(24).reshape(2, 3, 4) # (2, 3, 4)
print(np.add.reduce(x, axis=1).shape, x.sum(axis=1).shape, x.sum(axis=1, keepdims=True).shape)
print("sum por (0, 2):", x.sum(axis=(0, 2))) # (3,)
print("cumsum:", np.cumsum([3, 1, 4, 1, 5]))
print("máximo acumulado:", np.maximum.accumulate([3, 1, 4, 1, 5]))
print("tabla de multiplicar 3 x 4:\n", np.multiply.outer(np.arange(1, 4), np.arange(1, 5)))
k = x.argmax() # índice plano
print("argmax plano:", k, "-> coordenadas", tuple(int(c) for c in np.unravel_index(k, x.shape)))
z = np.array([1000.0, 1000.5, 999.0])
with np.errstate(over="ignore"):
print("logaddexp.reduce:", np.logaddexp.reduce(z), " ingenuo:", np.log(np.sum(np.exp(z))))
rng = np.random.default_rng(2)
precio = 100 * np.exp(np.cumsum(0.01 * rng.standard_normal(250))) # un año de precios
pico = np.maximum.accumulate(precio) # máximo alcanzado hasta cada día
caida = 1 - precio / pico # drawdown diario
dia = int(caida.argmax())
print(f"drawdown máximo: {caida.max():.1%}, el día {dia}, desde el pico del día {int(precio[:dia + 1].argmax())}")Drawdown, the fall from the previous maximum, is one of the most widely used risk measures in portfolio management, and its definition, , involves a cumulative maximum: with np.maximum.accumulate it is one loop-free line. np.logaddexp.reduce computes without overflow, the subject of the next section.
Classic patterns
Pairwise distances
Given two point clouds and (one point per row), the matrix of squared distances appears in -nearest neighbors, k-means assignment, Gaussian kernels, and, with a dot product instead of a distance, transformer attention. There are three ways to calculate it:
- Double loop: interpreter iterations, each with a NumPy operation on vectors of length .
- Naive broadcasting:
X[:, None, :] - Y[None, :, :]has shape ; square it and sum along the last axis. Zero loops, but an intermediate tensor of numbers. - Dot-product identity: expanding the square,
with and . The cross term is a single matrix product; the other two are a column vector and a row vector that broadcasting adds to every element: xx[:, None] + yy[None, :] - 2 * X @ Y.T. Intermediate memory is instead of , and a matrix product, the most optimized operation available, does the heavy work. These are the norm and dot product from the linear algebra module applied to many vectors at once.
def dist2_bucles(X, Y):
D = np.empty((len(X), len(Y)))
for i in range(len(X)):
for j in range(len(Y)):
D[i, j] = np.sum((X[i] - Y[j]) ** 2)
return D
def dist2_ingenua(X, Y):
return ((X[:, None, :] - Y[None, :, :]) ** 2).sum(axis=-1) # (n, m, d) -> (n, m)
def dist2_producto(X, Y):
xx = (X * X).sum(axis=1) # (n,)
yy = (Y * Y).sum(axis=1) # (m,)
return xx[:, None] + yy[None, :] - 2.0 * X @ Y.T # (n, m)
rng = np.random.default_rng(3)
X, Y = rng.standard_normal((200, 32)), rng.standard_normal((300, 32))
D = dist2_bucles(X, Y)
print("coinciden:", np.allclose(D, dist2_ingenua(X, Y)), np.allclose(D, dist2_producto(X, Y)))
for f in (dist2_bucles, dist2_ingenua, dist2_producto):
print(f"{f.__name__:15s} {medir(f, X, Y) * 1e3:8.2f} ms")
# puntos a 10⁵ del origen y separados unos 10⁻²: coordenadas UTM en metros, embeddings con media grande...
P = 1e5 + 1e-2 * rng.standard_normal((400, 3))
fuera = ~np.eye(400, dtype=bool)
D_ref = dist2_ingenua(P, P) # diferencias primero: exacta hasta el redondeo
D_id = dist2_producto(P, P)
print("negativas:", int((D_id < 0).sum()), " mínimo:", D_id.min())
print("error relativo máximo:", (np.abs(D_id - D_ref)[fuera] / D_ref[fuera]).max())
Pc = P - P.mean(axis=0) # trasladar no cambia las distancias
print("tras centrar: ", (np.abs(dist2_producto(Pc, Pc) - D_ref)[fuera] / D_ref[fuera]).max())The identity wins on speed but has a numerical cost. If points are far from the origin compared with their separation, and are huge numbers nearly equal to , and their difference loses almost all significant digits: catastrophic cancellation. With coordinates on the order of , each term is on the order of and its rounding error on the order of , only about a hundred times smaller than typical squared distances, on the order of , and larger than the smallest. Of float64’s sixteen digits, two survive in a typical distance and none in the shortest: in the cell, some distances are negative (and their square roots nan) and maximum relative error comfortably exceeds 100%. Two remedies can be combined: clip to zero with np.maximum(D, 0), which avoids nan but does not recover precision, and center the data first, which does recover it because distances are translation-invariant and norms are small after centering.
Row normalization
Dividing each row by its norm, subtracting each column’s mean, or scaling each channel use the same template: a reduction with keepdims=True followed by an elementwise operation.
Xn = X / np.linalg.norm(X, axis=1, keepdims=True) # filas unitarias: (n, d) / (n, 1)
Xc = X - X.mean(axis=0) # columnas centradas: (n, d) - (d,), los ejes iniciales no hacen falta
Xs = (X - X.mean(axis=0)) / X.std(axis=0) # estandarizar cada característica
The second and third lines work without keepdims because they reduce axis 0, the first: result is padded to and returns to its place. The first reduces axis 1 and needs it; without it, divided by fails or, if , silently divides incorrectly. When in doubt, keepdims=True: it is free.
Stable softmax and log-sum-exp
The softmax function converts a vector of scores (logits) into probabilities, and log-sum-exp is the logarithm of its denominator:
Computed directly, they fail when logits are large: overflows to inf in float64 for , and in float32 for , leaving inf / inf = nan. If all logits are very negative the opposite happens: all exponentials round to and leave 0 / 0. The solution follows from a property worth deriving:
Subtracting the maximum with keepdims=True makes the recipe work on any tensor axis: z - z.max(axis=k, keepdims=True). This is the log-sum-exp trick, and the final bound explains why log-sum-exp is used as a smooth maximum.
One-hot
Encoding labels as vectors with a single 1 broadcasts a comparison: a column of labels against a row of classes gives a Boolean matrix .
Y = (y[:, None] == np.arange(K)[None, :]).astype(np.float64) # (n, 1) == (1, K) -> (n, K)
The alternative np.eye(K)[y] uses advanced indexing and gives the same result. With one-hot, a classifier’s cross-entropy is -(Y * log_p).sum(axis=1).mean(); in practice the one-hot matrix is not materialized and log_p[np.arange(n), y] is read directly, as covered in the next lesson.
Memory cost and chunked vectorization
Naive broadcasting of distances creates a tensor of numbers. With and , in float64, that is elements and GB, and in practice the peak is double because the difference and its square coexist briefly before the difference is freed. With it no longer fits in 32 GB RAM: the “most vectorized” version is the only one that does not finish. The identity needs , but even stops fitting when and are on the order of .
The solution is never to materialize the entire tensor:
The Python loop still exists, but runs times instead of , and each iteration brings enough work for its microsecond overhead to be negligible. When the final result is small, for example the nearest-neighbor index of each row, reduction is performed within the block and the complete matrix never exists either.
What you should have seen:
- The double loop uses least memory and takes longest: a few microseconds per pair, which with million pairs means minutes.
- Naive scales with and the identity hardly does. Naive moves numbers through memory several times; the identity performs operations inside a matrix product, which reuses each loaded datum tens of times, and only elementwise work. Vectorizing is not only removing loops: how many times memory is traversed also matters.
- With blocks, the memory curve is flat: it depends on the budget, not . Time is the same because total work does not change; sometimes it even falls because a small block fits in cache.
The next cell checks the last claim by measuring peak memory with tracemalloc, which sees NumPy allocations:
import tracemalloc
def vecino_ingenuo(X, Y):
return dist2_ingenua(X, Y).argmin(axis=1)
def vecino_bloques(X, Y, max_bytes=2**22):
n, d = X.shape
m = len(Y)
b = max(1, max_bytes // (2 * m * d * 8)) # filas por bloque: el pico es 2 · b · m · d · 8 bytes
out = np.empty(n, dtype=np.intp)
for s in range(0, n, b):
out[s:s + b] = dist2_ingenua(X[s:s + b], Y).argmin(axis=1)
return out
def pico_memoria(f, *args):
tracemalloc.start()
f(*args)
pico = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
return pico
rng = np.random.default_rng(4)
X, Y = rng.standard_normal((1000, 16)), rng.standard_normal((800, 16))
print("mismo resultado:", np.array_equal(vecino_ingenuo(X, Y), vecino_bloques(X, Y)))
for f in (vecino_ingenuo, vecino_bloques):
print(f"{f.__name__:15s} pico {pico_memoria(f, X, Y) / 1e6:7.1f} MB tiempo {medir(f, X, Y) * 1e3:6.1f} ms")Fifty times less memory and the same time, or slightly less. This is the same idea, applied to hardware, behind FlashAttention’s tiled attention: a transformer’s attention matrix is never fully materialized either.
Where the speedup comes from
A Python loop adding two lists pays the same cost each iteration: find the next element, check its type, dispatch addition to the appropriate method, create a new float object for the result, and manage its reference count. That is tens or hundreds of nanoseconds per element for an addition the processor performs in less than one. A ufunc pays call overhead once (check shapes and dtypes, choose the loop, allocate output), then traverses contiguous memory in a C loop without intermediate objects. A simple cost model summarizes it:
For small , fixed overhead dominates and NumPy can be slower than Python; the crossover is at . Measured in the browser:
for n in (1, 10, 100, 1000, 10_000, 100_000):
a, b = np.ones(n), np.ones(n)
al, bl = a.tolist(), b.tolist()
t_np = medir(np.add, a, b, minimo=0.05)
t_py = medir(lambda: [p + q for p, q in zip(al, bl)], minimo=0.05)
print(f"n = {n:7d} NumPy {t_np * 1e6:8.1f} µs ({t_np / n * 1e9:7.1f} ns/elem) Python {t_py * 1e6:8.1f} µs ({t_py / n * 1e9:6.1f} ns/elem)")
pos = rng.standard_normal((300, 2))
d3 = lambda p: p[None, :, :] - p[:, None, :] # (N, N, 2)
d2 = lambda p: (p[None, :, 0] - p[:, None, 0], p[None, :, 1] - p[:, None, 1]) # dos (N, N)
print(f"(N, N, 2): {medir(d3, pos) * 1e3:.2f} ms dos (N, N): {medir(d2, pos) * 1e3:.2f} ms")The per-element columns tell the story: NumPy goes from microseconds per element to a few nanoseconds as fixed overhead is spread out, while Python stays at a constant per-element cost, roughly a hundred times higher. With one or ten elements both versions cost the same, a few microseconds: call overhead consumes the entire advantage. Vectorizing a loop over three-element arrays speeds up nothing.
The last line is subtler. Both expressions calculate the same differences, but the version is several times slower. A ufunc’s inner loop traverses the last axis of iteration, and NumPy merges consecutive axes only when the strides of all operands permit it. Here, with one operand of strides and another of , it cannot: the compiled loop runs only 2 iterations and the surrounding machinery is paid times. Separating coordinates gives inner loops of length . That is why fuerzas_vec uses two arrays instead of one : good vectorization gives each compiled call lots of contiguous work. Low-level details (cache lines, SIMD, prefetching) are covered in cache lines and locality.
When not to vectorize
Vectorization requires operations on elements to be independent of one another. When they are not, no array rewrite fixes that. A typical case is a recurrence: in the logistic map , step needs the result of step , so time is inevitably sequential. But there is almost always another independent axis: here, different values of . The practical rule is to vectorize the parallel axis and leave the loop on the sequential one.
import matplotlib.pyplot as plt
def logistica(r, x0=0.5, pasos=600, guardar=100):
x = np.full_like(r, x0) # (R,): una trayectoria por valor de r
for _ in range(pasos - guardar): # el tiempo es secuencial: x_{t+1} depende de x_t
x = r * x * (1 - x)
traza = np.empty((guardar, len(r))) # (T, R)
for t in range(guardar):
x = r * x * (1 - x)
traza[t] = x
return traza
r = np.linspace(2.5, 4.0, 800)
t0 = time.perf_counter(); traza = logistica(r, guardar=60); t_vec = time.perf_counter() - t0
t0 = time.perf_counter()
for rr in r[:40]: # el mismo cálculo con un bucle por trayectoria (solo 40 de 800)
xx = 0.5
for _ in range(600):
xx = rr * xx * (1 - xx)
t_py = (time.perf_counter() - t0) * len(r) / 40
print(f"vectorizado en r: {t_vec * 1e3:.0f} ms bucle doble (estimado): {t_py * 1e3:.0f} ms")
fig, ax = plt.subplots(figsize=(7, 3.6))
ax.plot(np.broadcast_to(r, traza.shape).ravel(), traza.ravel(), ",", alpha=0.35)
ax.set_xlabel("r"); ax.set_ylabel("x, últimos 60 de 600 pasos"); ax.set_title("Diagrama de bifurcación del mapa logístico")
plt.show()There is an important intermediate case: linear recurrences, such as the exponential moving average . They can be written in closed form using cumsum of terms rescaled by , but that form overflows on long series; use a specialized compiled loop such as scipy.signal.lfilter, or a parallel scan. This is covered in vectorizing linear recurrences.
And two false vectorizations worth recognizing:
relu2 = np.vectorize(lambda t: t * t if t > 0 else 0.0)
x = rng.standard_normal(100_000)
t_vec = medir(relu2, x)
t_lista = medir(lambda v: [t * t if t > 0 else 0.0 for t in v.tolist()], x)
t_where = medir(lambda v: np.where(v > 0, v * v, 0.0), x)
print(f"np.vectorize {t_vec * 1e3:6.1f} ms lista {t_lista * 1e3:6.1f} ms np.where {t_where * 1e3:6.2f} ms")np.vectorize is a Python loop with a ufunc interface: it accepts broadcasting and returns arrays, but calls your function once per element, and its own documentation says it is provided for convenience, not performance. Here it is even slower than the list comprehension, and fifty to a hundred times slower than np.where, which evaluates both branches over entire arrays. The same holds for DataFrame.apply(f, axis=1) in pandas: a loop in disguise.
Lab: N bodies
Return to the motivation and complete the simulation. Accelerations are now computed using the difference tensor , the most direct version of the formula, and integrated using leapfrog (kick-drift-kick), which conserves energy very well. In addition to speed, we measure how temporary memory grows as increases and write the chunked version.
def aceleraciones(pos, masa):
d = pos[None, :, :] - pos[:, None, :] # (N, N, 2): d[i, j] = x_j - x_i
r2 = (d * d).sum(axis=-1) + EPS2 # (N, N)
w = masa[None, :] / (r2 * np.sqrt(r2)) # (N, N)
np.fill_diagonal(w, 0.0)
return (w[:, :, None] * d).sum(axis=1) # (N, 2)
def aceleraciones_bloques(pos, masa, b=64):
a = np.empty_like(pos)
for s in range(0, len(pos), b): # b filas (partículas i) por bloque: temporales (b, N, 2)
d = pos[None, :, :] - pos[s:s + b, None, :]
r2 = (d * d).sum(axis=-1) + EPS2
w = masa[None, :] / (r2 * np.sqrt(r2))
w[np.arange(len(w)), np.arange(s, s + len(w))] = 0.0 # la "diagonal" del bloque
a[s:s + b] = (w[:, :, None] * d).sum(axis=1)
return a
def energia(pos, vel, masa):
d = pos[None, :, :] - pos[:, None, :]
r = np.sqrt((d * d).sum(axis=-1) + EPS2)
i, j = np.triu_indices(len(pos), 1) # cada pareja una vez
return 0.5 * (masa * (vel * vel).sum(axis=1)).sum() - (masa[i] * masa[j] / r[i, j]).sum()
rng = np.random.default_rng(5)
N = 200
pos = rng.standard_normal((N, 2))
vel = 0.3 * rng.standard_normal((N, 2))
masa = np.full(N, 1.0 / N)
vel -= (masa[:, None] * vel).sum(axis=0) / masa.sum() # centro de masas en reposo
print("bloques = completo:", np.allclose(aceleraciones_bloques(pos, masa), aceleraciones(pos, masa)))
E0, dt = energia(pos, vel, masa), 0.005
inicio = pos.copy()
a = aceleraciones(pos, masa)
t0 = time.perf_counter()
for paso in range(250): # leapfrog: medio impulso, deriva, medio impulso
vel += 0.5 * dt * a
pos += dt * vel
a = aceleraciones(pos, masa)
vel += 0.5 * dt * a
print(f"250 pasos con N = {N}: {time.perf_counter() - t0:.2f} s, deriva relativa de la energía {abs(energia(pos, vel, masa) - E0) / abs(E0):.1e}")
for n_ in (250, 500, 1000):
p_, m_ = rng.standard_normal((n_, 2)), np.full(n_, 1.0 / n_)
print(f"N = {n_:5d}: completo {medir(aceleraciones, p_, m_) * 1e3:6.1f} ms (temporal {n_ * n_ * 2 * 8 / 1e6:5.1f} MB)"
f" por bloques {medir(aceleraciones_bloques, p_, m_) * 1e3:6.1f} ms (temporal {64 * n_ * 2 * 8 / 1e6:4.1f} MB)")
fig, ax = plt.subplots(figsize=(5.5, 5))
ax.scatter(*inicio.T, s=6, alpha=0.35, label="inicio")
ax.scatter(*pos.T, s=8, label="tras 250 pasos")
ax.set_aspect("equal"); ax.legend(loc="upper right"); ax.set_title("200 cuerpos con gravedad suavizada")
plt.show()Time per step grows like , as does temporary memory: doubling quadruples both. The chunked version limits each temporary to bytes, linear in instead of quadratic, at practically the same cost. For truly large , even operations are unacceptable and tree or multipole algorithms are used, covered in N-body simulation.
Lab: softmax, log-sum-exp, and one-hot
We implement the three functions on arbitrary axes and check them against scipy.special. An edge case is not covered by the derivation: if every logit in a row is (a fully masked row, common in attention), the maximum is and gives nan. Solve it by replacing nonfinite maxima with zero before subtracting.
from scipy import special
def logsumexp(z, axis=-1, keepdims=False):
m = np.max(z, axis=axis, keepdims=True) # (..., 1, ...)
m = np.where(np.isfinite(m), m, 0.0) # filas de -inf: no restar -inf
with np.errstate(divide="ignore"): # log(0) = -inf es el resultado correcto
s = np.log(np.sum(np.exp(z - m), axis=axis, keepdims=True)) + m
return s if keepdims else np.squeeze(s, axis=axis)
def softmax(z, axis=-1):
e = np.exp(z - np.max(z, axis=axis, keepdims=True))
return e / e.sum(axis=axis, keepdims=True)
def one_hot(y, K):
return (y[:, None] == np.arange(K)[None, :]).astype(np.float64) # (n, 1) == (1, K) -> (n, K)
rng = np.random.default_rng(6)
Z = 30 * rng.standard_normal((4, 5, 7))
for ax in (0, 1, 2, (0, 2)):
assert np.allclose(logsumexp(Z, axis=ax), special.logsumexp(Z, axis=ax))
for ax in (0, 1, 2):
assert np.allclose(softmax(Z, axis=ax), special.softmax(Z, axis=ax))
print("coinciden con scipy.special en todos los ejes probados")
z = np.array([1000.0, 999.0, 990.0])
with np.errstate(over="ignore", invalid="ignore"):
print("ingenua:", np.exp(z) / np.exp(z).sum(), " estable:", softmax(z).round(6))
z32 = np.array([89.0, 88.0], dtype=np.float32)
with np.errstate(over="ignore"):
print("exp en float32:", np.exp(z32), " logsumexp:", logsumexp(z32))
print("fila enmascarada:", logsumexp(np.array([[-np.inf, -np.inf], [0.0, 0.0]]), axis=1))
logits = rng.standard_normal((6, 4)) # (n, K)
y = np.array([2, 0, 3, 3, 1, 0])
log_p = logits - logsumexp(logits, axis=1, keepdims=True) # log-softmax, (n, K)
ce_onehot = -(one_hot(y, 4) * log_p).sum(axis=1).mean()
ce_indices = -log_p[np.arange(len(y)), y].mean()
print("entropía cruzada:", ce_onehot, ce_indices, np.isclose(ce_onehot, ce_indices))log_p = logits - logsumexp(logits, keepdims=True) is log-softmax, how loss is calculated in practice: logits are never exponentiated only to take logarithms again. This is softmax cross-entropy loss on logits, and transformer attention applies the same row-wise softmax to a matrix of query-key dot products: conceptually, broadcasting against reduced over , in practice computed as matrix product without materializing the tensor, just like the distance identity. This is scaled dot-product attention.
Lab: the game of life
In Conway’s game of life, each board cell is alive or dead and, at each step, a live cell survives if it has 2 or 3 live neighbors and a dead one is born if it has exactly 3. Counting neighbors seems to require a loop with eight checks per cell. Vectorized, it is the sum of eight shifted views of the board surrounded by a zero border; and the rules are Boolean masks.
def vecinas(T):
"""Número de vecinas vivas de cada celda: suma de 8 vistas desplazadas del tablero con borde de ceros."""
P = np.pad(T, 1) # (H + 2, W + 2)
H, W = T.shape
return sum(P[1 + di:H + 1 + di, 1 + dj:W + 1 + dj]
for di in (-1, 0, 1) for dj in (-1, 0, 1) if (di, dj) != (0, 0))
def paso(T):
N = vecinas(T)
return ((N == 3) | ((T == 1) & (N == 2))).astype(np.uint8)
def paso_bucles(T):
H, W = len(T), len(T[0])
nuevo = [[0] * W for _ in range(H)]
for i in range(H):
for j in range(W):
n = 0
for di in (-1, 0, 1):
for dj in (-1, 0, 1):
if (di or dj) and 0 <= i + di < H and 0 <= j + dj < W:
n += T[i + di][j + dj]
nuevo[i][j] = 1 if n == 3 or (T[i][j] == 1 and n == 2) else 0
return nuevo
rng = np.random.default_rng(7)
T = (rng.random((64, 64)) < 0.3).astype(np.uint8)
print("misma evolución:", np.array_equal(paso(T), np.array(paso_bucles(T.tolist()))))
tb, tv = medir(paso_bucles, T.tolist()), medir(paso, T)
print(f"64 x 64: bucles {tb * 1e3:6.1f} ms NumPy {tv * 1e3:5.2f} ms x{tb / tv:.0f}")
T2 = (rng.random((512, 512)) < 0.3).astype(np.uint8)
print(f"512 x 512: NumPy {medir(paso, T2) * 1e3:.1f} ms (los bucles tardarían unas 64 veces lo de 64 x 64)")
G = np.zeros((12, 12), np.uint8)
G[1, 2] = G[2, 3] = G[3, 1] = G[3, 2] = G[3, 3] = 1 # un planeador
G4 = G
for _ in range(4):
G4 = paso(G4)
print("el planeador se desplaza (1, 1) cada 4 pasos:", np.array_equal(G4, np.roll(G, (1, 1), axis=(0, 1))))
for _ in range(60):
T2 = paso(T2)
fig, ax = plt.subplots(figsize=(4.5, 4.5))
ax.imshow(T2[:160, :160], cmap="gray_r", interpolation="nearest")
ax.set_xticks([]); ax.set_yticks([]); ax.set_title("Tras 60 pasos (esquina 160 x 160)")
plt.show()The views P[1 + di:H + 1 + di, ...] copy nothing: they are the same buffer with another offset, as seen in views versus copies. The sums are what get created. The rules, (N == 3) | ((T == 1) & (N == 2)), are three comparisons and two logical operations over whole boards. Counting neighbors is convolution with a kernel of ones with zero at the center, and that is how to write it with a library, as in the next section.
The professional version
Everything you implemented has a library version, more thoroughly tested and often faster. Knowing the from-scratch version lets you choose well and understand what it does inside:
from scipy.spatial.distance import cdist
from scipy.ndimage import convolve
rng = np.random.default_rng(8)
X, Y = rng.standard_normal((1000, 16)), rng.standard_normal((800, 16))
D = cdist(X, Y, "sqeuclidean") # bucle en C, sin cancelación
print("cdist = identidad:", np.allclose(D, np.maximum(dist2_producto(X, Y), 0)))
nucleo = np.ones((3, 3), dtype=np.uint8); nucleo[1, 1] = 0
print("vecinas por convolución:", np.array_equal(convolve(T, nucleo, mode="constant"), vecinas(T)))
print("logsumexp:", special.logsumexp(Z, axis=1).shape, " softmax:", special.softmax(Z, axis=-1).sum(axis=-1).round(12).max())from sklearn.metrics import pairwise_distances_argmin, pairwise_distances_chunked
print("vecino más cercano:", np.array_equal(pairwise_distances_argmin(X, Y), vecino_bloques(X, Y)))
# bloques con un presupuesto de memoria (working_memory, en MiB) y una reducción dentro de cada bloque
bloques = pairwise_distances_chunked(X, Y, reduce_func=lambda Dc, inicio: Dc.argmin(axis=1), working_memory=1)
print("por bloques:", np.array_equal(np.concatenate(list(bloques)), vecino_bloques(X, Y)))cdist traverses pairs with a double loop in C, without intermediate tensors or cancellation, and is the most accurate option; for large , the identity with a matrix product is usually faster. Scikit-learn’s pairwise_distances_chunked is exactly chunked vectorization: working_memory is budget and reduce_func the reduction performed within each block.
In PyTorch the broadcasting rules are identical, and the same errors appear with different syntax: torch.cdist, torch.logsumexp(z, dim=k, keepdim=True) and torch.softmax(z, dim=k) replace their equivalents, with dim instead of axis and singular keepdim.
import torch
x = torch.randn(32, 3, 224, 224) # (N, C, H, W)
mu = x.mean(dim=(0, 2, 3), keepdim=True) # (1, 3, 1, 1)
sd = x.std(dim=(0, 2, 3), keepdim=True)
x_norm = (x - mu) / sd # mismas reglas que NumPy
print(torch.broadcast_shapes((8, 1, 6, 1), (7, 1, 5))) # torch.Size([8, 7, 6, 5])
You will see this in detail in the PyTorch tensors lesson. There and on the GPU, per-call overhead is even higher (each operation launches a kernel), and vectorization becomes the only reasonable way to write code.
Common mistakes
Exercises
a + b for the indicated shapes or says it errors.More than one answer may be correct.
a = np.zeros((3, 1)) is float64 and contiguous. What are the strides of np.broadcast_to(a, (2, 3, 4))?X has shape . What does X - X.mean(axis=1) do?x has shape (32, 3, 224, 224), in (N, C, H, W) order. Which lines correctly normalize each channel using its mean and standard deviation over the batch and pixels?More than one answer may be correct.
X[:, None, :] - Y[None, :, :] with , , in float64. How many GB ( bytes) does that intermediate tensor occupy?x is an array of a million floats. Which expressions traverse elements in compiled code without calling a Python function per element?More than one answer may be correct.
pairwise_sq_dists(X, Y), receiving X of shape and Y of shape and returning the matrix of squared Euclidean distances, without Python loops or creating any tensor: use the dot-product identity and clip negative values caused by rounding to zero. Tests compare with scipy.spatial.distance.cdist, check for no negative values with points far from the origin, and measure peak memory.import numpy as np
def pairwise_sq_dists(X, Y):
# ||x - y||² = ||x||² + ||y||² - 2 x·y, con broadcasting
passnearest_neighbor(X, Y, max_bytes), returning an integer array of length with the index of the row of Y nearest (in Euclidean distance) to each row of X. It must process X in row blocks so peak additional memory, measured with tracemalloc, does not exceed max_bytes (plus an allowance of bytes and 64 kB for the result and auxiliary vectors). Assume max_bytes is at least .import numpy as np
def nearest_neighbor(X, Y, max_bytes):
# elige b filas por bloque según max_bytes y reduce con argmin dentro de cada bloque
passStep 1 of 5. Why is studying one axis enough?
Summary
keepdims to return to the original shape. Temporary memory is the price, controlled by reformulating or processing in blocks.- The rules: align on the right, pad with ones on the left, equal or one on each axis; the result size is the one that is not 1. A vector acts as a row; for a column,
v[:, None]. - Think in shapes: annotate each variable’s shape, assign an axis to each free index, and reduce summed indices. Beware square matrices and subtractions, which raise no error.
- ufuncs: elementwise functions with broadcasting and
reduce,accumulate,outer, andatmethods. Reduced axes disappear unlesskeepdims=True; without it they recombine correctly only if they were first. - Patterns: pairwise distances with the dot-product identity (beware cancellation: clip and center), normalization with
keepdims, softmax and log-sum-exp subtracting the maximum, one-hot with a broadcast comparison. - Memory: naive broadcasting creates tensors occupying the product of their shape times 8 bytes (in float64); with blocks, peak memory depends on the budget rather than , with the same time.
- Limits: speedup comes from paying interpreter overhead once per call rather than once per element; nonlinear recurrences cannot be vectorized over time (vectorize another axis), and
np.vectorizeorapplyare not vectorization.