Sub topic 14
Vectorization and Memory Cost
This chapter assumes you know how to create arrays, apply universal functions (ufuncs) and reductions, and read the shape rules for broadcasting from earlier chapters. It covers why replacing a Python loop with an array expression is fast, and what that speed costs in memory. It also covers how to keep the cost under control.
What vectorization means
Vectorization means writing an operation on whole arrays so the loop runs inside NumPy's compiled code instead of in the Python interpreter. a + b, np.sqrt(a) and x.sum(axis=0) are all vectorized. Each one is a single Python call that loops over the data in C.
Here is the same computation, the sum of squares, written both ways.
import timeit
import numpy as np
x = np.random.default_rng(0).random(1_000_000)
def loop_sum_squares(values):
total = 0.0
for v in values:
total += v * v
return total
def vector_sum_squares(values):
return float(np.dot(values, values))
print(np.isclose(loop_sum_squares(x), vector_sum_squares(x))) # True
t_loop = timeit.timeit(lambda: loop_sum_squares(x), number=3)
t_vec = timeit.timeit(lambda: vector_sum_squares(x), number=3)
print(f"loop: {t_loop:.3f}s vectorized: {t_vec:.5f}s ratio: {t_loop / t_vec:.0f}x")The exact ratio depends on your machine. For simple arithmetic on a million elements it is usually one to three orders of magnitude.
Why the loop is slow
The Python loop pays several costs on every element.
- Iterating over an
ndarraycreates a new Python float object for each element. - The interpreter looks up the type of
vand dispatches*and+at run time. - Each intermediate result is a new Python object that must be allocated and freed.
A ufunc avoids all of this. It checks the dtype once, picks a compiled inner loop for that dtype, and runs it over a contiguous block of raw numbers. Contiguous data also helps the CPU, which can prefetch memory and use SIMD instructions (one instruction acting on several numbers at once).
Where the memory cost comes from
Vectorized code is fast partly because it does work in bulk, and bulk work needs bulk storage. An array uses size * itemsize bytes, which you can read from nbytes. Every expression that produces an array allocates a new one.
Consider a * 2 + 1. Evaluated naively, a * 2 allocates a temporary array, and + 1 allocates a second array for the result. With three operations chained, you can have several full-size arrays alive at once. NumPy can sometimes reuse a temporary for large arrays, but you should not rely on that.
You can avoid the extra allocations with in-place operations and the out= argument.
import numpy as np
a = np.ones(1_000_000)
print(a.nbytes) # 8000000
out = np.empty_like(a)
np.multiply(a, 2, out=out) # writes into out, no new array
np.add(out, 1, out=out) # in place again
a *= 2 # augmented assignment modifies a itself
a += 1
ints = np.arange(5)
try:
ints += 0.5 # float result cannot be stored in an int array
except TypeError as err:
print("error:", type(err).__name__) # UFuncTypeErrorThree details matter here.
- In-place operators overwrite the original data. Any view of that array sees the change.
- In-place operations keep the destination dtype. NumPy refuses to cast float results into an integer array under its default
same_kindcasting rule, so you get aUFuncTypeError, a subclass ofTypeError. Create the array with the dtype you need. - The temporaries saved here only matter for large arrays. For arrays of a few thousand elements, readable code is better than clever code.
Broadcasting is free until you materialize it
Broadcasting does not copy the smaller array. NumPy treats a size-1 or missing axis as if it were repeated, by giving that axis a stride of 0. You can see this with np.broadcast_to.
import numpy as np
row = np.arange(4)
big = np.broadcast_to(row, (1000, 4))
print(big.strides, big.flags.writeable) # (0, 8) FalseThe (0, 8) strides show that stepping down a row moves 0 bytes. That array looks like 1000 rows but stores only the 4 original numbers. The result of an operation, however, is a real array. big + 1 allocates all 4000 elements. So the memory cost of broadcasting is the size of the output, plus any intermediate arrays with the broadcast shape.
Worked example: pairwise distances
The pairwise distance example from the broadcasting chapter is compact, but its intermediate array is where the cost hides. For n points in d dimensions, diff has shape (n, n, d).
import numpy as np
def pairwise_broadcast(pts):
diff = pts[:, np.newaxis, :] - pts[np.newaxis, :, :] # (n, n, d)
return np.sqrt((diff ** 2).sum(axis=-1)) # (n, n)
def pairwise_gram(pts):
sq = (pts ** 2).sum(axis=1) # (n,)
d2 = sq[:, np.newaxis] + sq[np.newaxis, :] - 2.0 * (pts @ pts.T)
return np.sqrt(np.maximum(d2, 0.0)) # clip rounding noise
def pairwise_chunked(pts, chunk=256):
n = len(pts)
out = np.empty((n, n))
for start in range(0, n, chunk):
block = pts[start:start + chunk] # (m, d)
diff = block[:, np.newaxis, :] - pts[np.newaxis, :, :]
out[start:start + chunk] = np.sqrt((diff ** 2).sum(axis=-1))
return out
pts = np.random.default_rng(1).random((500, 3))
a = pairwise_broadcast(pts)
print(np.allclose(a, pairwise_gram(pts), atol=1e-6)) # True
print(np.allclose(a, pairwise_chunked(pts))) # True
n, d = 10_000, 3
print(n * n * d * 8 / 1e9) # 2.4 (GB for diff alone, float64)For 10,000 points, diff alone needs 2.4 GB, and diff ** 2 needs another 2.4 GB. The result (n, n) is only 0.8 GB. The table compares the three approaches.
| Approach | Largest intermediate | Trade-off |
|---|---|---|
| Full broadcast | `(n, n, d)` | Simplest code. Memory grows with `d`. |
| Gram matrix with `@` | `(n, n)` | Fast and lean. Rounding can give tiny negative squared distances, so clip them. Accuracy drops for nearly identical points. |
| Chunked broadcast | `(chunk, n, d)` | Exact arithmetic, bounded memory, with a short Python loop over blocks. |
The chunked version still has a Python loop. That is fine, because the loop runs n / chunk times, not n * n times, and each pass does a lot of work. A loop over blocks is a normal compromise when the whole problem does not fit in memory.
Other ways to reduce memory
- Use a smaller dtype.
float32uses half the memory offloat64. Be aware that it carries about 7 significant decimal digits, so long sums can lose accuracy. - Reduce early. Compute
x.sum(axis=0)on the data you have instead of building a larger intermediate and reducing afterward. - Prefer views. Basic slices and
reshapeof a contiguous array do not copy. Boolean masks, integer-array indexing and.copy()do. - Delete large temporaries. Use
del diffor let the variable go out of scope before the next big allocation. - Check shapes before running. Multiply the broadcast result shape by
itemsizeto estimate memory before you start the computation.
When not to vectorize
Vectorization is a tool, not a goal. Keep a loop when:
- Each step depends on the result of the previous one, such as a recurrence or a simulation with state. Look for a built-in such as
np.cumsumornp.cumprodfirst, then consider Numba or Cython. - The arrays are tiny. Every NumPy call has a fixed overhead of about a microsecond, so plain Python can win for a handful of elements.
- The vectorized form needs an intermediate array too large to hold in memory.
- The vectorized form is so hard to read that nobody can check it.
Common mistakes
- Timing once on a small array. Measure with
timeiton realistic sizes, and run each version several times. - Assuming broadcasting is free. The inputs are cheap, but the output and any intermediates have the full broadcast shape.
- Using
+=on an int array with float data. This raises an error. Create the array withdtype=float. - Modifying a view in place by accident.
a[:, 1] *= 2changes the original array. - Trusting the Gram trick near zero. Clip negative values before
sqrt, and use the exact form if tiny distances matter.
Exercise
You have 20,000 points with 2 coordinates each, stored as float64 in an array pts of shape (20000, 2). You compute diff = pts[:, np.newaxis, :] - pts[np.newaxis, :, :]. What is the shape of diff, and about how much memory does it need? Name one way to compute the full distance matrix without allocating diff.
Show answer
The shape is (20000, 20000, 2). That is 800,000,000 elements, and at 8 bytes each it needs about 6.4 GB. The distance matrix itself, shape (20000, 20000), is 3.2 GB, which is already large. To avoid diff, use the Gram-matrix form with pts @ pts.T and clip negative squared distances before np.sqrt. You could also process the rows in chunks so that only a (chunk, 20000, 2) intermediate exists at a time. Using float32 halves every figure.