Sub topic 14
Vectorization and memory cost
This chapter assumes you can index and slice arrays, apply ufuncs and reductions, and read the broadcasting rules from earlier chapters. It covers why array expressions beat Python loops, and what that speed costs in memory.
What vectorization means
A vectorized expression hands a whole array to one NumPy function. The loop over elements then runs in compiled C code instead of the Python interpreter. Each pass through a Python loop pays for type checks and object creation. The compiled loop works on raw numbers stored next to each other in memory.
import time
import numpy as np
x = np.random.default_rng(0).random(1_000_000)
t0 = time.perf_counter()
total_loop = 0.0
for v in x:
total_loop += v * v
t1 = time.perf_counter()
total_vec = (x * x).sum()
t2 = time.perf_counter()
print(np.isclose(total_loop, total_vec)) # True
print(f"loop: {t1 - t0:.3f}s, vectorized: {t2 - t1:.3f}s")The two results agree. The timings depend on your machine, but the vectorized version is usually tens of times faster.
The hidden cost: temporaries
Every intermediate result in an expression is a real array. In (x * x).sum(), NumPy first builds x * x in full, then sums it. For one million floats that is 8 MB, which is harmless. Broadcasting can make the temporary much larger than the inputs.
Take the pairwise-distance idea from the previous chapter. The difference array has shape (n, n, d), even though the input has only n * d values.
import numpy as np
n, d = 2000, 3
pts = np.random.default_rng(0).random((n, d))
diff = pts[:, np.newaxis, :] - pts[np.newaxis, :, :]
print(diff.shape) # (2000, 2000, 3)
print(diff.nbytes / 1e6) # 96.0 (megabytes)The input holds 6,000 numbers. The temporary holds 12 million. Memory grows with n squared. At n = 10_000 the difference array alone needs 2.4 GB, and diff ** 2 allocates another array of the same size.
flowchart LRKeeping memory under control
Three techniques cover most cases.
- Work in blocks. Process a slice of rows at a time so the temporary stays small.
- Reuse buffers. Use in-place operators such as
x *= 2, or passout=to a ufunc, to avoid allocating a new array. - Pick a smaller dtype when the precision allows it.
float32halves the memory offloat64.
Here is the pairwise distance computation in blocks of rows:
import numpy as np
def pairwise_chunked(pts, block=500):
n = len(pts)
out = np.empty((n, n))
for start in range(0, n, block):
stop = min(start + block, n)
diff = pts[start:stop, np.newaxis, :] - pts[np.newaxis, :, :]
out[start:stop] = np.sqrt((diff ** 2).sum(axis=-1))
return out
pts = np.random.default_rng(0).random((2000, 3))
dist = pairwise_chunked(pts)
print(dist.shape) # (2000, 2000)
print(dist[0, 0]) # 0.0
print(np.allclose(dist, dist.T)) # TrueThe loop runs only n / block times, so Python overhead stays negligible. Each pass builds a temporary of 500 × 2000 × 3 floats, about 24 MB, instead of 96 MB.
A quick way to estimate cost
Before running a broadcast expression, multiply the result shape together and then multiply by the dtype's bytes per element. Use arr.itemsize to read the byte size of one element. Count each intermediate array in the expression, not only the final one.
Exercise
A broadcast expression produces an intermediate array of shape (5000, 5000, 3) with dtype float64. About how much memory does that one array use, and what is one way to reduce it?
Show answer
It has 5000 5000 3 = 75,000,000 elements. At 8 bytes each that is 600,000,000 bytes, about 600 MB. You can reduce it by processing the rows in blocks so only a slice exists at a time, or by using float32, which halves it to about 300 MB.