Vectorization: move the loop, control the memory
向量化与广播
Compute nearest-reference assignments in reusable NumPy blocks, account for buffers and test numerical rewrites.
vectorizationRemove the inner loop without buying a giant temporary
A sensor station matches each two-channel reading to the nearest of three reference settings. The rule is simple: compute squared distances, choose the smallest, and use the first reference when computed distances tie. The implementation becomes interesting when five readings turn into five million.
A Python loop can perform each scalar subtraction and multiplication. A NumPy expression can move those element operations into compiled loops. But writing all point–reference differences at once creates an array with one dimension for points, one for references and one for features. The arithmetic is unchanged; the memory demand is not.
We will vectorize within blocks of points and keep a short outer Python loop. NumPy’s broadcasting guide explains both the compiled-loop benefit and why large broadcast results can make an outer loop worthwhile. Here the reference settings are given; we are not fitting clusters or learning a distance metric.
Name the axes and the temporary arrays
Let X contain N points with D features and C contain K reference vectors, with K and D positive. For each point, compute:
The outer minimum chooses the smallest reference index among ties. Square roots are unnecessary because they preserve the order of nonnegative distances. Feature units still matter: doubling one feature multiplies its squared contribution by four. Any fitted scaling must be learned under the experiment’s training-data rules, not improvised from evaluation data.
For b points, X_block[:,None,:] has shape (b,1,D) and C[None,:,:] has shape (1,K,D). Subtraction produces (b,K,D). Broadcasting need not copy the operands into that shape, but the subtraction result must exist in this implementation. Contracting the feature axis then yields (b,K):
einsum('bkd,bkd->bk', ...) states which axis disappears. With an explicit output buffer, this contraction avoids writing a separate full squared-difference array at the Python expression level. The einsum reference documents the output and contraction syntax. This is not a promise that a numerical library never uses internal workspace.
Two named float64 distance buffers therefore occupy exactly:
where B is the positive block-row limit. Processing all points together would use the same expression with b=N. This count excludes copied inputs, output labels and distances, small indexing arrays, validation temporaries, allocator overhead and library workspace. It is not a measured process-memory peak.
Each point belongs to exactly one block, and each block compares its points with every reference. Therefore blocking preserves the mathematical problem and the number of pair-feature calculations. It reduces temporary storage rather than the order of arithmetic work.
Reuse two buffers across the blocks
Run the following with Python 3.12 and NumPy 1.26.4. nearest_blocks accepts plain two-dimensional NumPy arrays with real integer or floating dtypes; Boolean, object and complex arrays are rejected. Inputs are copied into contiguous float64 arrays, so the computation is defined on those converted values, which may differ from higher-precision inputs. Coordinates after conversion must be finite and have magnitude at most one million. Points may have zero rows; references may not. Feature dimensions must agree and be nonzero.
block_rows must be a positive Python integer, not a Boolean. The function returns labels, squared distances, the number of processed blocks and the two distance-buffer byte counts. It does not modify either input. argmin returns the first occurrence of a computed minimum; a mathematical near-tie can still be affected by floating-point rounding.
import numpy as np
def _matrix(value, name, features=None, allow_empty=False):
if type(value) is not np.ndarray or value.ndim != 2 or value.shape[1] == 0:
raise ValueError(name + ' must be a plain matrix with at least one feature')
if value.dtype.kind not in 'iuf':
raise ValueError(name + ' must have a real integer or floating dtype')
if not allow_empty and value.shape[0] == 0:
raise ValueError(name + ' must contain at least one row')
if features is not None and value.shape[1] != features:
raise ValueError('feature dimensions must match')
with np.errstate(over='raise', invalid='raise'):
try:
result = np.array(value, dtype=np.float64, order='C', copy=True)
except FloatingPointError as exc:
raise ValueError('float64 conversion overflow') from exc
if not np.isfinite(result).all() or np.any(np.abs(result) > 1e6):
raise ValueError('finite coordinates of magnitude at most 1e6 required')
return result
def nearest_blocks(points, centres, block_rows=64):
if type(block_rows) is not int or block_rows < 1:
raise ValueError('block_rows must be a positive integer, not bool')
c = _matrix(centres, 'centres')
x = _matrix(points, 'points', features=c.shape[1], allow_empty=True)
n, d = x.shape
k = len(c)
b = min(block_rows, n)
labels = np.empty(n, dtype=np.intp)
distances = np.empty(n, dtype=np.float64)
difference = np.empty((b, k, d), dtype=np.float64)
squared = np.empty((b, k), dtype=np.float64)
blocks = 0
for start in range(0, n, block_rows):
stop = min(start + block_rows, n)
size = stop - start
diff = difference[:size]
sq = squared[:size]
with np.errstate(over='raise', invalid='raise'):
np.subtract(x[start:stop, None, :], c[None, :, :], out=diff)
np.einsum('bkd,bkd->bk', diff, diff, out=sq, optimize=False)
if not np.isfinite(sq).all():
raise ValueError('distance computation was nonfinite')
chosen = np.argmin(sq, axis=1)
labels[start:stop] = chosen
distances[start:stop] = sq[np.arange(size), chosen]
blocks += 1
return {'labels': labels, 'squared_distances': distances,
'blocks': blocks,
'distance_buffer_bytes': difference.nbytes + squared.nbytes,
'full_distance_buffer_bytes': 8 * n * k * (d + 1)}
if __name__ == '__main__':
points = np.array([[0, 0], [2, 0], [5, 2], [9, 3], [4, 4]])
centres = np.array([[0, 0], [4, 0], [8, 4]])
result = nearest_blocks(points, centres, block_rows=2)
print('labels', result['labels'].tolist())
print('squared distances', result['squared_distances'].tolist())
print('blocks', result['blocks'])
print('distance buffers', result['distance_buffer_bytes'], result['full_distance_buffer_bytes'])
full = nearest_blocks(points, centres, block_rows=len(points))
print('full agreement', np.array_equal(result['labels'], full['labels']))
close_x = np.array([[1e6]])
close_c = np.array([[1e6 - 2e-6], [1e6 - 1e-6]])
direct = nearest_blocks(close_x, close_c)
expanded = (close_x * close_x).sum(axis=1)[:, None] + (close_c * close_c).sum(axis=1)[None, :] - 2 * (close_x @ close_c.T)
print('nearby direct / expanded labels', direct['labels'].tolist(), expanded.argmin(axis=1).tolist())
print('expanded squared distances', expanded.tolist())
empty = nearest_blocks(np.empty((0, 2)), centres)
print('empty', empty['labels'].tolist(), empty['blocks'], empty['distance_buffer_bytes'])
Output:
labels [0, 0, 1, 2, 1]
squared distances [0.0, 4.0, 5.0, 2.0, 16.0]
blocks 3
distance buffers 144 360
full agreement True
nearby direct / expanded labels [1] [0]
expanded squared distances [[0.0, 0.0]]
empty [] 0 0
The second point, (2,0), is equally far from references 0 and 1, so index 0 wins. The final point has squared distances 32, 16 and 16; index 1 wins that tie. With five points, three references and two features, block size two needs 144 bytes for the named distance buffers, versus 360 for the full block. There are three blocks because the last contains one point.
The close-point example is a numerical counterexample to replacing the direct differences with the algebraically equivalent identity:
The direct calculation selects reference 1. The expanded expression rounds both tiny distances to zero in this run, so it selects reference 0. Clipping negative roundoff to zero would not recover the lost distinction. Matrix multiplication can be an effective alternative for well-scaled data, but an algebraic rewrite needs numerical checks as well as a memory estimate.
Under a constant-cost float64 arithmetic model, validation/copying and assignment take O((N+K)D+NKD+1) work. The named array-storage bound, including input copies and results, is O((N+K)D+N+bKD+1). Only O(N) result entries survive the call. Both full and blocked vectorization still examine all NK pairs.
A shorter expression is not always a faster algorithm
Choose a block size that fits a deliberate workspace budget, then benchmark representative inputs. A very small block reduces distance-buffer memory but increases Python dispatches; a very large block can stress memory. If K or D is huge, point-only blocking may still be too large. Blocking references as well requires keeping a running minimum and handling cross-block ties consistently; that is a further implementation, not something this function already does.
NumPy’s vectorize wraps a Python callable with array-shaped behavior. It is a convenience mechanism, not a way to compile an arbitrary Python loop. Use operations with suitable compiled kernels, or consider a different implementation when the computation has irregular control flow. Removing every visible loop is not the objective.
Float64 is finite-precision arithmetic. Very small squared differences can underflow to zero; reductions and algebraic rewrites may round differently. The code does not certify the nearest reference over exact real numbers. Its magnitude bound limits overflow exposure, but it does not remove near-tie sensitivity. Likewise, successful computation says nothing about whether Euclidean distance is meaningful for the chosen features.
The input-copy policy makes ownership simple but adds memory and preparation time. A service with validated immutable arrays could use a different contract to avoid those copies. Measure that complete path separately rather than subtracting its setup cost from one implementation and leaving it in another.
Predict the shape, the memory and the answer
- N=1000, K=20, D=8 and B=25. How much storage do the two named distance buffers use? What would the full block use?
Answer: The block uses 8*25*20*9 = 36,000 bytes; the full block uses 8*1000*20*9 = 1,440,000 bytes. Neither number is total process memory. Both methods still compute 20,000 point–reference distances.
- Why does
(4,4)select reference 1 rather than reference 2 in the main example?
Answer: The squared distances are 32, 16 and 16. The contract chooses the first minimum, hence index 1. A replacement using the last minimum would change the interface even though its distance value matched.
- Can
maximum(expanded_distances,0)repair the close-point example?
Answer: No. Both expanded values are already zero, so clipping leaves them tied. Subtraction before squaring retains the distinguishing differences in this example; clipping cannot reconstruct information lost during cancellation.
- If the references are processed in several blocks, what must be retained for each point, and how should exact computed ties be handled?
Answer: Retain the best squared distance and its global reference index. Replace a winner for a smaller distance, or for an equal distance with a smaller global index. Using each block’s local index or unconditionally replacing on equality can change the result.
Read the operation contract and the allocation together
The broadcasting guide treats vectorization as a way of arranging computations, while also identifying oversized intermediates. The einsum API makes contractions and output placement explicit. The argmin contract supplies the tie behavior needed to preserve results when changing execution strategy. The vectorize notes explain why an array-shaped wrapper is not itself a speedup.
Continue from NumPy arrays to profiling and numerical testing. A useful optimization report records the unchanged mathematical contract, the changed allocation pattern, numerical counterexamples and the workload on which timing was measured.
Make a prediction, then check
Why can a short outer block loop be useful in vectorized distance computation?
Learning objectives
- Track broadcast axes, contractions and the arrays that actually materialize.
- Separate distance-buffer bytes from total memory and arithmetic complexity.
- Preserve computed tie rules and test cancellation when changing a numerical expression.
Prerequisites & connections
Explore related knowledge →References
- Broadcasting — NumPy v1.26 Manual
NumPy Developers - numpy.einsum — NumPy 1.26
NumPy developers - numpy.argmin — NumPy 1.26
NumPy developers - numpy.vectorize — NumPy 1.26
NumPy developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Six tests passed with actual NumPy 1.26.4 and CPython 3.12.4. Exact Fraction Voronoi half-spaces and expanded inner products independently check six fixtures under four block sizes: 24 label/distance/workspace reports, including noncontiguous inputs, int8 arithmetic, duplicate references and a cancellation example.
- Instrumented np.empty/subtract/einsum confirms one allocation of each distance buffer and reuse across block lengths 2,2,1. Checked empty points, invalid dtypes/shapes/domains, ownership, computed ties and a squared-underflow case where the exact-real winner differs. No timing or RSS claim.
- Original bilingual Python and eight stdout lines, four matching displays, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML passed. Humanizer reread; AI author checks only, written pending independent review. Draft files only.
- Six author tests pass with the actual project CPython 3.12.4 / NumPy 1.26.4. Independent separable product quantization with 16 reference corners and orthogonal Hadamard transforms checks 18 complete reports and 126 row assignments. Known coordinate residuals use 60-digit Decimal, without scanning all pair distances or repeating the author’s half-space oracle. A shared zero-feature extension preserves winners/distances and changes the exact buffer count as predicted.
- Read both full articles, code, metadata and four exercises. Verified block partitioning, contraction axes, first computed tie, dtype conversion and integer-promotion boundary, empty points, input ownership, named-buffer accounting versus total memory, and cancellation/underflow limitations. Strict MDX/KaTeX plus actual React HTML/MathML pass four corresponding formulas, six anchors and four answers. Final five hashes match the frozen snapshot.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Broadcasting — NumPy v1.26 Manual · Actually read the fixed 1.26 guide: lines 41–43 compiled loops and memory caveat, 64–85 broadcasting rules, 167–201 output intermediates and outer-loop alternative. Original sensor fixture and blocked output-buffer implementation; no athlete example or external code copied.
- numpy.einsum — NumPy 1.26 · Actually read signature and parameters lines 76–125, especially explicit output labels, out, dtype/casting and optimize=False. This supports the stated Python-visible buffers, not a no-internal-workspace guarantee.
- numpy.argmin — NumPy 1.26 · Actually read axis/output parameters 78–105 and first-occurrence rule 122–124. Numerical winners refer to computed float64 distances.
- numpy.vectorize — NumPy 1.26 · Actually read definition 66–71 and Notes 113–118: convenience wrapper whose implementation is essentially a loop, with possible probing call when output types are omitted. No performance benchmark is inferred from the documentation.
- Broadcasting — NumPy v1.26 Manual · Independently read fixed 1.26 broadcasting rules at 41–85 and large difference arrays/outer-loop alternative at 200–201. Conceptual operand expansion is distinct from the materialized subtraction output.
- numpy.einsum — NumPy 1.26 · Independently read explicit contraction labels, out and optimize at 76–125, and explicit mode at 171–176. No internal-workspace or timing guarantee inferred.
- numpy.argmin — NumPy 1.26 · Independently read first-occurrence ties at 122–124 and axis/output contract at 78–105.
- numpy.vectorize — NumPy 1.26 · Independently read convenience/for-loop/probing-call notes at 113–118. No measured performance claim.
Related topics