Module contents
Lesson 5 of 24Core 90 min

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 jj exerts on ii points from xi\vb{x}_i to xj\vb{x}_j and decays with the square of the distance; summing over all the others,

Fi=∑j≠imimj (xj−xi)(∥xj−xi∥2+ε2)3/2,\vb{F}_i = \sum_{j \ne i} \frac{m_i m_j\,(\vb{x}_j - \vb{x}_i)}{\big(\norm{\vb{x}_j - \vb{x}_i}^2 + \eps^2\big)^{3/2}},

where ε\eps 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 (N,N)(N, N) containing all pairs at once.

[ ]Pairwise forces: loops versus arraysBrowser
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 (1,N)(1, N) and one of shape (N,1)(N, 1) and obtains a matrix (N,N)(N, N). 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 (3,1)(3, 1) plus a row of shape (4,)(4,).

[ ]Stretching without copyingBrowser
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 cij=ai+bjc_{ij} = a_i + b_j: 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: (0,1)(0, 1) with (1,4)(1, 4) gives (0,4)(0, 4), not (1,4)(1, 4). 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 (d,)(d,) behaves as a row (1,d)(1, d), never as a column. To make it act as a column, say so: v[:, None].
  • The index π\pi is exactly what zero strides do. The memory address of A[i]\mat{A}[\vb{i}] is offset+∑kiksk\text{offset} + \sum_k i_k s_k; with sk=0s_k = 0 coordinate iki_k disappears from the sum, the same as replacing it with 00. 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 (3,4)(3, 4), 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.

InteractiveThe shape aligner
axis -2
axis -1
A
3
1
B
1
4
1 → 3
1 → 4
=
3
4
Strides (bytes) for each operand as viewed in the result shape with np.broadcast_to:
A
8
0
B
0
8
Both axes. Dashed cells refer to the solid cell in their row or column and occupy no separate memory.
A
0
0
0
0
1
1
1
1
2
2
2
2
B
0
10
20
30
0
10
20
30
0
10
20
30
result
Values: A contributes units, B contributes tens.
Result shape(3, 4)
Result elements12
Elements stored in A and B3 and 4
Enter two or three shapes, or choose an example. The table aligns them on the right, pads with ones on the left (dashed gray), and marks each axis: equal, stretched (hatched), or incompatible (red). Under ‘Strides’ see each operand's strides viewed with the result shape: 0 on each stretched or added axis. In the cell map, dashed cells do not exist in memory; hover over a result cell to see which real cell each operand reads. Try the documentation example, the (n, 1) prediction, and the three-operand example.

What you should have seen:

  • Padding ones appear only on the left. With (2,3,4,5)(2, 3, 4, 5) and (3,)(3,), the 33 aligns with width 55, not the channel. This is the most frequent mistake when normalizing images by channel; fix it by giving shape (1,3,1,1)(1, 3, 1, 1), or (3,1,1)(3, 1, 1), which is the same after padding.
  • Each zero stride is an axis that occupies no memory. In the documentation example, the result has 8⋅7⋅6⋅5=16808 \cdot 7 \cdot 6 \cdot 5 = 1680 elements and the operands store 4848 and 3535.
  • The map shows the π\pi formula. Result cell (i,j)(i, j) reads row ii of an operand of shape (R,1)(R, 1) but column 00, whatever jj is.
  • The most dangerous broadcasting raises no error. A (5,1)(5, 1) prediction minus a (5,)(5,) target produces a (5,5)(5, 5) 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 (or np.newaxis) in an index adds a size-1 axis without copying anything: if v has shape (n,)(n,), v[:, None] is (n,1)(n, 1) and v[None, :] is (1,n)(1, n). This says “this dimension will be stretched.”
  • keepdims=True in 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 (n,1)(n, 1) and can be subtracted from or divided into X.
  • 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, ii and jj; therefore fuerzas_vec puts ii on axis 0 (x[:, None]) and jj on axis 1 (x[None, :]), operates on (N,N)(N, N) arrays, and ends with a .sum(axis=1) reduction, the formula’s ∑j\sum_j. 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.

[ ]Two silent failuresBrowser
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 (4,4)(4, 4) and (4,)(4,) 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 (4,3)(4, 3) 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.

InteractiveWhich axis am I reducing?
  • x (darker means larger)
  • r: result
Array
Operation
r = x.sum(axis=1)
Shape of x(4, 3, 5)
Shape of r(4, 5)
Values per output3
x − r: ValueError: operands could not be broadcast together with shapes (4,3,5) (4,5)
An array of shape (4, 3, 5); x[0, 0, 0] is the top front left corner. Choose axes and operation: cells travel along reduced axes (marked ✕) to the result, positioned where it would be with keepdims=True. Readouts give the result shape and check the next operation, x − r. For which axes does x − r work without keepdims? In ‘Images’ mode, a batch (N, C, H, W): the mean per channel and why normalization fails without keepdims.

What you should have seen:

  • Reducing axis kk collapses cells along kk, not “in direction kk” in a mental table: with axis=1 each output combines the 3 rows of one column within a block. One output per combination of the axes that remain.
  • Without keepdims, x - r only does the right thing if the reduced axes are the first ones. With axis=0, the result (3,5)(3, 5) aligns on the right with (4,3,5)(4, 3, 5) and broadcasting puts it back. With axis=1 or axis=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=True always works.
  • argmax returns positions, not values, and only accepts one axis. With axis=None it returns an index on the flattened array, which np.unravel_index converts to coordinates.
  • In the image batch, the mean per channel is x.mean(axis=(0, 2, 3)), of shape (C,)(C,), which aligns with width WW. With keepdims=True it is (1,C,1,1)(1, C, 1, 1) and normalization (x - mu) / sd is 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:

[ ]Reductions, accumulations, and a drawdownBrowser
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, 1−Pt/max⁡s≤tPs1 - P_t / \max_{s \le t} P_s, involves a cumulative maximum: with np.maximum.accumulate it is one loop-free line. np.logaddexp.reduce computes log⁡∑iezi\log\sum_i e^{z_i} without overflow, the subject of the next section.

Classic patterns

Pairwise distances

Given two point clouds X∈Rn×d\mat{X} \in \R^{n \times d} and Y∈Rm×d\mat{Y} \in \R^{m \times d} (one point per row), the matrix of squared distances Dij=∥xi−yj∥2D_{ij} = \norm{\vb{x}_i - \vb{y}_j}^2 appears in kk-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:

  1. Double loop: nmnm interpreter iterations, each with a NumPy operation on vectors of length dd.
  2. Naive broadcasting: X[:, None, :] - Y[None, :, :] has shape (n,m,d)(n, m, d); square it and sum along the last axis. Zero loops, but an intermediate tensor of nmdnmd numbers.
  3. Dot-product identity: expanding the square,
∥xi−yj∥2=∥xi∥2+∥yj∥2−2 xi⊤yj,es decir,D=sX1⊤+1 sY⊤−2 XY⊤,\norm{\vb{x}_i - \vb{y}_j}^2 = \norm{\vb{x}_i}^2 + \norm{\vb{y}_j}^2 - 2\,\vb{x}_i\T\vb{y}_j, \qquad\text{es decir,}\qquad \mat{D} = \vb{s}_X \mathbf{1}\T + \mathbf{1}\,\vb{s}_Y\T - 2\,\mat{X}\mat{Y}\T,

with sX=(∥xi∥2)i∈Rn\vb{s}_X = (\norm{\vb{x}_i}^2)_i \in \R^n and sY∈Rm\vb{s}_Y \in \R^m. 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 O(nm)\bigO(nm) instead of O(nmd)\bigO(nmd), 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.

[ ]Three distance methods and cancellationBrowser
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, ∥x∥2\norm{\vb{x}}^2 and ∥y∥2\norm{\vb{y}}^2 are huge numbers nearly equal to 2 x⊤y2\,\vb{x}\T\vb{y}, and their difference loses almost all significant digits: catastrophic cancellation. With coordinates on the order of 10510^5, each term is on the order of 3⋅10103 \cdot 10^{10} and its rounding error on the order of εmaˊq⋅3⋅1010≈7⋅10−6\eps_{\text{máq}} \cdot 3 \cdot 10^{10} \approx 7 \cdot 10^{-6}, only about a hundred times smaller than typical squared distances, on the order of 5⋅10−45 \cdot 10^{-4}, 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 (d,)(d,) is padded to (1,d)(1, d) and returns to its place. The first reduces axis 1 and needs it; without it, (n,d)(n, d) divided by (n,)(n,) fails or, if n=dn = d, 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) z∈RK\vb{z} \in \R^K into probabilities, and log-sum-exp is the logarithm of its denominator:

softmax⁡(z)k=ezk∑l=1Kezl,LSE⁡(z)=log⁡∑l=1Kezl.\softmax(\vb{z})_k = \frac{e^{z_k}}{\sum_{l=1}^{K} e^{z_l}}, \qquad \operatorname{LSE}(\vb{z}) = \log \sum_{l=1}^{K} e^{z_l}.

Computed directly, they fail when logits are large: eze^{z} overflows to inf in float64 for z>709.78z > 709.78, and in float32 for z>88.72z > 88.72, leaving inf / inf = nan. If all logits are very negative the opposite happens: all exponentials round to 00 and leave 0 / 0. The solution follows from a property worth deriving:

softmax⁡(z−c1)k=e−c ezke−c∑lezl\softmax(\vb{z} - c\mathbf{1})_k = \frac{e^{-c}\,e^{z_k}}{e^{-c}\sum_l e^{z_l}}
Subtracting the same constant cc from all logits factors out e−ce^{-c} from numerator and denominator.
1/6

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.

InteractiveSubtracting the maximum
z1z_{1}
2.0
z2z_{2}
1.0
z3z_{3}
0.1
z4z_{4}
−0.5
z5z_{5}
1.5
Naive: exp(z) / sum(exp(z))01Stable: exp(z − max z) / sum(exp(z − max z))010.4530.1670.0680.0370.2750.4530.1670.0680.0370.275
  • class 1
  • class 2
  • class 3
  • class 4
  • class 5
Type
× 1
0
max⁡kzk\max_k z_k2.00
∑kezk\sum_k e^{z_k} (naive)16.301
∑kezk−max⁡z\sum_k e^{z_k - \max z}2.206
naive logsumexp2.791
stable logsumexp2.791
Both implementations agree. Moving cc leaves the stable one unchanged because softmax is shift invariant.
The logits are zk=s bk+cz_k = s\,b_k + c, with fixed shape bb. The top row computes softmax directly; the bottom subtracts the maximum. Increase scale ss or move offset cc toward extremes until the naive version produces nan from overflow or underflow. Notice that the stable version does not change as cc moves and stable logsumexp remains exact. Switch to float64: the limit changes from about 88.7 to about 709.8, but does not disappear.

One-hot

Encoding labels yi∈{0,…,K−1}y_i \in \{0, \dots, K-1\} as vectors with a single 1 broadcasts a comparison: a (n,1)(n, 1) column of labels against a (1,K)(1, K) row of classes gives a Boolean matrix (n,K)(n, K).

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 n⋅m⋅dn \cdot m \cdot d numbers. With n=m=5000n = m = 5000 and d=64d = 64, in float64, that is 1.6⋅1091.6 \cdot 10^9 elements and 12.812.8 GB, and in practice the peak is double because the difference and its square coexist briefly before the difference is freed. With n=104n = 10^4 it no longer fits in 32 GB RAM: the “most vectorized” version is the only one that does not finish. The identity needs O(nm)\bigO(nm), but even O(nm)\bigO(nm) stops fitting when nn and mm are on the order of 10510^5.

The solution is never to materialize the entire tensor:

The Python loop still exists, but runs ⌈n/b⌉\lceil n / b \rceil times instead of nmnm, 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 (n,m)(n, m) matrix never exists either.

InteractivePairwise distances: time versus memory
Task: find the nearest neighbor of each of the n=5 000n = 5\,000 rows of X\mat{X} among the m=5 000m = 5\,000 rows of Y\mat{Y} in R64\R^{64}, using float64.
Estimated timePeak memory (vertical mark: 32 GB of RAM)
Nested loopsfor i, j: np.sum((X[i] - Y[j])**2)
3.4 min
40.0 kB
Naive broadcasting((X[:, None] - Y[None])**2).sum(-1)
14 s
25.6 GB
Dot-product identityxx[:, None] + yy - 2 * X @ Y.T
332 ms
600 MB
1 ms1 s1 min1 h1 day
1 MB1 GB1 TB
Peak memory against nn with fixed mm and dd
  • Nested loops
  • Naive broadcasting
  • Dot-product identity
  • RAM (32 GB)
Sizes
5 000
5 000
64
Inputs X\mat{X}, Y\mat{Y}5.1 MB
Intermediate tensor (n,m,d)(n, m, d)12.8 GB
Naive vs. identity× 41 slower
Three nearest-neighbor implementations. Times are a model calibrated with real measurements on a laptop (CPython 3.13 and NumPy 2.5, not in the browser); peak memory is measured with tracemalloc: 2nmd⋅82nmd \cdot 8 bytes for naive and 3nm⋅83nm \cdot 8 for the identity. The vertical mark on memory bars indicates 32 GB RAM. Take the naive version beyond RAM and enable ‘Chunked’: memory flattens at the budget and time barely changes. Also lower dd to 2 and raise it to 1024: why, with large dd, is naive tens or hundreds of times slower than the identity even though both are vectorized?

What you should have seen:

  • The double loop uses least memory and takes longest: a few microseconds per pair, which with 2525 million pairs means minutes.
  • Naive scales with dd and the identity hardly does. Naive moves nmdnmd numbers through memory several times; the identity performs 2nmd2nmd operations inside a matrix product, which reuses each loaded datum tens of times, and only O(nm)\bigO(nm) 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 nn. 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:

[ ]Chunked nearest neighborBrowser
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 T×TT \times T 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:

TPython(n)≈cpy n,TNumPy(n)≈c0+cC n,cC≪cpy.T_{\text{Python}}(n) \approx c_{\text{py}}\, n, \qquad T_{\text{NumPy}}(n) \approx c_0 + c_{\text{C}}\, n, \qquad c_{\text{C}} \ll c_{\text{py}}.

For small nn, fixed overhead c0c_0 dominates and NumPy can be slower than Python; the crossover is at n⋆≈c0/(cpy−cC)n^\star \approx c_0 / (c_{\text{py}} - c_{\text{C}}). Measured in the browser:

[ ]Fixed overhead versus per-element costBrowser
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 (N,N,2)(N, N, 2) 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 (0,16,8)(0, 16, 8) and another of (16,0,8)(16, 0, 8), it cannot: the compiled loop runs only 2 iterations and the surrounding machinery is paid N2N^2 times. Separating coordinates gives inner loops of length NN. That is why fuerzas_vec uses two (N,N)(N, N) arrays instead of one (N,N,2)(N, N, 2): 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 xt+1=r xt(1−xt)x_{t+1} = r\,x_t(1 - x_t), step t+1t + 1 needs the result of step tt, so time is inevitably sequential. But there is almost always another independent axis: here, different values of rr. The practical rule is to vectorize the parallel axis and leave the loop on the sequential one.

[ ]Loop over time, vector over parametersBrowser
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 yt=α yt−1+(1−α) xty_t = \alpha\,y_{t-1} + (1 - \alpha)\,x_t. They can be written in closed form using cumsum of terms rescaled by α−t\alpha^{-t}, 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:

[ ]np.vectorize is not vectorizationBrowser
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 (N,N,2)(N, N, 2), 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 NN increases and write the chunked version.

[ ]Vectorized N bodiesBrowser
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 N2N^2, as does temporary memory: doubling NN quadruples both. The chunked version limits each temporary to 64⋅N⋅2⋅864 \cdot N \cdot 2 \cdot 8 bytes, linear in NN instead of quadratic, at practically the same cost. For truly large NN, even O(N2)\bigO(N^2) 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 −∞-\infty (a fully masked row, common in attention), the maximum is −∞-\infty and z−mz - m gives nan. Solve it by replacing nonfinite maxima with zero before subtracting.

[ ]Stable softmax and log-sum-exp on any axisBrowser
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 (T,1,d)(T, 1, d) against (1,T,d)(1, T, d) reduced over dd, in practice computed as matrix product QK⊤\mat{Q}\mat{K}\T 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.

[ ]Life without loopsBrowser
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 3×33 \times 3 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:

[ ]The same operations with SciPyBrowser
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())
[ ]Blocks with scikit-learnBrowser
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 dd, the identity with a matrix product is usually faster. Scikit-learn’s pairwise_distances_chunked is exactly chunked vectorization: working_memory is budget MM 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

QuizFive shape pairs
Which statements are correct? Each gives the shape of a + b for the indicated shapes or says it errors.

More than one answer may be correct.

QuizStrides of a broadcast view
a = np.zeros((3, 1)) is float64 and contiguous. What are the strides of np.broadcast_to(a, (2, 3, 4))?
QuizCentering rows of a square matrix
X has shape (n,n)(n, n). What does X - X.mean(axis=1) do?
QuizNormalizing an image batch
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.

NumericThe tensor that does not fit
You compute X[:, None, :] - Y[None, :, :] with n=10 000n = 10\,000, m=5 000m = 5\,000, d=64d = 64 in float64. How many GB (10910^9 bytes) does that intermediate tensor occupy?
NumericChoosing block size
With naive chunking, a block of bb rows of X\mat{X} peaks at 2⋅b⋅m⋅d⋅82 \cdot b \cdot m \cdot d \cdot 8 bytes. With m=5 000m = 5\,000, d=64d = 64 and a 2 GB budget (2⋅1092 \cdot 10^9 bytes), what is the maximum number of rows per block?
QuizWhat is truly vectorized?
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.

QuizA linear recurrence
You want the exponential moving average yt=α yt−1+(1−α) xty_t = \alpha\,y_{t-1} + (1 - \alpha)\,x_t, with y0=(1−α) x0y_0 = (1 - \alpha)\,x_0 and 0<α<10 < \alpha < 1, of a series of 10610^6 values. Which statement is correct?
CodeSquared distances without loops
Implement pairwise_sq_dists(X, Y), receiving X of shape (n,d)(n, d) and Y of shape (m,d)(m, d) and returning the (n,m)(n, m) matrix of squared Euclidean distances, without Python loops or creating any (n,m,d)(n, m, d) 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
  pass
Shift+Enter to run
CodeNearest neighbor with a memory budget
Implement nearest_neighbor(X, Y, max_bytes), returning an integer array of length nn 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 2n⋅82n \cdot 8 bytes and 64 kB for the result and auxiliary vectors). Assume max_bytes is at least 4m⋅84 m \cdot 8.
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
  pass
Shift+Enter to run
ProofShape broadcasting is commutative and associative
Prove: Let ⊔\sqcup be the partial operation assigning two compatible shapes their broadcast result shape. Then a⊔b=b⊔a\vb{a} \sqcup \vb{b} = \vb{b} \sqcup \vb{a}, and (a⊔b)⊔c=a⊔(b⊔c)(\vb{a} \sqcup \vb{b}) \sqcup \vb{c} = \vb{a} \sqcup (\vb{b} \sqcup \vb{c}), in the sense that one side is defined if and only if the other is, and then they agree.
0
By the rules, a⊔b\vb{a} \sqcup \vb{b} is calculated by padding with ones on the left to a common length and applying the partial integer operation axis by axis: x⊔y=yx \sqcup y = y if x=1x = 1; xx if y=1y = 1 or x=yx = y; undefined otherwise.

Step 1 of 5. Why is studying one axis enough?

Summary

Key idea
Vectorization gives each compiled call lots of work: one axis per loop index, broadcasting to combine arrays of different shapes without copying (stretched axes have stride 0), and reductions with 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 (d,)(d,) 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 (n,1)−(n,)(n, 1) - (n,) subtractions, which raise no error.
  • ufuncs: elementwise functions with broadcasting and reduce, accumulate, outer, and at methods. Reduced axes disappear unless keepdims=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 nn, 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.vectorize or apply are not vectorization.