Mojo Vectorize
You now know how to do math on a small SIMD vector. Real data is longer: a list of a million prices, a sound file, an image. To use SIMD on it, you go through the data in chunks, say 16 numbers at a time, and then deal with the few numbers left at the end that don’t fill a whole chunk. vectorize from the std.algorithm module writes that loop for you. You give it a small function that handles one chunk, and it calls that function across the whole range.
Your first vectorize
Section titled “Your first vectorize”Here’s a list of 10 numbers, doubled in chunks of 4. The function prints what it’s asked to do, so you can see how vectorize calls it:
from std.algorithm import vectorize
def main(): var xs: List[Float32] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] var ptr = xs.unsafe_ptr()
def double_it[width: Int](i: Int) {imm ptr}: print("width", width, "at", i) var chunk = ptr.unsafe_load[width=width](i) ptr.unsafe_store(i, chunk * 2)
vectorize[4](len(xs), double_it) print(xs)Output:
width 4 at 0width 4 at 4width 1 at 8width 1 at 9[2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0]Let’s take it apart:
xs.unsafe_ptr()gives a pointer to the list’s memory, so you can load and store several numbers at once (you sawunsafe_loadandunsafe_storein Mojo SIMD).def double_it[width: Int](i: Int)is the chunk function.iis where the chunk starts.widthis how many numbers it covers, and it’s a parameter (in square brackets), so it’s known at compile time. That’s what lets you use it inunsafe_load[width=width].{imm ptr}is the capture list from Mojo Closures: the function readsptrfrommain. It writes through the pointer, but it never changesptritself, soimmis enough.vectorize[4](len(xs), double_it): chunks of 4, over the range 0 tolen(xs), callingdouble_it.
10 doesn’t divide by 4, so after two full chunks there are 2 numbers left. vectorize handles them by calling your function with width 1, once per leftover item. Your function doesn’t need any special case for the end; it just has to work for any width.
Leftovers in one go
Section titled “Leftovers in one go”If the size is known at compile time, you can pass it as a parameter with size= instead. Then vectorize can cover a leftover of 2 with one chunk of width 2:
from std.algorithm import vectorize
def main(): var xs: List[Float32] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] var ptr = xs.unsafe_ptr()
def show[width: Int](i: Int) {imm ptr}: print("width", width, "at", i, ":", ptr.unsafe_load[width=width](i))
vectorize[4, size=10](show)Output:
width 4 at 0 : [1.0, 2.0, 3.0, 4.0]width 4 at 4 : [5.0, 6.0, 7.0, 8.0]width 2 at 8 : [9.0, 10.0]The vectorize reference says this only happens when the leftover count is a power of two; otherwise it falls back to width 1. Most of the time your data size is only known at run time, so the first form is the one you’ll use.
Picking the chunk width
Section titled “Picking the chunk width”Hard-coding 4 is fine for learning, but the best width depends on the CPU. Ask for it with simd_width_of, as a comptime value:
from std.algorithm import vectorizefrom std.sys import simd_width_of
def main(): var xs: List[Float32] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] var ptr = xs.unsafe_ptr() var total: Float32 = 0
def add_up[width: Int](i: Int) {imm ptr, mut total}: total += ptr.unsafe_load[width=width](i).reduce_add()
comptime w = simd_width_of[DType.float32]() vectorize[w](len(xs), add_up) print(total)Output:
55.0On our test machine (512-bit registers) w is 16, which is more than the list’s 10 items, so this run is all leftovers. On a machine where w is 4 or 8 it chunks differently. The answer is the same either way, and that’s the point: write the chunk function once and let the width follow the hardware.
{mut total} lets the function add to total in main. Each chunk is added up with reduce_add() and the result goes into the running total.
Is it faster? Measure it
Section titled “Is it faster? Measure it”Adding up each chunk with reduce_add() is simple, but it reduces on every step. The faster pattern keeps a whole vector of running totals and reduces once at the end. Here’s that version next to a plain loop, timed with the benchmark module (the Mojo Benchmarking lesson explains run, keep and max_runtime_secs):
from std.algorithm import vectorizefrom std.benchmark import run, keep, Unitfrom std.sys import simd_width_of
comptime N = 1_000_000
def sum_loop(xs: List[Float32]) -> Float32: var total: Float32 = 0 for x in xs: total += x return total
def sum_vectorized(xs: List[Float32]) -> Float32: comptime w = simd_width_of[DType.float32]() var ptr = xs.unsafe_ptr() var acc = SIMD[DType.float32, w](0) var rest: Float32 = 0
def step[width: Int](i: Int) {imm ptr, mut acc, mut rest}: comptime if width == w: acc += ptr.unsafe_load[width=w](i) else: rest += ptr.unsafe_load[width=width](i).reduce_add()
vectorize[w](len(xs), step) return acc.reduce_add() + rest
def main() raises: var xs = List[Float32](capacity=N) for i in range(N): xs.append(Float32(i % 10)) print("results:", sum_loop(xs), sum_vectorized(xs))
def plain() {imm xs}: keep(sum_loop(xs)) def vec() {imm xs}: keep(sum_vectorized(xs)) var a = run(plain, max_runtime_secs=1.0) var b = run(vec, max_runtime_secs=1.0) print("plain loop:", round(a.mean(Unit.ms), 3), "ms") print("vectorize: ", round(b.mean(Unit.ms), 3), "ms")You’ll see something like this (one run on our test machine, a 4-core Linux VM with AVX-512; your numbers will be different):
results: 4500000.0 4500000.0plain loop: 0.658 msvectorize: 0.127 msTwo more runs gave 0.634 ms vs 0.129 ms and 0.639 ms vs 0.152 ms. So here, on this machine, the vectorized sum was roughly 4 to 5 times faster. A few honest notes about that number:
comptime if width == wsplits the full chunks (added into the vectoracc) from the leftovers (added intorest).widthis a parameter, so the check costs nothing at run time.- The plain loop isn’t slow because Mojo is slow. It’s slow because float addition depends on order (
(a + b) + ccan differ froma + (b + c)in the last digit), so the compiler won’t regroup it into SIMD on its own. The vectorized version adds in a different order, which you’ve explicitly allowed. With messy real numbers the two results can differ slightly. - On a CPU with narrower registers the gap will be smaller. For work that’s limited by memory speed rather than math, it can shrink a lot. Always measure your own case.
Old tutorials use a different syntax
Section titled “Old tutorials use a different syntax”vectorize changed in recent releases. Code from older blog posts passes the function as a parameter and marks it with @parameter. That doesn’t compile in Mojo 1.2:
from std.algorithm import vectorize
def main(): var xs: List[Float32] = [1, 2, 3, 4] var ptr = xs.unsafe_ptr()
@parameter def double_it[width: Int](i: Int): ptr.unsafe_store(i, ptr.unsafe_load[width=width](i) * 2)
vectorize[double_it, 4](len(xs))hello.mojo:7:6: warning: '@parameter' is deprecated; use '@__parameter' @parameter ^~~~~~~~~hello.mojo:11:5: error: no matching function in call to 'vectorize' vectorize[double_it, 4](len(xs)) ^~~~~~~~~mojo: error: failed to parse the provided Mojo source moduleThe fix is the form you’ve used on this page: drop @parameter, add a capture list, put only the width in square brackets, and pass the function as the last argument: vectorize[4](len(xs), double_it).
Practice
Section titled “Practice”1. Raise every price
Section titled “1. Raise every price”You have prices: List[Float32] = [10, 20, 30, 40, 50]. Use vectorize with chunks of 4 to raise every price by 50% (multiply it by 1.5), then print the list.
Hint: capture the pointer and the factor with imm. A single Float32 times a vector is broadcast to every lane.
Show solution
from std.algorithm import vectorize
def main(): var prices: List[Float32] = [10, 20, 30, 40, 50] var ptr = prices.unsafe_ptr() var factor: Float32 = 1.5
def scale[width: Int](i: Int) {imm ptr, imm factor}: ptr.unsafe_store(i, ptr.unsafe_load[width=width](i) * factor)
vectorize[4](len(prices), scale) print(prices)Output:
[15.0, 30.0, 45.0, 60.0, 75.0]One chunk of 4 covers the first four prices, and the fifth is handled as a leftover with width 1.
2. Dot product
Section titled “2. Dot product”Compute the dot product of a = [1, 2, 3, 4, 5, 6, 7] and b = [7, 6, 5, 4, 3, 2, 1] (both List[Float64]): multiply matching items and add everything up.
Hint: load a chunk from each list at the same i, multiply the two vectors, and add the reduce_add() of the product to a mut total.
Show solution
from std.algorithm import vectorize
def main(): var a: List[Float64] = [1, 2, 3, 4, 5, 6, 7] var b: List[Float64] = [7, 6, 5, 4, 3, 2, 1] var pa = a.unsafe_ptr() var pb = b.unsafe_ptr() var dot: Float64 = 0
def step[width: Int](i: Int) {imm pa, imm pb, mut dot}: var x = pa.unsafe_load[width=width](i) var y = pb.unsafe_load[width=width](i) dot += (x * y).reduce_add()
vectorize[4](len(a), step) print(dot)Output:
84.07 + 12 + 15 + 16 + 15 + 12 + 7 = 84. Both lists must have the same length, because one i indexes both.
vectorize[width](size, func)(fromstd.algorithm) callsfuncin chunks over0tosize, and handles the leftover items for you.- The chunk function looks like
def f[width: Int](i: Int) {captures}:;widthis a compile-time parameter andiis the start of the chunk. - Load and store chunks through
list.unsafe_ptr()withunsafe_load[width=width](i)andunsafe_store(i, ...). Never pass asizebigger than the data. - Pick the width with
simd_width_of[dtype]()so it fits the CPU. - For sums, keep a vector of totals and reduce once at the end. On our test machine that was about 4 to 5 times faster than a plain loop; measure your own.
- Old
@parameter+vectorize[func, width](size)code doesn’t compile in Mojo 1.2.
Next up: parallelize, which spreads work across all your CPU cores instead of one.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- vectorize (standard library): all three forms, including
size=,unroll_factorand the masked-tail version. - algorithm package: what else lives in
std.algorithm, such asmapand tiling helpers. - simd_width_of: the natural vector width of a type on the current machine.
- Using pointers: the manual’s guide to
Pointer, loads, stores and staying in bounds.