Skip to content

Mojo SIMD

Your CPU can add four, eight or even sixteen numbers in one step, as long as they sit side by side in a wide register. That trick is called SIMD: “single instruction, multiple data”. In Mojo you use it through a type called SIMD. It’s not a side feature: every number in Mojo, even a plain Int, is a SIMD value under the hood. This page shows how to make vectors, do math on them and get the results back out.

Here’s a SIMD value that holds four 32-bit floats, and some math on it:

def main():
var a = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0)
var b = SIMD[DType.float32, 4](10.0, 20.0, 30.0, 40.0)
print(a + b)
print(a * b)
print(a * 2)

Output:

[11.0, 22.0, 33.0, 44.0]
[10.0, 40.0, 90.0, 160.0]
[2.0, 4.0, 6.0, 8.0]

Here’s what’s going on:

  • SIMD[DType.float32, 4] is the type: a vector of 4 values, each a float32.
  • a + b works lane by lane: the first number with the first, the second with the second, and so on. Each position in the vector is called a lane.
  • a * 2 multiplies every lane by 2. A single number on one side is copied into every lane first.

On a CPU with SIMD registers (nearly every desktop, laptop and phone CPU today has them), a + b can be one machine instruction instead of four. You don’t call anything special for that: the compiler does it because the type tells it the four numbers belong together.

SIMD takes two parameters in square brackets:

  1. A DType: what kind of number each lane holds, like DType.float32, DType.int32 or DType.uint8. The next lesson, Mojo DType, covers them all.
  2. The width: how many lanes. It must be a power of two (1, 2, 4, 8, 16 …).

Try a width of 3 and the program won’t build:

def main():
var a = SIMD[DType.float32, 3](1.0, 2.0, 3.0)
print(a)
hello.mojo:2:9: error: SIMD vector length must be a power of two between 1 and 2^15, found '!kgen.simd<3, f32>'
var a = SIMD[DType.float32, 3](1.0, 2.0, 3.0)
^
mojo: error: failed to run the pass manager

(The real output repeats the error a few times with some internal notes. We trimmed it.) If you have three values, use a width of 4 and leave the last lane as 0.

Where Mojo already knows a DType is expected, you can drop the DType part and write just .float32. These two lines mean the same:

def main():
var a = SIMD[DType.int32, 4](1, 2, 3, 4)
var b = SIMD[.int32, 4](1, 2, 3, 4)
print(a + b)

Output:

[2, 4, 6, 8]

A SIMD with one lane is called a Scalar, and the number types you already know are just short names for one-lane vectors. Float32 is Scalar[DType.float32], which is SIMD[DType.float32, 1]:

def main():
var a: Float32 = 1.5
var b: SIMD[DType.float32, 1] = 2.5
print(a + b)

Output:

4.0

That works because a and b have exactly the same type. It’s also why Int, Float64 and friends all share the same methods: they’re all SIMD underneath. The numeric types reference lists every alias.

Pass a single value to fill all lanes with it. This is called broadcasting (or “splatting”):

def main():
var sevens = SIMD[DType.int32, 8](7)
var zeros = SIMD[DType.float64, 4](0)
print(sevens)
print(zeros)

Output:

[7, 7, 7, 7, 7, 7, 7, 7]
[0.0, 0.0, 0.0, 0.0]

You’ll use this a lot to start a running total at zero, or to compare every lane with the same limit.

Use square brackets with a lane number, like a list. Lanes start at 0:

def main():
var v = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0)
print(v[0], v[3])
v[1] = 99.5
print(v)
print(len(v))

Output:

1.0 4.0
[1.0, 99.5, 3.0, 4.0]
4

Reading one lane gives you a Float32 (a one-lane SIMD). len(v) is the width. Don’t overdo lane-by-lane access, though: if you touch every lane one at a time, you’ve written a normal loop and lost the point of SIMD.

To squash a vector into one number, use a reduction:

def main():
var v = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0)
print("sum: ", v.reduce_add())
print("product:", v.reduce_mul())
print("largest:", v.reduce_max())
print("smallest:", v.reduce_min())

Output:

sum: 10.0
product: 24.0
largest: 4.0
smallest: 1.0

A common pattern: keep a whole vector of running totals while you go through your data, and call reduce_add() once at the very end.

This is the part that surprises people. Comparing two vectors with < or > doesn’t compile:

def main():
var a = SIMD[DType.float32, 4](1.0, 5.0, 3.0, 8.0)
var b = SIMD[DType.float32, 4](2.0, 2.0, 2.0, 2.0)
print(a > b)
hello.mojo:1:5: error: function instantiation failed
def main():
^
hello.mojo:4:13: note: call expansion failed
print(a > b)
^
Mojo/stdlib/std/simd.mojo:1504:9: note: constraint failed: Strict inequality is only defined for `Scalar`s; did you mean to use `SIMD.gt(...)`?
mojo: error: failed to run the pass manager

> has to give one Bool, but four lanes give four answers. The message points to the fix: use the methods .gt(), .lt(), .ge(), .le(), .eq() and .ne(). They return a vector of Bools, one per lane, called a mask:

def main():
var a = SIMD[DType.float32, 4](1.0, 5.0, 3.0, 8.0)
var b = SIMD[DType.float32, 4](2.0, 2.0, 2.0, 2.0)
var bigger = a.gt(b)
print(bigger)
print(bigger.select(a, b))

Output:

[False, True, True, True]
[2.0, 5.0, 3.0, 8.0]

mask.select(x, y) picks lane by lane: from x where the mask is True, from y where it’s False. Here that gives the larger of each pair, with no if and no loop.

== and != do compile on vectors, but they give a single Bool: a == b is True only if all lanes are equal. Use .eq() when you want the per-lane answer.

Most functions in std.math take a whole vector and work on every lane. min, max and the .clamp() method do too:

from std.math import sqrt
def main():
var v = SIMD[DType.float32, 4](1.0, 4.0, 9.0, 16.0)
print(sqrt(v))
print(min(v, 5))
print(v.clamp(2.0, 10.0))

Output:

[1.0, 2.0, 3.0, 4.0]
[1.0, 4.0, 5.0, 5.0]
[2.0, 4.0, 9.0, 10.0]

min(v, 5) broadcasts the 5 and takes the smaller value in each lane. .clamp(low, high) keeps every lane inside a range.

.cast[...]() converts each lane to another DType. The width stays the same:

def main():
var v = SIMD[DType.float32, 4](1.9, 2.5, -3.7, 4.0)
print(v.cast[DType.int32]())
var small = SIMD[DType.uint8, 4](250, 251, 252, 253)
print(small + 10)

Output:

[1, 2, -3, 4]
[4, 5, 6, 7]

Two things to notice. Casting a float to an integer cuts off the fraction (it doesn’t round). And a uint8 lane can only hold 0 to 255, so 250 + 10 wraps around to 4 without any warning, just like the integer overflow you’ve already seen with Int.

Each CPU has registers of a fixed size, for example 128, 256 or 512 bits. simd_width_of tells you how many lanes of a type fit in one register on the machine that compiles your code:

from std.sys import simd_width_of
def main():
print("float64:", simd_width_of[DType.float64]())
print("float32:", simd_width_of[DType.float32]())
print("uint8: ", simd_width_of[DType.uint8]())

You’ll see something like this (on our test machine, a 4-core VM with AVX-512 registers):

float64: 8
float32: 16
uint8: 64

On a laptop with 256-bit registers you’d see half of that, and on Apple silicon (128-bit) a quarter. So your results will vary. That’s also why it’s a function and not a fixed number: code that uses simd_width_of adapts to whatever CPU it’s built for. Notice the pattern too: smaller types fit more lanes, so float32 math can do twice as many numbers per step as float64.

A wider type than the register still works (Mojo splits it into several instructions), so the width is about speed, not about what compiles.

Real data usually lives in a List. To work on it in chunks, you get a pointer to the list’s memory with unsafe_ptr() and load several values at once:

def main():
var xs: List[Float32] = [1, 2, 3, 4, 5, 6, 7, 8]
var ptr = xs.unsafe_ptr()
var chunk = ptr.unsafe_load[width=4](4)
print(chunk)
ptr.unsafe_store(0, chunk * 10)
print(xs)

Output:

[5.0, 6.0, 7.0, 8.0]
[50.0, 60.0, 70.0, 80.0, 5.0, 6.0, 7.0, 8.0]
  • unsafe_load[width=4](4) reads 4 values starting at index 4.
  • unsafe_store(0, ...) writes a whole vector starting at index 0.

They’re called “unsafe” because nothing checks the bounds: loading 4 values at index 6 of an 8-item list reads past the end. The Mojo Unsafe Pointers lesson explains the rules. Older code calls these load and store; in Mojo 1.2 those names still work but give a deprecation warning.

You won’t usually write these loops by hand. vectorize, two lessons from now, does the chunking and the leftover items for you.

Put the numbers 4, 8, 15, 16, 23, 42, 7 and 5 in a SIMD[DType.float64, 8] and print their average.

Hint: add up the lanes with one method call, then divide by the width.

Show solution
def main():
var v = SIMD[DType.float64, 8](4, 8, 15, 16, 23, 42, 7, 5)
print(v.reduce_add() / 8)

Output:

15.0

reduce_add() gives 120.0, a single Float64, and dividing by 8 gives the average.

Given SIMD[DType.int32, 8](3, 9, 1, 12, 7, 15, 2, 10), count how many lanes are greater than 8, without a loop.

Hint: .gt() gives a mask of Bools. Cast it to DType.int32 and each True becomes 1.

Show solution
def main():
var v = SIMD[DType.int32, 8](3, 9, 1, 12, 7, 15, 2, 10)
var mask = v.gt(SIMD[DType.int32, 8](8))
print(mask)
print(mask.cast[DType.int32]().reduce_add())

Output:

[False, True, False, True, False, True, False, True]
4

The mask has a True in four lanes. After the cast those are 1s and the rest are 0s, so adding them up counts them.

Replace every negative lane of SIMD[DType.float32, 4](-2.5, 1.0, -0.5, 3.0) with 0.

Hint: there’s a one-word way and a mask way. Try max first.

Show solution
def main():
var w = SIMD[DType.float32, 4](-2.5, 1.0, -0.5, 3.0)
print(max(w, 0))
print(w.lt(0).select(SIMD[DType.float32, 4](0), w))

Output:

[0.0, 1.0, 0.0, 3.0]
[0.0, 1.0, 0.0, 3.0]

max(w, 0) keeps the larger of each lane and 0. The second line does the same with a mask: where a lane is below 0, take 0, otherwise keep the lane.

  • SIMD[DType.float32, 4] is a vector of 4 floats; math on it works lane by lane, and a single number is broadcast to every lane.
  • The width must be a power of two. Float32, Int and the other number types are one-lane SIMD values (Scalar).
  • Reductions like reduce_add() and reduce_max() turn a vector into one number.
  • Compare vectors with .gt(), .lt(), .eq(), which give a mask; mask.select(x, y) picks per lane. < and > only work on scalars.
  • .cast[...]() converts every lane; small integer types wrap around silently.
  • simd_width_of[dtype]() tells you how many lanes fit in one register, and it differs between machines.

Next up: DType, the list of number formats a SIMD lane can hold and how to pick one.

Quick check

1. What does SIMD[DType.int32, 8](5) * 2 give?
2. Which of these widths can a SIMD vector NOT have?
3. You want to know, lane by lane, where a is greater than b. What do you write?
4. Why does simd_width_of[DType.float32]() print different numbers on different computers?