Maps to: Stanford CS149 Fall 2025, Lecture 3 (Sep 30), slide deck
03_multicore2-ispc(56 slides). The lecture opened by finishing Lecture 2’s hardware multi-threading, which these notes cover in Lecture 2 §6. The ISPC material continues at the start of Lecture 4; it is taught here in full. Sources: the public Fall 2025 slides; the 2023 lecture video. Every experiment and number below was written for these notes and run on the author’s machine (Apple M4 Pro, 8 performance + 4 efficiency cores, NEON; clang 21, macOS 27). ISPC itself is not installed there: its meaning is shown on an emulator, and its implementation cost is measured with hand-written SIMD code. Code:code/lecture03/. Reading time: ~75 minutes for the prose; ~20 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Distinguish latency (延迟) from bandwidth / throughput (带宽 / 吞吐量), and explain how pipelining (流水线) raises throughput without changing latency, and why a pipeline runs at the speed of its slowest stage.
- Explain why a processor with plenty of hardware threads can still be stalled most of the time, and recognize a bandwidth-bound (带宽受限) computation from its ratio of arithmetic to bytes moved.
- Estimate a kernel’s efficiency from its bytes per operation and the machine’s bandwidth (slide 22’s < 1% on a GPU, ~3% on a CPU), and confirm it with a measurement.
- Explain the difference between a programming model’s semantics (语义) — what a program means — and its implementation (实现) — how a machine executes it.
- Read and write ISPC-style SPMD (single program, multiple data, 单程序多数据) code: gangs, program instances,
programCount,programIndex,uniformvs. varying,foreach, and cross-instance operations likereduce_add. - Explain why interleaved (交错) assignment of iterations to program instances is cheaper than blocked (分块) assignment on SIMD hardware, and spot SPMD programs whose output is undefined.
0.2 Prerequisites and scope
- Prerequisites: Lecture 2 — SIMD lanes, masks, hardware threads, latency hiding, Little’s law. Lecture 1’s memory hierarchy.
- Scope: the first half is about the memory system as a throughput resource. The second half is about one programming model, ISPC, as a case study of abstraction vs. implementation. ISPC tasks (its multi-core feature) are only introduced; they become central in Lectures 4–5 and in PA1. DRAM internals are Lecture 12.
0.3 Section → code map
| Section | Idea | Demo in code/lecture03/ |
|---|---|---|
| §1 | latency vs. throughput, pipelining | 01_latency_vs_bandwidth.py Part A |
| §2 | a core starved by memory bandwidth | 01_latency_vs_bandwidth.py Parts B–C |
| §3 | the bandwidth wall of a real chip; arithmetic intensity | 02_bandwidth_meter |
| §5–§6 | ISPC semantics: gangs, foreach, uniform, reductions | 03_ispc_semantics.py (+ spmd.py) |
| §5.4 | the cost of blocked vs. interleaved lanes on real SIMD | 04_gang_assignment |
Run them all with cd code/lecture03 && make run (~2 seconds).
0.4 Notation
- GB/s = 10⁹ bytes per second (the convention for memory bandwidth). “Bytes” here means the bytes a program explicitly reads and writes in its source code.
- Arithmetic intensity (算术强度) = floating-point operations per byte moved to or from memory.
- In ISPC code, uniform means “one value shared by all program instances”; anything not uniform is varying (各实例不同的).
Part 1 · Latency and bandwidth
1. Two ways to be fast
1.1 A thought experiment
The lecture opens with a question. Take two vectors A and B of millions of floats and compute C[i] = A[i] × B[i]. Every element is independent, so this is perfectly data parallel. Is it a good program for a throughput-oriented processor like an NVIDIA V100, with 80 cores and 5,120 floating-point ALUs?
It sounds ideal. The answer, which this half of the lecture builds up to, is that the GPU’s ALUs will sit idle more than 99% of the time. To see why, we need two words that everyday language mixes up.
1.2 Latency vs. throughput: the highway
The slides’ analogy: driving from San Francisco to Stanford, 50 km at 100 km/h.
- Latency — how long one car takes: 0.5 hours.
- Throughput — how many cars arrive per hour. If only one car may be on the highway at a time, it is 2 cars/hour.
Two ways to raise throughput:
- Drive faster (200 km/h): latency 0.25 h, throughput 4 cars/hour. This improves both, but it is hard: it is the “raise the clock frequency” strategy that hit the power wall (Lecture 1).
- Build more lanes: 4 lanes, 8 cars/hour. Latency unchanged.
And a third, the best: use the highway more efficiently. Let cars follow each other 1 km apart: at 100 km/h, a car arrives every 1/100 hour, 100 cars/hour per lane, 400 with 4 lanes. Each car still takes 0.5 hours. Throughput rose 200× without any car going faster.
Memory works the same way. Memory latency is the time from requesting data to receiving it (~120 ns on the author’s machine). Memory bandwidth is the rate at which the memory system can deliver data, e.g. 200 GB/s. They are independent: a memory system can have high latency and high bandwidth at the same time, by having many requests in flight.
1.3 Pipelining: the laundry room
The slides’ second analogy: a load of laundry needs washing (45 min), drying (60 min) and folding (15 min). Latency for one load: 2 hours. To do many loads:
- Duplicate resources: two washers, two dryers, a friend. 2 loads per 2 hours = 1 load/hour, at twice the equipment.
- Pipeline: start the second load in the washer as soon as the first moves to the dryer. Demo 01 computes the schedule with the classic pipeline recurrence:
load | wash ends | dry ends | fold ends
1 | 45 min | 105 min | 120 min
2 | 90 min | 165 min | 180 min
3 | 135 min | 225 min | 240 min
4 | 180 min | 285 min | 300 min
Each load still takes 2 hours; after the first, one load finishes every 60 minutes, the time of the slowest stage (the dryer). Four loads take 300 minutes instead of 480, with one washer and one dryer. The slides’ “connected pipes” make the same point: a 100 L/s pipe feeding a 50 L/s pipe carries 50 L/s. A system’s throughput is set by its narrowest part. That sentence is the whole of §2.
1.4 Instruction pipelines
Processors pipeline instructions the same way. Slide 25’s four-stage pipeline (fetch, decode, execute, write-back) takes 4 clocks per instruction, but starts one every clock:
instr 0 | IF D EX WB
instr 1 | IF D EX WB
instr 2 | IF D EX WB
instr 3 | IF D EX WB
Real CPU pipelines have up to ~20 stages. So when we say a core “does one multiply per clock”, we mean throughput, never latency. A multiply takes ~4 clocks (Lecture 1, demo 05); a new one can start every clock if it does not depend on the ones in flight.
2. A processor limited by memory bandwidth
2.1 The slides’ machine
Slides 17–20 consider threads that repeat three dependent instructions:
X = load 64 bytes
Y = add X + X
Z = add X + Y
running on a multi-threaded core that
- executes one math instruction per clock;
- can issue loads in parallel with math (to a separate load/store unit);
- receives 8 bytes per clock from memory, so a 64-byte load takes 8 clocks to transfer;
- has plenty of hardware threads, so latency can be hidden as in Lecture 2.
2.2 What happens
01_latency_vs_bandwidth.py simulates it clock by clock (memory latency 4 clocks, up to 3 loads in flight):
ALU | ............AA......AA......AA......AA......AA......AA......
bus | ========================================================
steady state: ALU busy 25%, memory bus busy 100%
After the first load arrives, the memory bus (=) never rests, yet the ALU (A) is busy only 2 clocks out of every 8. Each load brings 64 bytes in 8 clocks, and those bytes feed exactly 2 adds. The rate of instructions is set by the rate at which memory provides data (slide 20). The core is bandwidth-bound: it is stalled 75% of the time although it has many threads, because every thread is waiting for the same overloaded bus.
2.3 Latency does not matter here — throughput does
Slide 20 asks you to convince yourself that, in steady state, the core’s underutilization depends only on instruction and memory throughput, not on memory latency or on how many requests may be outstanding. Demo 01 checks this by sweeping both:
| latency (clocks) | max loads in flight | ALU utilization | bus utilization |
|---|---|---|---|
| 0 | 1 | 25.0% | 100% |
| 20 | 1 | 7.1% | 28.6% |
| 20 | 4 | 25.0% | 99.9% |
| 100 | 4 | 7.4% | 29.6% |
| 100 | 16 | 24.9% | 99.5% |
| 100 | 32 | 24.9% | 99.5% |
Latency and the outstanding-load limit only decide whether the bus can be kept busy. That is Little’s law from Lecture 2: with latency 100 and 8 clocks per transfer, ~14 loads must be in flight. Once it is busy, the ALU gets exactly 25%, whatever the latency. Hiding latency (Lecture 2) is necessary, but it cannot create bandwidth.
2.4 More arithmetic per byte moves the bottleneck
Keep the loads the same but do more math with each one:
| adds per 64-byte load | ALU utilization | bus utilization | bound by |
|---|---|---|---|
| 1 | 12.5% | 99.9% | memory bandwidth |
| 2 | 25.0% | 99.9% | memory bandwidth |
| 4 | 49.9% | 99.9% | memory bandwidth |
| 8 | 99.9% | 99.9% | both (balanced) |
| 16 | 99.9% | 52.4% | ALU |
| 32 | 99.9% | 27.5% | ALU |
The ratio of math to bytes decides which resource limits the program. Below 8 adds per 64 bytes, adding math is free: the ALU was idle anyway. Above it, the ALU limits and the memory bus starts to idle. Lecture 6 names this ratio arithmetic intensity and builds the roofline model on it.
3. The bandwidth wall on a real chip
3.1 Slide 22’s arithmetic
Back to C[i] = A[i] × B[i]. Each multiply needs two 4-byte loads and one 4-byte store: 12 bytes per multiply.
- NVIDIA V100: 5,120 FP32 multiplies per clock × 1.6 GHz = 8.2·10¹² multiplies/s. To feed them it would need 8.2·10¹² × 12 B ≈ 98 TB/s. Its HBM2 memory delivers 0.9 TB/s, so efficiency is 0.92%.
- An 8-core Xeon E5v4 at 3.2 GHz, one 8-wide multiply per core per clock = 205·10⁹ multiplies/s. Its 76 GB/s memory supplies 76/12 = 6.3·10⁹ per second: ~3% efficiency.
The GPU is still ~12× faster in absolute terms, because its memory is 12× faster. Both chips leave nearly all their arithmetic idle.
3.2 Measured on the author’s machine
02_bandwidth_meter runs C = A*B on three 64 MiB arrays, ~10× bigger than all caches, so every byte comes from DRAM:
| threads | read only | C = A*B | speedup of C = A*B |
|---|---|---|---|
| 1 | 79 GB/s | 112 GB/s | 1.00× |
| 2 | 155 GB/s | 177 GB/s | 1.58× |
| 4 | 192 GB/s | 186 GB/s | 1.67× |
| 8 | 243 GB/s | 215 GB/s | 1.92× |
| 12 | 238 GB/s | 214 GB/s | 1.92× |
Three observations:
- The plateau. Beyond ~6 threads, more cores add nothing: the memory system delivers ~200–245 GB/s, whoever asks. (Apple’s published figure for the M4 Pro is 273 GB/s; we reach ~80–90% of it.)
- One core already takes half. One M4 core moves ~110 GB/s by itself, because it keeps many misses in flight (Lecture 2, demo 05: ~34). On the class machines’ Intel CPUs a single core gets a smaller share, and the curve climbs more before it flattens.
- Efficiency. 215 GB/s ÷ 12 bytes = 17.9 GFLOP/s, which is 3.0% of the 591 GFLOP/s that the same 8 threads reach on a compute-heavy kernel (§3.3). Slide 22 predicted about 3% for a CPU, and that is what we measured.
Bandwidth measurements are noisy; the README lists run-to-run ranges. The plateau and the ~3% are stable across runs.
Caches have much more bandwidth. The same kernel on arrays small enough to stay in each core’s L1/L2 (192 KiB per thread) streams 815 GB/s with 8 threads, 3.7× the DRAM rate. Every core has its own caches, so cache-resident work keeps scaling with cores.
3.3 How much math per byte does it take?
Demo 02 Part C keeps the 12 bytes per element and adds arithmetic. Each element gets x = a·b, then K fused multiply-adds, for 2K + 1 FLOPs. Measured on 8 threads:
| K | FLOPs per byte | GFLOP/s | GB/s | limited by |
|---|---|---|---|---|
| 1 | 0.25 | 45 | 179 | memory bandwidth |
| 4 | 0.75 | 122 | 163 | memory bandwidth |
| 16 | 2.75 | 428 | 156 | memory bandwidth |
| 32 | 5.42 | 509 | 94 | arithmetic |
| 128 | 21.4 | 591 | 28 | arithmetic |
| 256 | 42.8 | 563 | 13 | arithmetic |
Up to K = 16 the GB/s stays roughly constant and each doubling of K nearly doubles GFLOP/s. The extra arithmetic is free, because the cores were waiting for memory anyway. That is slide 24’s “the math is free”. Beyond ~3 FLOPs per byte, the ALUs become the limit and the memory system idles. A kernel needs at least ~3 FLOPs per byte to use this chip’s arithmetic; C = A*B has 0.08.
(The first version of this sweep used only 4 independent vectors per loop iteration, and its GFLOP/s fell for large K. Each iteration was then a long dependency chain, Lecture 2’s ILP lesson again. The final version keeps 12 chains in flight; see the README.)
3.4 High-bandwidth memory
Since bandwidth limits so many programs, accelerators put their memory physically close. The V100 uses HBM2 (高带宽内存): DRAM dies stacked next to the GPU, connected by a 4,096-bit-wide interface, giving 900 GB/s. Apple’s chips use a wide LPDDR interface on the package. Lecture 12 explains how DRAM and HBM work inside.
3.5 Bandwidth is the critical resource
Slide 24’s conclusion: in modern computing, bandwidth is the critical resource. Performant parallel programs
- fetch data from memory less often: they reuse data a thread loaded before (temporal locality) and share data among threads that cooperate;
- prefer doing more arithmetic to storing and reloading values, because the math is free;
- above all, access memory infrequently relative to the work they do.
The slides end with a point that will come back in every lecture from here on. Overcoming bandwidth limits is often the most important challenge in programming throughput-oriented machines. Lecture 6 (locality, roofline), Lecture 9 (GEMM blocking, FlashAttention) and Lecture 11 (asynchronous data movement) are all about it.
Part 2 · Abstraction vs. implementation: ISPC
4. Two questions about every programming model
The second half has one theme, stated on slide 26: abstraction vs. implementation. Confusing what a programming abstraction means with how it happens to be implemented is, according to the slides, a common cause of confusion in this course. For every programming model, ask two separate questions:
- Semantics. Given a program and the meaning of its operations, what answer does it compute? What may run in parallel, and which orders of execution are allowed?
- Implementation (scheduling). How will that answer be computed on a parallel machine? Which thread, core, execution unit or SIMD lane does each operation?
The goal the slides set: given a program and knowledge of how its model is implemented, you should be able to trace in your head what each part of the machine does during each step.
The case study is ISPC, the Intel SPMD Program Compiler (open source, ispc.github.io). It is a C-like language for writing SIMD code that compiles to SSE/AVX on x86 and to NEON on Arm. Matt Pharr’s blog series “The Story of ISPC” (2018) tells how it came about, and the slides recommend it.
5. sinx in ISPC
5.1 Calling an ISPC function
The C++ program calls ispc_sinx(N, terms, x, result) like any function. What happens inside is different (slides 31–33):
- the call spawns a gang (组) of
programCountprogram instances (程序实例); - all instances run the ISPC function’s code concurrently; each has its own copy of the local variables;
- when the function returns, all instances have completed, and the C++ code continues sequentially.
This is the SPMD model: define one function, run many instances of it in parallel on different data. Each instance can be thought of as a logical thread of control, a little like an ISPC version of a CUDA thread.
5.2 programCount, programIndex, uniform
The ISPC version of sinx, from slide 32:
export void ispc_sinx(uniform int N, uniform int terms,
uniform float* x, uniform float* result)
{
// assumes N % programCount == 0
for (uniform int i = 0; i < N; i += programCount) {
int idx = i + programIndex;
float value = x[idx];
float numer = x[idx] * x[idx] * x[idx];
uniform int denom = 6; // 3!
uniform int sign = -1;
for (uniform int j = 1; j <= terms; j++) {
value += sign * numer / denom;
numer *= x[idx] * x[idx];
denom *= (2*j+2) * (2*j+3);
sign *= -1;
}
result[idx] = value;
}
}
The new keywords (slide 34):
programCount: the number of instances in the gang, the same for all of them (uniform).programIndex: this instance’s id, 0 … programCount−1. Different in each instance (varying).uniform: a type modifier meaning “all instances have the same value of this variable”. The slides stress that it is purely an optimization: it is not needed for correctness.denom,sign,iandjare the same in every instance, so they can live in one scalar register instead of a vector.
So instance k computes elements k, k + programCount, k + 2·programCount, … This is an interleaved assignment of array elements to program instances.
5.3 How the gang is implemented: SIMD
How does a compiler run 8 “concurrent instances”? Slide 36: ISPC implements the gang with SIMD instructions. The number of instances in a gang is the SIMD width of the hardware, or a small multiple of it (8 or 16 for AVX2, 4 or 8 for NEON). Each instance is one lane:
- a varying variable like
valueis a vector register, one lane per instance; - a uniform variable like
denomis an ordinary scalar register; - an
ifon varying data becomes masked execution, exactly as in Lecture 2 §4.4; - the compiler emits one object file with a normal C function that contains vector instructions.
So “concurrent instances” is the abstraction, and SIMD lanes running in lockstep are the implementation. The whole gang runs on one core. On the class machines, everything shown so far uses one of the four cores. ISPC’s multi-core feature is tasks (§6.6).
5.4 Interleaved vs. blocked assignment
Slide 37 rewrites sinx with a blocked assignment. Each instance takes a contiguous block of N/programCount elements:
uniform int count = N / programCount;
int start = programIndex * count;
for (uniform int i = 0; i < count; i++) {
int idx = start + i;
...same body...
}
Both versions are correct and compute the same results. Which instance computes which element (16 elements, gang of 8):
interleaved (slide 35): 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
blocked (slide 38): 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7
Now think about the implementation. Each step of the loop executes float value = x[idx] once, for all 8 instances at once, as one vector instruction:
- interleaved: the 8 instances want x[i], x[i+1], …, x[i+7], which are contiguous in memory. One packed vector load (
vmovapson AVX,vld1q_f32on NEON) does it (slide 39). - blocked: instance k wants x[k·count + i]. The 8 addresses are far apart, so the gang needs a gather (聚集读): a more complex, more costly instruction (
vgatherdpson AVX2), or several separate loads. Storingresult[idx]needs a scatter (分散写), which AVX2 does not even have (slide 40).
03_ispc_semantics.py runs both versions, plus the foreach version of §5.5, on the gang emulator (spmd.py), with N = 1024 and 5 terms:
| version | vector instructions | packed loads | gathers | packed stores | scatters | same answer |
|---|---|---|---|---|---|---|
| interleaved | 3,840 | 128 | 0 | 128 | 0 | yes |
| blocked | 3,841 | 0 | 128 | 0 | 128 | yes |
| foreach | 3,712 | 128 | 0 | 128 | 0 | yes |
Same meaning, same arithmetic, different memory instructions. What does that cost on real hardware? 04_gang_assignment runs identical NEON arithmetic with the two mappings. NEON has no gather instruction, so the blocked version uses 4 single-lane loads and 4 single-lane stores per vector.
| kernel | blocked ÷ interleaved time |
|---|---|
| light (1 FMA per element), data in L1 | 2.51× |
| light, ~64 MiB arrays in DRAM | 2.80× |
| sinx, 10 terms (~40 operations per element) | 1.09× |
When memory instructions are a large part of the work, the blocked mapping is ~2.5–2.8× slower. When the arithmetic dominates, it hardly matters. Either way the answers are identical. The mapping is an implementation choice, and interleaving is the cheap one for SIMD.
Contrast this with Lecture 1, demo 2 and Lecture 2, demo 01, where threads worked on contiguous blocks and that was good: each core streams its own region through its own cache. The best assignment depends on the implementation of the workers. For SIMD lanes, which share one instruction and want neighbouring data, interleaving wins. For cores with their own caches, blocks are usually better (Lecture 6 explains why, through locality).
5.5 foreach: raising the level of abstraction
Writing programIndex arithmetic by hand is error-prone, so ISPC offers foreach (slide 41):
foreach (i = 0 ... N) {
float value = x[i];
...
result[i] = value;
}
foreach declares parallel loop iterations: these are the iterations the entire gang must perform. Each instance does not do all of them. The ISPC implementation decides which instance does which iteration. Slide 42 lists four legal implementations:
- program instance 0 executes all iterations;
- interleaved: iteration
loop_i + programIndex; - blocked: each instance takes a contiguous range;
- dynamic: instances repeatedly grab the next iteration from a shared counter.
Demo 03 Part B runs y[i] = 2*x[i] + 1 for 1,000 iterations (not a multiple of 8) all four ways:
| implementation | vector instructions | lane utilization | packed | gather/scatter | same answer |
|---|---|---|---|---|---|
| 1: instance 0 does all | 4,000 | 12.5% | 2,000 | 0 | yes |
| 2: interleaved | 500 | 100% | 250 | 0 | yes |
| 3: blocked | 500 | 100% | 0 | 250 | yes |
| 4: dynamic | 500 | 100% | 250 | 0 | yes |
All four are correct. Only cost differs, because foreach promises nothing about the mapping. The real ISPC compiler uses the interleaved mapping, for the reason §5.4 measured. The partial last group of iterations runs with the extra lanes masked off.
In simple cases foreach lets you write the program almost as if it were sequential: “independently, for each element, do this”.
6. Writing correct SPMD programs
6.1 A correct program and an undefined one
Slide 44’s absolute_repeat writes |x[i]| twice into y:
foreach (i = 0 ... N) {
if (x[i] < 0) y[2*i] = -x[i];
else y[2*i] = x[i];
y[2*i+1] = y[2*i];
}
Its stores are strided (scatters), but every address is written by exactly one iteration, so the result is well defined. The emulator confirms: 0 write conflicts.
Slide 45’s shift_negative is different:
foreach (i = 0 ... N) {
if (i >= 1 && x[i] < 0) y[i-1] = x[i];
y[i] = x[i];
}
Iteration i may write y[i-1], and iteration i−1 also writes y[i-1]. Which write lands last depends on how iterations are mapped to instances and in what order the vector stores happen. Demo 03 runs it on x = 3, −1, 4, −1, −5, 9, −2, 6, 5, −3, 5, 8:
sequential C loop : y = -1 -1 -1 -5 -5 -2 -2 6 -3 -3 5 8
gang of 8, interleaved : y = 3 -1 4 -1 -5 9 -2 6 5 -3 5 8 (write conflicts: 5)
gang of 4, interleaved : y = 3 -1 4 -5 -5 9 -2 6 5 -3 5 8 (write conflicts: 5)
gang of 8, blocked : y = -1 -1 -1 -1 -5 9 -2 6 -3 -3 5 8 (write conflicts: 2)
gang of 1, interleaved : y = -1 -1 -1 -5 -5 -2 -2 6 -3 -3 5 8 (write conflicts: 0)
Four implementations, four different outputs. The output of this program is undefined (slide 45). A gang of one instance reproduces the sequential answer, so a test on a scalar machine would pass. That is exactly why such bugs are dangerous: a parallel program that is correct only for one programCount, or one mapping, is a bug, even if it passes every test you ran.
6.2 Summing an array: two type errors
Slide 46 shows two wrong ways to sum an array in ISPC:
sum_incorrect_1declaresuniform float sumand doessum += x[i]insideforeach. Each instance has a different x[i], so which value should go into the one shared sum? ISPC rejects this at compile time: a varying value cannot be assigned to a uniform variable.sum_incorrect_2declaresfloat sum(varying) and returns it from a function whose C++ caller expects one float. Many copies cannot be returned as one, so ISPC rejects this too.
The emulator raises the same two errors (demo 03 Part D).
6.3 The right way: per-instance partial sums + reduce_add
Slide 47:
export uniform float sum_array(uniform int N, uniform float* x) {
uniform float sum;
float partial = 0.0f;
foreach (i = 0 ... N) {
partial += x[i]; // each instance: a private partial sum
}
sum = reduce_add(partial); // cross-instance: add up the partials
return sum;
}
Each instance accumulates its own partial sum, with no communication. Then reduce_add, a cross-instance operation (跨实例操作) from ISPC’s standard library, adds the programCount partial sums into one uniform value. The slides show that this runs much like hand-written AVX code: a vector accumulator updated with one vector add per 8 elements, stored at the end to a temporary array, then 8 scalar adds. The slides offer it as a self-test: if you understand why that AVX code correctly implements the gang’s semantics, you understand ISPC.
One consequence that is easy to miss: the gang adds the numbers in a different order from a sequential loop. Floating-point addition is not associative, so the answer can change in its last digits. Demo 03 sums 4,096 floats in float32:
sum_array with reduce_add(partial) -> 31.3477402
sequential float loop -> 31.3477230
exact (double precision) -> 31.3477368
Here the parallel answer is actually closer to the exact sum: eight short running sums lose less precision than one long one. Either way, a parallel reduction does not reproduce the sequential result bit for bit. Tests of parallel code must compare floating-point results with a tolerance.
6.4 Cross-instance operations
ISPC’s standard library lets instances cooperate (slide 48):
| operation | meaning |
|---|---|
uniform int64 reduce_add(int32 x) | sum of x over all instances |
uniform int32 reduce_min(int32 a) | minimum over all instances |
int32 broadcast(int32 value, uniform int index) | every instance gets instance index’s value |
int32 rotate(int32 value, uniform int offset) | instance i gets the value of instance (i + offset) % programCount |
On SIMD hardware these are lane-shuffle instructions. Slide 53 combines them into a product of 8 numbers in log₂ 8 = 3 steps (for a gang of 8):
float val1 = x[programIndex];
float val2 = shift(val1, 1);
if (programIndex % 2 == 0) val1 = val1 * val2;
val2 = shift(val1, 2);
if (programIndex % 4 == 0) val1 = val1 * val2;
val2 = shift(val1, 4);
if (programIndex % 8 == 0) *result = val1 * val2;
The emulator computes the product of (1.5, 2, −1, 3, 0.5, 4, 2, −0.25) as 9 in 15 vector instructions, matching the sequential answer. This log-step pattern, where each step combines pairs that are twice as far apart, comes back as the parallel reduction and scan of Lecture 8.
6.5 How low-level should a language be?
ISPC is deliberately low-level (slide 52). Exposing programIndex and programCount lets the programmer decide exactly what work and what data each instance handles, which makes code like vec8product possible. It also makes undefined programs possible (§6.1), and programs that are correct only for one programCount.
The slides sketch two alternatives:
- No
programIndex/programCount; onlyforeach. Then there is almost no need to think about instances. Everything outside aforeachmust be uniform values and uniform logic. (Why? WithoutprogramIndex, nothing outside aforeachcan differ between instances.) - No array indexing at all. The programmer supplies a function, and the system applies it to every element of a collection:
map(f, collection). This is NumPy’s and PyTorch’s model (Z = X + Yon whole arrays), and the subject of Lecture 8. The programmer writes no loops and no indices, so many bugs become impossible, and the implementation has full freedom to choose the mapping.
The trade-off runs through the whole course. Higher-level abstractions are safer and give the implementation more freedom; lower-level ones give the programmer more control.
6.6 ISPC tasks: using all the cores
Everything above runs on one core: a gang is SIMD within one thread. To use several cores, ISPC has a second abstraction, the task. launch[n] f(...) creates n tasks, and the ISPC runtime runs them on a pool of worker threads, one per core. Each task is itself a gang. Lecture 4 §3 shows how the runtime assigns tasks to workers, and PA1 asks you to measure what tasks add on top of gangs.
7. Abstraction vs. implementation, everywhere
| abstraction (what the programmer says) | possible implementations (what the machine does) |
|---|---|
| a gang of programCount concurrent instances | SIMD lanes in lockstep on one core, with masks |
foreach over N iterations | instance 0 alone; interleaved; blocked; dynamic |
uniform value | one scalar register (purely an optimization) |
reduce_add | vector adds, then a horizontal sum (some order of additions) |
launch[n] tasks | a thread pool with a shared “next task” counter |
std::thread | an OS thread placed on some core’s execution context |
C = A * B on arrays | SIMD loads, multiplies and stores, limited by DRAM bandwidth |
A correct program means the same under every implementation. A fast program is written knowing which implementation it will get. Both halves of this lecture show the same thing: to predict performance, you must look through the abstraction at what it does to the hardware — in the first half, to the memory system.
Summary
- Latency is the time one item takes; bandwidth/throughput is items per second. Pipelining and more lanes raise throughput without changing latency. A pipeline runs at the pace of its slowest stage.
- A core fed by memory runs at the rate memory delivers data. The slides’ core (1 add per clock, 8 bytes per clock, 2 adds per 64 bytes) is 25% busy whatever the latency, once enough loads are in flight. Latency hiding is necessary, but it cannot create bandwidth.
- Element-wise C = A × B needs 12 bytes per multiply: < 1% of a V100’s arithmetic, ~3% of a CPU’s. Measured on the M4 Pro: ~215 GB/s for the whole chip (one core already gets ~110), and 3.0% of its arithmetic throughput. Caches stream ~4× faster.
- Extra arithmetic per byte is free while a kernel is memory-bound; this chip needs ~3 FLOPs per byte to become compute-bound. Bandwidth is the critical resource: reuse data, share it, recompute rather than reload.
- Abstraction vs. implementation: semantics say what a program computes; implementation says how. ISPC’s SPMD gang of program instances is implemented as SIMD lanes.
programIndex/programCountexpose the mapping;uniformis an optimization;foreachleaves the mapping to the compiler. - Interleaved assignment lets a gang use packed loads; blocked needs gathers and scatters (2.5–2.8× slower for a light kernel on NEON; ~1.1× for sinx). Same answers either way.
- Programs where two iterations write the same location have undefined output, and may still pass tests. Reductions use cross-instance operations (
reduce_add) and change the order of floating-point additions.
Common pitfalls
- Assuming more cores always help a data-parallel loop. Bandwidth-bound kernels plateau after a few cores (here ~6, with ~1.9× total).
- Confusing “one per clock” (throughput) with “takes one clock” (latency).
- Thinking that hiding latency fixes a memory-bound program. It only lets you reach the bandwidth limit.
- Picking the blocked mapping for SIMD lanes because blocks are good for threads. Lanes share an instruction and want contiguous data; cores have their own caches and want contiguous blocks.
- Writing
foreachbodies where two iterations touch the same output location. The result is undefined even if it looks right on your machine. - Expecting a parallel float sum to equal the sequential one bit for bit. Compare with a tolerance.
- Believing
uniformchanges the meaning of a program. It is an optimization (and a type rule): values that are the same everywhere can live in scalar registers.
Exercises
-
Pipelines. A three-stage pipeline has stage times 3, 7 and 4 ns. What are the latency of one item and the steady-state throughput? If you could split one stage into two equal halves, which stage, and what would the new throughput be?
Answer
Latency 3 + 7 + 4 = 14 ns; throughput one item per 7 ns (the slowest stage), ~143 M items/s. Split the 7-ns stage into two 3.5-ns stages: the slowest stage becomes 4 ns, so one item per 4 ns (250 M items/s); latency stays 14 ns. -
The slides’ core. Memory delivers 16 bytes per clock and each 64-byte load feeds 2 adds; the core does 1 add per clock. What is the steady-state ALU utilization with enough loads in flight? With a latency of 60 clocks, how many loads must be in flight?
Answer
A 64-byte line now takes 4 clocks and feeds 2 adds: 2/4 = 50%. Each load occupies 60 + 4 = 64 clocks from issue to data, and one completes every 4 clocks, so 64/4 = 16 loads must be in flight (Little's law). Check:simulate_core(20000, bytes_per_clock=16, latency=60, max_outstanding=16). -
Efficiency estimate. A kernel computes y[i] = a·x[i] + y[i] on floats (2 FLOPs; reads x and y, writes y). On a chip with 200 GB/s and 600 GFLOP/s, what is the best possible GFLOP/s and efficiency?
Answer
Bytes per element: 4 (x) + 4 (y read) + 4 (y write) = 12, for 2 FLOPs: 1/6 FLOP per byte. 200 GB/s × 1/6 = 33 GFLOP/s, 5.6% of peak. (The hardware may move even more bytes than the program names; Lecture 14 explains write policies.) -
Mapping for a gang. A gang of 8 runs
foreach (i = 0 ... 64) y[i] = x[63 - i];. With the interleaved mapping, are the loads packed or gathers? What simple SIMD trick makes them cheap anyway?Answer
The instances of one step want x[63−i], …, x[56−i]: contiguous, but in reverse lane order. A strict "lane k reads base + k" check (as inspmd.py) calls it a gather. Real compilers load the 8 contiguous values with one packed load and reverse the lanes with one shuffle instruction, which is cheap. -
Undefined or not? Which of these
foreach (i = 0 ... N)bodies have well-defined results? (a)y[i] = x[i] + x[i+1];(b)x[i] = x[i] + 1;(c)y[i/2] = x[i];(d)y[N-1-i] = x[i];Answer
(a) defined: reads may overlap, but each y[i] has one writer and x is only read. (b) defined: each iteration reads and writes only its own x[i]. (c) undefined: iterations 2k and 2k+1 both write y[k]. (d) defined: a permutation, one writer per location. -
Uniform. In ISPC’s sinx, why is it legal to declare
denomuniform, but notnumer? What would happen to the generated code ifdenomwere declared varying?Answer
denomdepends only on the loop counter j, which is the same for all instances, so every instance always holds the same value.numerstarts as x[idx]³, which differs per instance. As varying,denomwould occupy a vector register, and each update would be a vector multiply computing the same value in every lane. The results are the same, with a little more work and register pressure (uniform is an optimization, not semantics).
The related assignment: Programming Assignment 1
PA1’s later parts use exactly this lecture’s ideas. One part runs ISPC versions of a computation, first as a single gang and then with tasks, and asks you to explain the speedups against the SIMD width and the number of cores. Another part asks which inputs make an ISPC program run with high or low SIMD efficiency (Lecture 2’s divergence). A third measures a bandwidth-bound kernel and asks why it barely speeds up, and how much memory traffic it really generates. These notes do not provide solutions; the demos here practise the same reasoning on different kernels.
Further reading
- The Fall 2025 slides for this lecture and the 2023 lecture video.
- Matt Pharr, “The Story of ISPC” (blog series, 2018), and M. Pharr and W. R. Mark, “ispc: A SPMD Compiler for High-Performance CPU Programming”, InPar 2012.
- The ISPC User’s Guide (ispc.github.io):
uniformvs.varying,foreach, the standard library’s cross-program-instance operations, tasks. - J. D. McCalpin, “Memory Bandwidth and Machine Balance in Current High Performance Computers”, IEEE TCCA Newsletter, 1995. The STREAM benchmark, the standard way to measure what demo 02 measures.
- S. Williams, A. Waterman and D. Patterson, “Roofline: An Insightful Visual Performance Model for Multicore Architectures”, CACM 2009 (preview of Lecture 6).
Preview of Lecture 4 — Parallelizing code: the thought process
Today’s programs were already parallel. Lecture 4 asks how to make a program parallel. You identify independent work (decomposition), give it to workers (assignment), and coordinate them (orchestration). It introduces Amdahl’s law, which shows how a small serial part limits a large machine. Then it works through a 2D grid solver whose obvious loop has dependencies everywhere, until a reordering (red-black) exposes parallelism. The solver is written twice, in a data-parallel style and with threads, locks and barriers in a shared address space.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| latency | 延迟 |
| bandwidth / throughput | 带宽 / 吞吐量 |
| pipelining / pipeline stage | 流水线 / 流水级 |
| bottleneck (slowest stage) | 瓶颈(最慢的一级) |
| instruction pipeline (fetch, decode, execute, write-back) | 指令流水线(取指、译码、执行、写回) |
| memory bandwidth / bandwidth-bound | 内存带宽 / 带宽受限 |
| compute-bound | 计算受限 |
| outstanding (in-flight) request | 未完成(在途)请求 |
| arithmetic intensity | 算术强度 |
| efficiency (fraction of peak) | 效率(占峰值的比例) |
| high-bandwidth memory (HBM) | 高带宽内存 |
| temporal locality / data reuse | 时间局部性 / 数据重用 |
| abstraction / implementation | 抽象 / 实现 |
| semantics / scheduling | 语义 / 调度 |
| SPMD (single program, multiple data) | 单程序多数据 |
| ISPC (Intel SPMD Program Compiler) | 英特尔 SPMD 程序编译器 |
| gang / program instance | 组 / 程序实例 |
| programCount / programIndex | 实例数 / 实例编号 |
| uniform / varying | 统一(所有实例相同) / 各实例不同 |
| interleaved / blocked assignment | 交错 / 分块分配 |
| packed (contiguous) vector load | 连续(打包)向量加载 |
| gather / scatter | 聚集读 / 分散写 |
| foreach | foreach(并行迭代声明) |
| undefined output / write conflict | 未定义的输出 / 写冲突 |
| cross-instance operation (reduce, broadcast, rotate, shift) | 跨实例操作(归约、广播、旋转、移位) |
| reduction / partial sum | 归约 / 部分和 |
| floating-point associativity | 浮点加法结合律 |
| type error (compile time) | (编译期)类型错误 |
| ISPC task / launch | ISPC 任务 / 启动 |
| map (over a collection) | 映射(对集合逐元素应用) |