Skip to content

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.

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 0
width 4 at 4
width 1 at 8
width 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 saw unsafe_load and unsafe_store in Mojo SIMD).
  • def double_it[width: Int](i: Int) is the chunk function. i is where the chunk starts. width is 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 in unsafe_load[width=width].
  • {imm ptr} is the capture list from Mojo Closures: the function reads ptr from main. It writes through the pointer, but it never changes ptr itself, so imm is enough.
  • vectorize[4](len(xs), double_it): chunks of 4, over the range 0 to len(xs), calling double_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.

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.

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 vectorize
from 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.0

On 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.

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 vectorize
from std.benchmark import run, keep, Unit
from 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.0
plain loop: 0.658 ms
vectorize: 0.127 ms

Two 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 == w splits the full chunks (added into the vector acc) from the leftovers (added into rest). width is 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) + c can differ from a + (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.

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 module

The 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).

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.

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.0

7 + 12 + 15 + 16 + 15 + 12 + 7 = 84. Both lists must have the same length, because one i indexes both.

  • vectorize[width](size, func) (from std.algorithm) calls func in chunks over 0 to size, and handles the leftover items for you.
  • The chunk function looks like def f[width: Int](i: Int) {captures}:; width is a compile-time parameter and i is the start of the chunk.
  • Load and store chunks through list.unsafe_ptr() with unsafe_load[width=width](i) and unsafe_store(i, ...). Never pass a size bigger 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

1. You call vectorize[4](10, f). Which calls does f get?
2. Why is width written in square brackets in def f[width: Int](i: Int)?
3. What does the capture list {imm ptr, mut total} allow the chunk function to do?