A compiler turns a[i] = a[i] + b[i] into vector code at once, but not a[i + 1] = a[i] + b[i], though the two loops look almost the same. On 5,400 SPY returns the first costs 3,375 instructions on 8 lanes and the second 27,000. What does the compiler see that you do not?
The idea in plain words
Where we are. The last topic showed that NumPy is the vector idea behind a function call, with a fixed cost per call. Now you write the loop yourself in a compiled language such as C, C++, Rust or Fortran, and the compiler has to decide whether to turn it into vector code. That is auto-vectorization. The question it leaves is which loops the compiler may touch, and you will play compiler on LaneSim to find out.
A vector version is allowed only if it gives exactly the same answer as the scalar loop. If the compiler cannot prove that from the code, it leaves the loop scalar.
The only thing that can break that promise in a[i + w] = a[i + r] + b[i] is a dependence between passes: a value written by one pass and read by another. A vector register runs lanes passes at once, so those passes cannot depend on each other. This is also why finance code is mixed: adding daily profit and loss to a running total (total[i + 1] = total[i] + pnl[i]) is a chain, while adding two return series element by element is not.
The smallest example: a vector that is wrong
scalar_loop runs a[i + w] = a[i + r] + b[i] one element per pass, on a copy of a, and defines what the answer must be. With writes at a[i + 1] and reads at a[i] it is a running total: every pass adds b[i] to what the pass before just wrote. Now force that same loop into registers of 4 lanes without thinking, and compare.
# The running total, scalar: the answer every faster version must matcha = [1.0] * 9b = [1.0] * 8print(scalar_loop(LaneSim(4), a, b, 1, 0))# The same loop forced into 4-lane registers: both loads happen before the storesim = LaneSim(4)out = list(a)for i in range(0, 8, 4): sim.vstore(out, i + 1, sim.vadd(sim.vload(out, i), sim.vload(b, i)))1print(out)
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] [1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 2.0, 2.0, 2.0]
- 1Pass 1 loads
a[1]before pass 0 has stored it.
The scalar run counts up 1, 2, 3 ... 9, a running total. The forced vector run gives [1, 2, 2, 2, 2, 3, 2, 2, 2]: wrong, and silently wrong, since nothing raised an error. In the scalar loop, pass 1 reads a[1] after pass 0 wrote it. In the vector version all four loads happen before the store, so lanes 1 to 3 read the old values. That is exactly the kind of difference a compiler must rule out before it may vectorize.
Build it up: the distance and the verdict
Count how many passes later a value is read after it was written. A pass writes a[i + w]. A later pass reads that same element when its own i + r equals it, which happens w - r passes later. That number is the dependence distance, and a single subtraction is the whole analysis for this loop shape.
- 1Find the pairWhich array does the loop write, and which element of the same array does it read? Different arrays do not conflict here.
- 2SubtractDistance d = w - r: how many passes later the written value is read.
- 3Compare with the lanesIf d ≤ 0 nothing is read after being written. If d ≥ lanes, the value is written in an earlier register. Otherwise it is read inside the same register: stop.
- 4Pick the pathSafe: emit the vector loop. Unsafe: keep the scalar loop. This is what
run_loopdoes.
Look at the four loops below and the verdicts the functions you will write give. Notice that distance 0 and a negative distance are fine for any width, distance 1 is never fine, and distance 4 splits the two machines: safe on 4 lanes, unsafe on 8.
# Verdicts for four loops of the shape a[i + w] = a[i + r] + b[i]loops = [("a[i] = a[i] + b[i]", 0, 0), ("a[i + 1] = a[i] + b[i]", 1, 0), ("a[i + 4] = a[i] + b[i]", 4, 0), ("a[i] = a[i + 3] + b[i]", 0, 3)]for text, w, r in loops: print(f"{text:24} d={dependence_distance(w, r):2} widest={max_vector_width(w, r):2} 4 lanes={can_vectorize(w, r, 4)!s:5} 8 lanes={can_vectorize(w, r, 8)}")1
a[i] = a[i] + b[i] d= 0 widest=16 4 lanes=True 8 lanes=True a[i + 1] = a[i] + b[i] d= 1 widest= 1 4 lanes=False 8 lanes=False a[i + 4] = a[i] + b[i] d= 4 widest= 4 4 lanes=True 8 lanes=False a[i] = a[i + 3] + b[i] d=-3 widest=16 4 lanes=True 8 lanes=True
- 1Reading ahead (d = -3) is safe: the old values are the ones the scalar loop reads too.
Now run_loop, the compiler's decision as code: ask can_vectorize, then emit the vector loop or the scalar one. Run it on all four loops over the 5,400 returns from the lead on both machine widths and read the instruction totals.
# Instruction totals over 5,400 elements, on both machine widthsn = 5400for text, w, r in loops: totals = [] for lanes in (4, 8): sim = LaneSim(lanes) run_loop(sim, [1.0] * (n + max(w, r)), [1.0] * n, w, r) totals.append(sim.total()) print(f"{text:24} 4 lanes={totals[0]:6} 8 lanes={totals[1]:6}")
a[i] = a[i] + b[i] 4 lanes= 6750 8 lanes= 3375 a[i + 1] = a[i] + b[i] 4 lanes= 27000 8 lanes= 27000 a[i + 4] = a[i] + b[i] 4 lanes= 6750 8 lanes= 27000 a[i] = a[i + 3] + b[i] 4 lanes= 6750 8 lanes= 3375
- What the compiler checksVerdict if it fails
- a[i + 1] = a[i] + b[i]Is a value read within the same register it was written in?stays scalar
- p[i] = q[i] + r[i]Could the pointers
pandqpoint at overlapping memory?runtime overlap check, or stays scalar - if (x[i] < 0) break;Can the loop stop early, before the register is full?stays scalar
- a[i] = f(b[i])Does it call a function the compiler cannot see into?fine if it is inlined or has a vector version
Compilers can report each loop they did or did not vectorize, and often the reason. In GCC the flag is -fopt-info-vec-missed, in Clang -Rpass-missed=loop-vectorize; the exact wording depends on the version.
Typical mistakes
Believing a loop is parallel because it looks simple. Smoothing recurrences are the classic case in quant code. An exponential moving average, ema[i + 1] = alpha * x[i] + (1 - alpha) * ema[i], reads what the previous pass wrote, so its distance is 1 and it stays scalar whatever the compiler. The cure is to change the algorithm, not the flags, and later topics show how to restructure such loops.
Code that vectorizes on your laptop and not on the server. A lag-4 loop (d = 4) is safe on 4 lanes and unsafe on 8. The same source vectorizes on one machine and silently stays scalar on a wider one, so a speedup measured on one chip does not carry over. The output below is the lag-4 row of the data panel, on both widths.
# The lag-4 loop on both widths: the answer is the same, the cost is nota4, b4 = [1.0] * 20, [1.0] * 16for lanes in (4, 8): sim = LaneSim(lanes) result = run_loop(sim, a4, b4, 4, 0) print(lanes, "lanes:", sim.total(), "instructions, vectorized:", can_vectorize(4, 0, lanes))1print(result == scalar_loop(LaneSim(8), a4, b4, 4, 0))
4 lanes: 20 instructions, vectorized: True 8 lanes: 80 instructions, vectorized: False True
- 1Same answer; 8 lanes fall back to the scalar loop.
Expecting a warning. The compiler says nothing when it keeps a loop scalar. A slow loop with no message is the normal outcome, which is why the report flags above matter. In the simulator the quiet cost shows up as the larger count; in a real build you only see it if you ask.
Hints such as restrict or #pragma omp simd tell the compiler to trust you that passes are independent. If you are wrong, it vectorizes anyway and the answer silently changes, as in the forced run above.
What the tasks ask
- Task and functionWhat it must return
- dependence_distance(w, r)
w - r: how many passes later a written value is read.one subtraction - max_vector_width(w, r, cap=16)The widest power-of-two vector that keeps the answer, from the distance.calls
dependence_distance - can_vectorize(w, r, lanes)
Truewhenlaneslanes are safe, checked against a real run of the loop.callsmax_vector_width - run_loop(sim, a, b, w, r)The scalar loop's answer, computed on the vector path when safe and on the scalar path otherwise.exact counts are tested
Next. When the compiler refuses a loop, or vectorizes it badly, you can write the vector code yourself. The next topic does that with intrinsics: each LaneSim instruction becomes a function you call by name, you meet a fused multiply-add that does two operations in one instruction, and you will see how a name like _mm256_add_pd is built from the register width and the type of the numbers.
Lab · what's graded
4 tasks · 100 pts- Measure the gap with
dependence_distance25 pts - Find the widest safe vector with
max_vector_width25 pts - Give the verdict with
can_vectorize25 pts - Choose the path in
run_loop25 pts