---
title: SIMD and vector instructions
heading: One instruction, many data: packed lanes, vector lengths, and the limits Amdahl and memory set
eyebrow: C8 · Lesson 42 · SIMD and vector instructions
xp: 40
---

::: hook
Lesson 41 found parallelism by running several instructions at once. Much of the work a computer does, filtering audio, blending pixels, multiplying matrices, applies the same operation to many numbers in a row, and there's a cheaper way to speed that up: make one instruction operate on many numbers. A 256-bit register holds eight 32-bit floats, and one instruction adds eight pairs. That's **SIMD**, single instruction, multiple data, and it's how phones decode video and laptops run neural networks. The same idea works inside an ordinary 32-bit register with clever masking, which this lesson does on the course's own processor. Two limits stop it from scaling forever: the part of a program that isn't vectorizable, and memory bandwidth.
:::

::: play
- Four bytes packed in each register are added lane by lane on the plain RV32I processor, with masks that stop carries from crossing between bytes: $((a \wedge \texttt{7F7F7F7F}) + (b \wedge \texttt{7F7F7F7F})) \oplus ((a \oplus b) \wedge \texttt{80808080})$.
- 0x7F + 0x01 gives 0x80 in the top lane, while 0x01 + 0xFF and 0xFF + 0x01 wrap to 0x00 without disturbing their neighbors.
:::

```sim cpu
    li   a0, 0x7F01FF10
    li   a1, 0x01FF0110
    li   t0, 0x7F7F7F7F
    and  t1, a0, t0       # low 7 bits of each byte of a
    and  t2, a1, t0       # and of b
    add  t1, t1, t2       # add: no carry can leave a byte
    xor  t3, a0, a1
    li   t0, 0x80808080
    and  t3, t3, t0       # each byte's top-bit sum, without carry
    xor  a2, t1, t3       # four byte sums at once
    ebreak
show: a0, a1, a2
hex: a0, a1, t1, t3, a2
speed: 2
```

::: predict
## 80% of a program's time is in a loop that vectorizes perfectly onto 8 lanes. The rest is serial. What's the overall speedup?

- [ ] 8
- [ ] 6.4
- [x] About 3.3
- [ ] 5

::: reveal
$1/(0.2 + 0.8/8)$ = 3.33. The vector part shrinks from 0.8 to 0.1 of the original time, but the serial 0.2 stays, and it now dominates. Even infinitely wide vectors couldn't beat $1/0.2$ = 5. This is Amdahl's law, and it's why vectorizing one hot loop gives a good but bounded win.
:::
:::

::: nameit
## Packed SIMD

Packed SIMD extensions (x86's SSE and AVX, ARM's NEON) add wide registers of 128 to 512 bits and instructions that treat them as arrays of lanes: sixteen 8-bit, eight 16-bit, four 32-bit and so on. `vaddps` adds eight float pairs at once. Lanes don't carry into each other, saturating versions clamp instead of wrapping (useful for pixels and audio), and shuffles rearrange lanes. The width is fixed by the instruction set, so code is rewritten for each new width.

## Vector instruction sets

RISC-V's V extension instead lets the program ask for a vector length. `vsetvli` takes the number of elements left and returns how many the hardware will process this time, up to its own maximum. A loop then **strip-mines**: process as many as the hardware allows, advance, repeat, with no separate code for the last partial group. The same binary runs on cores with short or long vectors.

## SIMD within a register

On a plain integer processor, packed bytes can still be processed in parallel with masks:

- **Lane-wise add:** add the low 7 bits of each byte (no carry can escape), then fix the top bits with XOR: $((a \wedge m) + (b \wedge m)) \oplus ((a \oplus b) \wedge h)$, with $m$ = 0x7F7F7F7F and $h$ = 0x80808080.
- **Find a zero byte:** $(x - \texttt{0x01010101}) \wedge \bar x \wedge \texttt{0x80808080}$ is nonzero exactly when some byte of $x$ is zero. String functions such as `strlen` check four or eight bytes per step this way.

## The limits

- **Amdahl's law:** with a fraction $f$ of the work vectorized onto $L$ lanes, the speedup is $\dfrac{1}{(1 - f) + f/L}$, never more than $1/(1 - f)$.
- **Memory bandwidth:** adding two float arrays moves 12 bytes per element. At 20 GB/s that's at most 1.7 billion elements per second, however many lanes there are. Wide SIMD pays off fully only when data is reused from cache or registers.
- **Alignment and tails:** wide loads are fastest from aligned addresses, and leftover elements need masking or a short scalar loop.
:::

::: example
## Add the packed bytes of 0x7F01FF10 and 0x01FF0110 lane by lane with the masking trick, and check it byte by byte.

::: solution
1. **Byte by byte, modulo 256.**
   $$\begin{aligned} \text{0x7F} + \text{0x01} &= \text{0x80} \\ \text{0x01} + \text{0xFF} &= \text{0x00} \\ \text{0xFF} + \text{0x01} &= \text{0x00} \\ \text{0x10} + \text{0x10} &= \text{0x20} \end{aligned}$$
   so the expected result is 0x80000020.
2. **Add the low 7 bits of each byte.**
   $$\begin{aligned} a \wedge m &= \text{0x7F017F10} \\ b \wedge m &= \text{0x017F0110} \\ \text{sum} &= \text{0x80808020} \end{aligned}$$
3. **Find the top bits.**
   $$\begin{aligned} a \oplus b &= \text{0x7EFEFE00} \\ (a \oplus b) \wedge h &= \text{0x00808000} \end{aligned}$$
4. **Fix the top bits with XOR.**
   $$\begin{aligned} &\text{0x80808020} \oplus \text{0x00808000} \\ &= \text{0x80000020} \end{aligned}$$
   matching.
5. **Count the instructions.** Eight instructions (plus two to build the constants, once per loop) do four additions.

**Answer:** both ways give 0x80000020.
:::
:::

::: example
## A vector loop processes 1003 elements on hardware whose vectors hold 8 elements. How many iterations, and how many elements does the last one handle? What would a fixed-width SIMD loop need?

::: solution
1. **The vector loop.** With `vsetvli`, the loop runs
   $$\left\lceil \frac{1003}{8} \right\rceil = 126$$
   iterations: 125 full ones and a last one of 3 elements, using the same code.
2. **A fixed-width SIMD loop.** A fixed 8-lane SIMD loop does 125 full iterations and then needs a separate scalar tail loop, or masked instructions, for the last 3.

**Answer:** 126 iterations, the last one handling 3 elements; a fixed-width SIMD loop needs a separate tail loop or masked instructions for those 3.
:::
:::

::: example
## A filter does 2 floating-point operations per 4-byte input sample it reads, and the memory system delivers 25 GB/s. A core can do 64 billion floating-point operations per second with full-width SIMD. Which limit binds?

::: solution
1. **Samples from memory.**
   $$\frac{25 \times 10^9}{4} = 6.25 \times 10^9\ \text{/s}$$
2. **The operations they feed.** That's enough for 12.5 billion operations per second, and the core could do 64 billion.
3. **Which binds.** The filter is memory-bound at about a fifth of the SIMD peak.
4. **What would help.** Widening the vectors would change nothing, while reusing each sample more (a longer filter that keeps data in registers) would.

**Answer:** memory bandwidth binds: it feeds 12.5 billion operations per second, about a fifth of the core's 64 billion.
:::
:::

::: check
given: f = 0.5 | 0.8 | 0.9 | 0.95; L = 4 | 8 | 16
answer: 1/((1 - f) + f/L)
tolerance: 0.5%

## A fraction {f} of a program's time vectorizes perfectly onto {L} lanes. What's the overall speedup?

::: right
Right. $1/((1 - f) + f/L)$ = {answer}.
:::

::: misses
- [L] Only the vectorized part speeds up.
- [1/(1 - f)] That's the limit with infinitely many lanes.
- [f*L] Use Amdahl's law: the times add, not the speedups.
- [any] Not yet. $1/((1 - f) + f/L)$.
:::
:::

::: check
given: n = 37 | 101 | 250 | 1003; L = 8 | 16 | 32
answer: ceil(n/L)
tolerance: 0.1%

## A strip-mined vector loop processes {n} elements, at most {L} per iteration. How many iterations does it run?

::: right
Right. $\lceil n/L\rceil$ = {answer}, the last one partly full.
:::

::: misses
- [floor(n/L)] Round up: the leftover elements need one more iteration.
- [any] Not yet. $\lceil n/L\rceil$.
:::
:::

::: check
given: B = 10 | 25 | 50; bpe = 8 | 12 | 16; ops = 2 | 4 | 8
answer: B/bpe*ops
tolerance: 0.5%

## A loop moves {bpe} bytes of memory per element and does {ops} floating-point operations per element. With {B} GB/s of memory bandwidth, what's the most it can compute, in billions of operations per second?

::: right
Right. $B/\text{bytes} \times \text{ops}$ = {answer}, whatever the SIMD width.
:::

::: misses
- [B*ops] Divide the bandwidth by the bytes each element needs.
- [B/bpe] Multiply elements per second by the operations per element.
- [any] Not yet. Elements per second times operations per element.
:::
:::

::: check
kind: asm
given: p0 = 128..255 int; p1 = 0..255 int; p2 = 0..255 int; p3 = 0..255 int; q0 = 128..255 int; q1 = 0..255 int; q2 = 0..255 int; q3 = 0..255 int; let A = p0 + 256*p1 + 65536*p2 + 16777216*p3; let B = q0 + 256*q1 + 65536*q2 + 16777216*q3
setup: a0 = A; a1 = B
expect: a2 = (p0 + q0 - 256*floor((p0 + q0)/256)) + 256*(p1 + q1 - 256*floor((p1 + q1)/256)) + 65536*(p2 + q2 - 256*floor((p2 + q2)/256)) + 16777216*(p3 + q3 - 256*floor((p3 + q3)/256))

## `a0` and `a1` each hold four packed bytes. Put their lane-by-lane sums (each modulo 256) in `a2`, without letting carries cross between bytes.

```asm starter
    add a2, a0, a1      # carries leak between bytes: fix this
    ebreak
```

```asm solution
    li  t0, 0x7F7F7F7F
    and t1, a0, t0
    and t2, a1, t0
    add t1, t1, t2
    xor t3, a0, a1
    li  t0, 0x80808080
    and t3, t3, t0
    xor a2, t1, t3
    ebreak
```

::: right
Right. Adding only the low seven bits of each byte keeps every carry inside its lane, and the XOR puts back each lane's top bit.
:::
:::

::: check
kind: choice

## A programmer widens a loop from 4-lane to 16-lane SIMD and sees no speedup. The loop adds two large arrays into a third. What's the most likely reason?

- [x] It's limited by memory bandwidth, not arithmetic: 12 bytes move per addition however wide the vectors are
- [ ] 16-lane instructions are slower than 4-lane ones
- [ ] The compiler ignored the wider vectors
- [ ] Amdahl's law limits any loop to 4 lanes

::: right
Right. One addition per 12 bytes of traffic is far below what even 4-lane SIMD can compute, so the loop already waited on memory. Fusing it with other work on the same data, while it's in registers, is what helps.
:::

::: misses
- [2] Wider instructions do more per cycle; the bottleneck is elsewhere.
- [3] Possible, but the bandwidth limit explains it with no bug at all.
- [4] Amdahl's law limits the serial fraction, not the lane count.
:::
:::

::: check
kind: python
given: seed = 1 | 2 | 3

## Write two SWAR functions for 32-bit words: `add_bytes(a, b)`, lane-wise byte addition modulo 256 using the masking trick, and `has_zero_byte(x)` returning `True` if any byte of `x` is zero, using $(x - \texttt{0x01010101}) \wedge \bar x \wedge \texttt{0x80808080}$. Keep results in 32 bits. They'll be checked against byte-by-byte references on random words from `random.Random(seed)`.

```python starter
def add_bytes(a, b):
    return (a + b) & 0xFFFFFFFF
def has_zero_byte(x):
    return x == 0
```

```python solution
M, H = 0x7F7F7F7F, 0x80808080
def add_bytes(a, b):
    return (((a & M) + (b & M)) ^ ((a ^ b) & H)) & 0xFFFFFFFF
def has_zero_byte(x):
    return ((x - 0x01010101) & ~x & 0x80808080 & 0xFFFFFFFF) != 0
```

```python tests
import random
rng = random.Random(seed)
for _ in range(3000):
    a, b = rng.getrandbits(32), rng.getrandbits(32)
    ref = sum((((a >> s) & 255) + ((b >> s) & 255)) % 256 << s for s in (0, 8, 16, 24))
    assert add_bytes(a, b) == ref, f"add_bytes({a:#010x}, {b:#010x}) should be {ref:#010x}."
    x = a if rng.random() < 0.5 else a & ~(0xFF << (8 * rng.randrange(4))) & 0xFFFFFFFF
    assert has_zero_byte(x) == any(((x >> s) & 255) == 0 for s in (0, 8, 16, 24)), f"has_zero_byte({x:#010x}) is wrong."
```

::: right
Right. Both tricks process four bytes per instruction sequence on an ordinary integer unit, which is how C libraries' string functions run fast without SIMD hardware.
:::
:::

::: explain
## A video decoder speeds up 6 times when moved from scalar code to 8-lane SIMD, but only 7 times with 16 lanes. Explain both numbers, and what you'd look at to go faster.

::: model
By Amdahl's law, if a fraction $f$ of the time vectorizes, 8 lanes give $1/((1 - f) + f/8)$; a speedup of 6 means $f$ is about 0.95, so about 5% of the original time stays serial. With 16 lanes the vectorized part shrinks further, but the serial 5% doesn't, and the formula gives only about 9; in practice memory bandwidth and the overhead of shuffles and tails take some of that too, so 7 is plausible. To go faster, attack what's left: vectorize or restructure the serial parts such as entropy decoding, reduce memory traffic by keeping data in cache between stages, and avoid unaligned loads and lane shuffles in the vector code.
:::
:::

::: practice

::: check
given: f = 0.6 | 0.75 | 0.99; L = 2 | 8 | 32
answer: 1/((1 - f) + f/L)
tolerance: 0.5%

## A fraction {f} vectorizes onto {L} lanes. What's the speedup?

::: misses
- [L] The serial part doesn't speed up.
- [any] $1/((1 - f) + f/L)$.
:::
:::

::: check
given: n = 77 | 500 | 1025; L = 8 | 32
answer: n - L*floor(n/L)
tolerance: 0.5%

## A vector loop with {L}-element vectors processes {n} elements. How many does its last, partial iteration handle?

::: misses
- [L] That's a full iteration; the last one has only the remainder.
- [any] $n \bmod L$.
:::
:::
:::
