A naive approach applies a scalar function to arrays without deliberately arranging vectorization. It may work through broadcasting and universal functions, fail clearly, or silently produce an incorrect result. section 6.1.1
Two straightforward forms illustrate the tradeoff:
- Pass arrays directly to the original function. For ten pairs of vectors, dot returns one scalar instead of ten pairwise dot products; broadcasting can let the mistake spread unnoticed. section 6.1.1
- Loop over elements manually with a list comprehension. This produces the expected individual results, but it is straightforward rather than efficient. section 6.1.1
Listing 6.7 Comparing the speed of different approaches
%timeit [dot(v1s[i],v2s[i]).block_until_ready() for i in range(v1s.shape[0])] #1 >>> 4.58 ms ± 152 µs per loop #2 (mean ± std. dev. of 7 runs, 100 loops each) #2 %timeit dot_vectorized(v1s, v2s).block_until_ready() >>> 91.9 µs ± 20 µs per loop #3 (mean ± std. dev. of 7 runs, 10000 loops each) #3 %timeit dot_vmapped(v1s, v2s).block_until_ready() >>> 831 µs ± 7.7 µs per loop #4 (mean ± std. dev. of 7 runs, 1000 loops each) #4 dot_vectorized_jitted = jax.jit(dot_vectorized) #5 dot_vmapped_jitted = jax.jit(dot_vmapped) #5 # warm-up dot_vectorized_jitted(v1s, v2s); dot_vmapped_jitted(v1s, v2s); %timeit dot_vectorized_jitted(v1s, v2s).block_until_ready() >>> 6.93 µs ± 194 ns per loop #6 (mean ± std. dev. of 7 runs, 100000 loops each) %timeit dot_vmapped_jitted(v1s, v2s).block_until_ready() >>> 7.6 µs ± 1.42 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each) #6 #1 Don’t forget about asynchronous dispatch! #2 The naive approach is the slowest one. #3 The manually vectorized function has great performance. #4 The automatically vectorized function is slower but still very fast. #5 JIT-ting both vectorized functions #6 After JIT-ting, the speeds of manually and automatically vectorized solutions are much closer.
Speed measurements show the naive loop is much slower than vectorized alternatives; JIT compilation makes the approaches more similar. section 6.1.4
