Lesson 2 of 9 · 26m
Vectorization, Memory Pressure, and Numerical Safety
Write fast numerical code without creating hidden temporaries, overflowing integers, or turning rounding error into model nonsense.
A model pipeline rarely dies because matrix multiplication was slow. It dies because a 2 GB intermediate appeared during feature expansion, an integer overflow flipped distances negative, or floating-point noise made a reproducibility test flaky. Vectorization is not a style preference. It is control over memory layout, allocation count, and numerical behavior.
Count the temporaries
This looks innocent:
score = np.exp((X - mean) / scale).sum(axis=1)It may allocate several arrays the size of X: subtraction, division, exponentiation. On a million rows and hundreds of columns, that is real memory. Prefer fused or incremental forms when memory is tight:
centered = X - mean
centered /= scale
np.exp(centered, out=centered)
score = centered.sum(axis=1)Do this only when mutation is safe. Premature optimization that corrupts input data is not optimization.
Overflow is quiet
Numpy integer arithmetic does not become arbitrary precision just because Python integers do:
x = np.array([2**31 - 1], dtype=np.int32)
print(x + 1) # overflow warning or wrapped negative valueThis matters in feature engineering: timestamps, counters, IDs, hashes, and cross-products can overflow before reaching a float model. Convert early when magnitude matters:
ts_seconds = raw_ts.astype(np.int64)
delta_hours = (ts_seconds - ts_seconds.min()) / 3600.0Floating point is approximate by design
Floats are not exact decimal numbers. Equality checks are usually wrong:
a = 0.1 + 0.2
print(a == 0.3) # False
print(np.isclose(a, 0.3)) # TrueModel evaluation often involves thresholds. A score barely above or below 0.5 is not a stable business decision. If the decision matters, treat threshold selection as its own validation problem rather than accepting the library default.
Reductions accumulate error
Summing millions of small floats can lose information. Numpy uses pairwise summation for many reductions, but precision still depends on dtype. For sensitive aggregations, accumulate in float64:
loss = np.sum(per_example.astype(np.float64), dtype=np.float64)The opposite mistake also exists: casting everything to float64 doubles memory traffic and slows training pipelines for no measurable benefit.
Use einsum only after reading it aloud
np.einsum is expressive, but readability is a safety feature:
batch_scores = np.einsum('nd,d->n', X, weights)That says: for every row n, sum over feature d. If a new hire cannot decode the letters, write the equivalent matrix multiplication or explicit contraction. Clever numerical code becomes maintenance debt fast.
Profile with representative data
A benchmark on 100 rows is fiction. Use shapes and dtypes that look like production:
python -m timeit -s 'import numpy as np; X=np.random.rand(100000,64)' 'np.sqrt((X**2).sum(axis=1))'Measure allocation, runtime, and memory. Then decide whether optimization is worth the complexity.
Field notes
np.nanmeanand friends cost extra passes because they must detect missing values.- Boolean masks allocate; chained masks allocate repeatedly.
np.dot,@, andmatmulare the same operation here, but shape errors still differ by input dimensions.- Integer division changed in Python but not in numpy's dtype rules; inspect result dtype instead of assuming.
- Reproducibility across CPU architectures is approximate once parallelism and fused operations enter the picture.
Was this lesson helpful?