Course contents 15 / 32

15 / 32 · Parallelism and Performance

Vectors, SIMD and GPUs

One instruction for many data elements: SIMD registers, vector processors and the RISC-V Vector extension with strip mining, a loop vectorized by the compiler and timed, GPUs with their warps and memory hierarchy, and the roofline model that tells arithmetic limits from memory limits.

On this page 6

The previous note gave a program several instruction streams, one per core, at the price of dividing the work and keeping private caches coherent. Much of the arithmetic a computer does is simpler than that: the same operation on every element of a long array. Brightening an image adds a constant to every pixel; a layer of a neural network multiplies a matrix by a matrix; a physics code updates every cell of a grid by one formula. A core that fetches, decodes, renames and schedules one instruction per element spends most of its energy on bookkeeping that is identical for every element. Data-level parallelism removes that bookkeeping: one instruction operates on many data elements at once. This note follows it from the SIMD registers of a CPU through vector processors and the RISC-V Vector extension to GPUs, measures what it gains on one loop, and ends with the roofline model, which says when the arithmetic is the limit and when memory is.

Notation. The running example is saxpy, yi←a xi+yiy_i \leftarrow a\,x_i + y_i for i=0,…,n−1i = 0, \dots, n - 1, on 32-bit floating-point numbers (“single-precision aa times xx plus yy”). For the RISC-V Vector extension, VLEN is the number of bits in one vector register, SEW the width of one element in bits, LMUL the number of registers grouped into one operand, and VLMAX=LMUL⋅VLEN/SEW\mathrm{VLMAX} = \mathrm{LMUL} \cdot \mathrm{VLEN}/\mathrm{SEW} the largest number of elements one instruction can process; vl\mathit{vl} is the number it actually processes, and AVL the number the program still has to process. For the roofline, PP is a machine’s peak arithmetic rate in FLOP/s, BB its memory bandwidth in bytes/s, and II the arithmetic intensity of a computation: floating-point operations per byte moved to or from memory.

Baseline: one element per instruction#

Scalar code processes one element per instruction. The integer version of the loop for RARS (the Code section runs it on ten elements) is

loop: lw   t0, 0(a2)      # t0 = x[i]
      lw   t1, 0(a3)      # t1 = y[i]
      mul  t0, t0, a1     # t0 = a * x[i]
      add  t1, t1, t0     # t1 = a * x[i] + y[i]
      sw   t1, 0(a3)      # y[i] = t1
      addi a2, a2, 4      # advance the pointers and the counter
      addi a3, a3, 4
      addi a0, a0, -1
      bnez a0, loop

Nine instructions per element, of which two do the arithmetic and three move data; the other four are loop overhead. Every one of them is fetched, decoded and, on the out-of-order core of the instruction-level parallelism note, renamed, queued, woken up and retired. A four-wide core needs at least 9/4=2.259/4 = 2.25 cycles per element even if no instruction ever waits. The work per element does not change from one element to the next, and nothing in the hardware takes advantage of that.

Flynn’s classification of computers names the alternatives (Patterson and Hennessy, 2020, §6.3): a single instruction stream on a single data stream (SISD) is the scalar core; multiple instruction streams on multiple data (MIMD) are the cores of the previous note; and a single instruction on multiple data (SIMD) is the subject of this note. Most parallel programs on MIMD hardware are written as one program that every core runs on its part of the data, the SPMD style (single program, multiple data).

SIMD instructions: several numbers in one register#

A SIMD extension adds wide registers that hold several numbers side by side, and instructions that operate on all of them at once. A 128-bit register holds four 32-bit floats, and one instruction multiplies or adds all four pairs. The four lanes are independent copies of a floating-point unit, controlled by one decoded instruction. ARM’s NEON and x86’s SSE use 128-bit registers, AVX and AVX2 256-bit, AVX-512 512-bit.

Worked example. Saxpy on 128-bit registers handles four elements per iteration: load four xx values, load four yy values, one fused multiply-add for all four, store four yy values, then the loop overhead. That is about eight instructions per four elements, two per element instead of the scalar loop’s nine.

SIMD extensions fix the width in the instruction set. A wider register needs new instructions and new compiled code: x86 went from 64-bit MMX through 128-bit SSE and 256-bit AVX to 512-bit AVX-512, and a program compiled for one width does not use the next. Arrays whose length is not a multiple of the width need a separate scalar loop for the last few elements, and loads of a full register are fastest when the address is a multiple of its size. Programs use SIMD in three ways: through a compiler that vectorizes loops automatically, through intrinsics (C functions that map to single SIMD instructions), or through libraries written with them.

What the compiler needs to vectorize a loop#

A compiler vectorizes a loop when it can prove that executing four iterations at once gives the same result as executing them one after another. For saxpy, clang at -O3 on the M1 reports vectorized loop (vectorization width: 4, interleaved count: 4) (the flag -Rpass=loop-vectorize prints it): four floats per 128-bit NEON register, and four such registers per iteration, sixteen elements, to give the out-of-order core independent work. Three things commonly prevent it:

  • A loop-carried dependence. In y[i] = y[i - 1] + x[i], each iteration needs the result of the previous one, so four iterations cannot run at once.
  • Possible aliasing. If x and y might overlap, storing four y values could change x values a later group reads. The restrict qualifier promises that they do not; without it the compiler adds a run-time overlap check or gives up. The next note treats aliasing in detail.
  • Control flow and calls. Branches inside the body must be turned into selects with a mask, and calls to functions the compiler cannot see stop it altogether.

Worked example (measured). The saxpy program of the Code section, one thread on an Apple M1 (macOS 26.5, Apple clang 21), with 2282^{28} element updates in total. With n=4,096n = 4{,}096 the two arrays take 32 KB and stay in the 128 KB first-level cache; with n=224n = 2^{24} they take 128 MB and come from main memory on every pass. One run of each build gave, in GFLOP/s (two operations per element):

Buildn=4,096n = 4{,}096, in cachen=224n = 2^{24}, from memory
-O01.451.39
-O3 -fno-vectorize -fno-slp-vectorize (scalar)6.023.41
-O3 (SIMD, 4 lanes)31.128.21

The machine was shared with other jobs, and eight runs of the -O3 build on different occasions ranged from 15.6 to 31.4 GFLOP/s in cache and from 5.4 to 8.2 from memory; the ratios below come from the single run in the table, in which the three builds ran one after another. Turning off optimization altogether costs a factor of about 20 in cache, mostly through loads and stores of the loop counter and pointers. Vectorization on top of an optimized scalar loop gains a factor of 5.2 when the data is in the cache, but only 2.4 when it comes from memory. At n=224n = 2^{24} the vectorized loop moves 1212 bytes per element (load xx, load yy, store yy) at 8.21 GFLOP/s, which is 49 GB/s: the loop now waits for memory, and wider registers would not make it faster. The roofline model below makes this precise.

Vector processors and the RISC-V Vector extension#

A vector architecture takes the idea further. Its registers hold many elements, typically tens to hundreds, and the hardware streams them through pipelined functional units, often several lanes wide. A vector instruction states up front that its element operations are independent, so the hardware does not need to check dependences between them, and one fetched instruction keeps the units busy for many cycles. Vector loads also accept a stride or a list of indices (a gather), so a column of a matrix or an indirect access is one instruction (Hennessy and Patterson, 2019, Chapter 4).

The RISC-V Vector extension (RVV) has 32 vector registers, v0–v31, each VLEN bits long. VLEN is a property of the implementation, not of the instruction set: the V extension requires at least 128, and a large machine may have 1,024 or more. Programs never assume a value. Instead, every loop asks the hardware how many elements it may process in this pass:

vsetvli rd, rs1, e32, m1, ta, ma   # rs1 = AVL; sets vl, writes it to rd

e32 sets SEW to 32 bits, m1 sets LMUL to 1, and ta, ma say that elements past vl\mathit{vl} and masked-off elements may be left with any value. The instruction computes VLMAX=LMUL⋅VLEN/SEW\mathrm{VLMAX} = \mathrm{LMUL} \cdot \mathrm{VLEN}/\mathrm{SEW} and sets vl\mathit{vl} by the rules of the specification (RISC-V International, 2021): vl=AVL\mathit{vl} = \mathrm{AVL} if AVL≤VLMAX\mathrm{AVL} \le \mathrm{VLMAX}; vl=VLMAX\mathit{vl} = \mathrm{VLMAX} if AVL≥2 VLMAX\mathrm{AVL} \ge 2\,\mathrm{VLMAX}; and in between, any value with ⌈AVL/2⌉≤vl≤VLMAX\lceil \mathrm{AVL}/2 \rceil \le \mathit{vl} \le \mathrm{VLMAX}, so that an implementation may split the last two passes evenly.

This loop is called strip mining: the array is cut into strips of at most VLMAX elements. In RVV, saxpy is the following loop. RARS does not implement the vector extension, so it is shown as an excerpt (not run here; it runs on a RISC-V machine or simulator with the V extension):

# saxpy: y[i] = a * x[i] + y[i] for i < n, with the RISC-V Vector extension
# arguments: a0 = n, fa0 = a, a1 = address of x, a2 = address of y
saxpy:
    vsetvli   t0, a0, e32, m1, ta, ma   # t0 = vl, the elements of this pass
    vle32.v   v1, (a1)                  # v1 = x[0 .. vl-1]
    vle32.v   v2, (a2)                  # v2 = y[0 .. vl-1]
    vfmacc.vf v2, fa0, v1               # v2 = a * v1 + v2, element by element
    vse32.v   v2, (a2)                  # y[0 .. vl-1] = v2
    sub       a0, a0, t0                # n = n - vl
    slli      t1, t0, 2                 # 4 bytes per element
    add       a1, a1, t1                # advance x
    add       a2, a2, t1                # advance y
    bnez      a0, saxpy                 # until no elements are left
    ret

Worked example. With VLEN = 128, SEW = 32 and LMUL = 1, VLMAX=128/32=4\mathrm{VLMAX} = 128/32 = 4. For n=10n = 10, a=2a = 2, x=(1,2,…,10)x = (1, 2, \dots, 10) and every yi=10y_i = 10:

Figure

Strip mining: saxpy on 10 elements with VLMAX = 4

Three passes of the vector loopTen x elements are processed in three passes of four lanes: 4, 4 and 2 active lanes. In the last pass two lanes are grey. Below the lanes are the stored y values from 12 to 30.xv2y1pass 1: AVL = 10, vl = 46 left112122141431616418182pass 2: AVL = 6, vl = 42 left520206222272424826263pass 3: AVL = 2, vl = 20 left92828103030––not writtenThree passes of the vector loopTen x elements are processed in three passes of four lanes: 4, 4 and 2 active lanes. In the last pass two lanes are grey. Below the lanes are the stored y values from 12 to 30.1pass 1: AVL = 10, vl = 46 leftxv2y112122141431616418182pass 2: AVL = 6, vl = 42 leftxv2y520206222272424826263pass 3: AVL = 2, vl = 20 leftxv2y92828103030––not written
The vector loop of saxpy y = a·x + y for n = 10, a = 2, x = 1, …, 10 and every y = 10, on a machine with VLEN = 128 bits, 32-bit elements and LMUL = 1, so that one register holds VLMAX = 4 elements. In each pass, vsetvli receives the number of elements left, AVL, and grants vl: 4 for AVL = 10, 4 for AVL = 6 (the specification would also allow 3) and 2 for AVL = 2. Green cells are the loaded x values, blue the lanes of register v2 after vfmacc, red the stored y = 12, …, 30. In the third pass two lanes stay unused, and no separate loop for the leftover elements is needed.
  1. Pass 1. AVL = 10 is at least 2⋅42 \cdot 4, so vl=4\mathit{vl} = 4. Elements 0–3 are computed: y=(12,14,16,18)y = (12, 14, 16, 18). Ten minus four leaves 6.
  2. Pass 2. AVL = 6 lies between 4 and 8, so the specification allows vl=3\mathit{vl} = 3 or 44; an implementation that always grants the maximum takes 4, and elements 4–7 become (20,22,24,26)(20, 22, 24, 26). Two are left.
  3. Pass 3. AVL = 2 is at most 4, so vl=2\mathit{vl} = 2: elements 8 and 9 become (28,30)(28, 30), and the other two lanes are not written. Nothing is left, and the loop ends.

The loop executes 10 instructions per pass: 30 for the ten elements, against 90 for the scalar loop. With VLEN = 512 the same binary would process sixteen elements per pass. An implementation that grants 3 in pass 2 finishes with passes of 4, 3 and 3 and the same result.

GPUs: thousands of threads in groups of 32#

A graphics processing unit pushes data-level parallelism furthest. It is built from many SIMD processors, which NVIDIA calls streaming multiprocessors (SMs), with a memory system designed for bandwidth rather than latency. An NVIDIA A100 has 108 SMs with 64 single-precision lanes each, 6,912 in all; at its boost clock of 1.41 GHz, with a fused multiply-add counted as two operations, that is 6,912⋅2⋅1.41×109=19.56{,}912 \cdot 2 \cdot 1.41 \times 10^9 = 19.5 TFLOP/s, its rated single-precision peak. Its tensor cores, units that multiply small matrices in one operation, reach 312 TFLOP/s in 16-bit arithmetic (NVIDIA, 2020, Table 4).

SIMT. A GPU is programmed in a scalar style. The programmer writes a function, a kernel, for one thread, and launches it on a grid of thousands of threads, grouped into blocks; each thread computes its own index. In CUDA, saxpy is (an excerpt, not run here; it needs an NVIDIA GPU):

__global__ void saxpy(int n, float a, const float *x, float *y) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;   // this thread's element
    if (i < n) y[i] = a * x[i] + y[i];
}
// launched as saxpy<<<(n + 255) / 256, 256>>>(n, a, x, y): blocks of 256 threads

The hardware runs 32 consecutive threads of a block together as a warp: one instruction is fetched and issued for all 32, and each lane applies it to its own thread’s registers. NVIDIA calls this single instruction, multiple threads (SIMT; Lindholm et al., 2008). It is SIMD with a per-lane mask that the hardware manages: when threads of one warp take different sides of a branch, the warp executes both sides one after the other, with the lanes of the other side switched off. This divergence costs time; an if/else that splits every warp in two halves the throughput of that part of the code.

Worked example. For n=106n = 10^6 and blocks of 256 threads, the launch creates ⌈106/256⌉=3,907\lceil 10^6/256 \rceil = 3{,}907 blocks, 3,907⋅256=1,000,1923{,}907 \cdot 256 = 1{,}000{,}192 threads and 3,907⋅8=31,2563{,}907 \cdot 8 = 31{,}256 warps. The test i < n switches off the last 192 threads; they all fall in the last block, in its last six warps, so only those warps have masked lanes and no warp diverges in a way that costs a second pass over useful work.

Hiding latency with threads. A load from GPU memory takes hundreds of cycles, and a GPU has no out-of-order execution to work around it. Instead, each A100 SM keeps up to 64 warps (2,048 threads) resident, with their registers in a 256 KB register file per SM, and every cycle its schedulers issue from warps that are ready while the others wait. This is the fine-grained multithreading of the previous note, on a large scale. It works only if there are many more threads than lanes; the register file sets the limit: 65,53665{,}536 32-bit registers shared by 2,048 threads is 32 registers per thread at full occupancy.

The memory hierarchy. Each A100 SM has its registers and 192 KB of fast on-chip memory, split between an L1 cache and up to 164 KB of shared memory, which the program manages explicitly to share data between the threads of a block. All SMs share a 40 MB L2 cache and 40 GB of high-bandwidth memory (HBM2) at 1,555 GB/s (NVIDIA, 2020, Table 4). When the 32 threads of a warp load 32 consecutive 4-byte words, the hardware coalesces the accesses into a few transactions for 128 contiguous bytes; when they load scattered words, each needs its own, and the effective bandwidth falls by up to 32 times (NVIDIA, CUDA C++ Programming Guide, on device memory accesses). The efficient-transformers note shows what this hierarchy means for attention: FlashAttention computes it in tiles that stay in shared memory and never writes the large score matrix to HBM.

The roofline model: arithmetic or memory?#

The measured saxpy stopped gaining from wider registers once its data came from main memory. The roofline model (Williams, Waterman and Patterson, 2009) predicts that limit from two numbers of the machine and one of the computation.

A computation does FF floating-point operations and moves DD bytes between the processor and memory. On a machine with peak arithmetic rate PP and memory bandwidth BB, the arithmetic alone takes at least F/PF/P seconds and the memory traffic at least D/BD/B. Even if the two overlap perfectly, the running time tt is at least the larger of them, so

t≥max⁡ ⁣(FP,DB)both must happenFt≤min⁡ ⁣(P,FD B)divide F by both sides=min⁡(P,  I⋅B)I=F/D.\begin{aligned} t &\ge \max\!\Big(\frac{F}{P}, \frac{D}{B}\Big) && \text{both must happen} \\ \frac{F}{t} &\le \min\!\Big(P, \frac{F}{D}\,B\Big) && \text{divide } F \text{ by both sides} \\ &= \min(P,\; I \cdot B) && I = F/D . \end{aligned}   attainable FLOP/s=min⁡(P,  I⋅B)  \boxed{\;\text{attainable FLOP/s} = \min(P,\; I \cdot B)\;}

On a log-log plot of attainable performance against II, the bound is a slanted line I⋅BI \cdot B (the memory roof) that meets a flat line PP (the compute roof) at the ridge point I∗=P/BI^* = P/B. A computation with I<I∗I < I^* is memory-bound: a faster arithmetic unit would not help it, and only moving fewer bytes would. One with I>I∗I > I^* is compute-bound.

Worked example. For the A100 with B=1.555B = 1.555 TB/s, the ridge point is 19.5/1.555=12.519.5/1.555 = 12.5 FLOP/byte for single-precision arithmetic and 312/1.555=200.6312/1.555 = 200.6 for the 16-bit tensor cores.

  • Vector addition, zi=xi+yiz_i = x_i + y_i: one operation per 12 bytes (two loads and a store of 4-byte floats), I=0.083I = 0.083. It attains at most 0.083⋅1.555=0.130.083 \cdot 1.555 = 0.13 TFLOP/s, 0.7 % of the single-precision peak.
  • Saxpy: two operations per 12 bytes, I=0.167I = 0.167, at most 0.26 TFLOP/s. A saxpy on 2242^{24} elements takes at least 129 µs to move its 201 MB, while its arithmetic alone would take 1.7 µs.
  • Matrix multiplication of two n×nn \times n matrices: 2n32n^3 operations. If each of the three matrices crosses the memory boundary once, it moves 3⋅4n23 \cdot 4 n^2 bytes in single precision, and I=2n3/(12n2)=n/6I = 2n^3/(12 n^2) = n/6. For n=64n = 64 that is 10.7, just below the ridge (at most 16.6 TFLOP/s); for n=4,096n = 4{,}096 it is 683, far above it: compute-bound at 19.5 TFLOP/s, or at 312 TFLOP/s on the tensor cores, whose 16-bit data doubles II to 1,365.
Figure

The roofline of an NVIDIA A100

Attainable performance of an A100 against arithmetic intensityA log-log plot. The slanted memory line rises from left to right and meets the flat line at 19.5 TFLOP/s at intensity 12.5 and the flat line at 312 TFLOP/s at 200.6. The points for vector addition and saxpy lie on the slanted line near 0.1 TFLOP/s; the 64 × 64 matrix product lies just below the first ridge, the 4,096 × 4,096 products on the flat lines.0.010.1110100100010⁴0.010.11101001000arithmetic intensity I, FLOP/byteTFLOP/sridge 12.5ridge 200.6FP32 peak: 19.5 TFLOP/sFP16 tensor peak: 312memory: 1.555 TB/svector addsaxpymatmul n = 64matmul n = 4096, fp32matmul n = 4096, fp16Attainable performance of an A100 against arithmetic intensityA log-log plot. The slanted memory line rises from left to right and meets the flat line at 19.5 TFLOP/s at intensity 12.5 and the flat line at 312 TFLOP/s at 200.6. The points for vector addition and saxpy lie on the slanted line near 0.1 TFLOP/s; the 64 × 64 matrix product lies just below the first ridge, the 4,096 × 4,096 products on the flat lines.0.010.1110100100010⁴0.010.11101001000I, FLOP/byteTFLOP/s12.5200.6FP32 19.5FP16 3121.555 TB/saddsaxpyn = 64n = 4096 fp32n = 4096 fp16
Attainable performance min(P, I·B) against arithmetic intensity I for an A100 (40 GB): the slanted roof is the memory bandwidth B = 1.555 TB/s, the flat roofs are the peaks of 19.5 TFLOP/s in FP32 and 312 TFLOP/s on the FP16 tensor cores. The ridge points at I = 12.5 and 200.6 FLOP/byte separate memory-bound from compute-bound work. Vector addition (I = 0.083) and saxpy (0.167) sit on the memory roof, far below the peak; an n × n matrix product in which each matrix crosses the memory boundary once has I = n/6 in FP32: 10.7 for n = 64, still just below the ridge, and 683 for n = 4,096, which reaches the peak. Both axes are logarithmic.

The matrix product reaches its high intensity only if the implementation actually reuses each loaded number about nn times, which needs tiles that stay in fast memory: in the shared memory of a GPU or the caches of a CPU, by the blocking of the next note. A naive implementation that reloads its operands for every multiply-add has an intensity below 1 and sits on the memory roof. This is why the dense layers of a neural network, matrix products as the neural-networks note writes them, run near the peak of a GPU, while element-wise operations such as activations, normalizations and the softmax of attention are memory-bound and take a share of the running time far above their share of the arithmetic.

What changed#

Scalar coreSIMD extensionVector (RVV)GPU
Elements per instruction1fixed by the ISA (4 floats at 128 bits)vl≤VLMAX\mathit{vl} \le \mathrm{VLMAX}, set at run time32 per warp instruction
Leftover elementsnonea scalar tail loophandled by vl\mathit{vl}masked threads
Who finds the parallelismthe out-of-order hardwarecompiler or programmercompiler or programmerprogrammer, one thread per element
Hides memory latency byout-of-order execution, cachesthe samelong vectors, pipeliningswitching among many warps
Peak in single precisiona few FLOP per cycle×4–16×lanes19.5 TFLOP/s (A100), 312 with tensor cores

Limitations#

  • Only regular loops benefit. Data-dependent branches, pointer chasing and loop-carried dependences leave lanes idle or prevent vectorization altogether.
  • Memory bandwidth is the usual limit. Low-intensity code such as vector addition and saxpy sits on the memory roof, and wider units do not help it.
  • Fixed-width SIMD ages with its ISA. Code compiled for one width does not use a wider one; vector-length-agnostic designs such as RVV avoid this.
  • GPUs pay for distance. Data must be copied to the GPU’s memory, and divergent or uncoalesced code loses most of the peak.
  • The roofline is a bound, not a prediction. It ignores latency, caches between the processor and memory, and the instruction overhead that kept the scalar saxpy below its memory roof.

What you should remember#

  • Data-level parallelism applies one instruction to many elements, saving the fetch, decode and scheduling of the scalar loop.
  • SIMD registers hold a fixed number of elements (four floats in 128 bits); vector architectures such as RVV let vsetvli grant vl≤VLMAX=LMUL⋅VLEN/SEW\mathit{vl} \le \mathrm{VLMAX} = \mathrm{LMUL} \cdot \mathrm{VLEN}/\mathrm{SEW} elements per pass, and strip mining loops until nothing is left.
  • A compiler vectorizes a loop without loop-carried dependences or aliasing. Measured on the M1: saxpy at 31 GFLOP/s from the cache against 6 without SIMD, but only 8.2 against 3.4 from memory.
  • GPUs run thousands of threads in warps of 32 (SIMT), hide memory latency by switching warps, and need coalesced accesses and little divergence.
  • Roofline: attainable FLOP/s =min⁡(P,I⋅B)= \min(P, I \cdot B), with the ridge at I∗=P/BI^* = P/B (12.5 FLOP/byte for the A100 in single precision). Vector operations are memory-bound; a large blocked matrix product is compute-bound.

Code#

The scalar loop of the baseline as a RARS program, on integers: y←2x+yy \leftarrow 2x + y for ten elements.

# y[i] = a * x[i] + y[i] on integers, one element per iteration (scalar code)
        .data
x:      .word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
y:      .word 10, 10, 10, 10, 10, 10, 10, 10, 10, 10
n:      .word 10
        .text
main:
        lw   a0, n              # a0 = n, elements left
        li   a1, 2              # a = 2
        la   a2, x
        la   a3, y
loop:   lw   t0, 0(a2)          # t0 = x[i]
        lw   t1, 0(a3)          # t1 = y[i]
        mul  t0, t0, a1         # t0 = a * x[i]
        add  t1, t1, t0         # t1 = a * x[i] + y[i]
        sw   t1, 0(a3)          # y[i] = t1
        addi a2, a2, 4
        addi a3, a3, 4
        addi a0, a0, -1
        bnez a0, loop
        la   s0, y              # print y
        lw   s1, n
print:  lw   a0, 0(s0)
        li   a7, 1
        ecall
        li   a0, ' '
        li   a7, 11
        ecall
        addi s0, s0, 4
        addi s1, s1, -1
        bnez s1, print
        li   a7, 10
        ecall
# prints: 12 14 16 18 20 22 24 26 28 30

Saxpy in C, timed for an array that fits in the first-level cache and one that does not. Compile it three ways: clang -std=c17 -Wall -Wextra -O0 saxpy.c, then with -O3 -fno-vectorize -fno-slp-vectorize, then with -O3; adding -Rpass=loop-vectorize to the last prints the vectorization report. The rates depend on the machine and vary between runs; the output shown is one run on an Apple M1 (macOS 26.5, Apple clang 21), one thread, with other programs running.

// saxpy, y = a*x + y, timed for a small array (fits in the L1 cache) and a large one (does not fit in any cache).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static void saxpy(long n, float a, const float *restrict x, float *restrict y) {
    for (long i = 0; i < n; i++)
        y[i] = a * x[i] + y[i];
}

static double now(void) {
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return t.tv_sec + t.tv_nsec / 1e9;
}

int main(void) {
    long sizes[] = {4096, 1L << 24};                // 2 x 16 KB, and 2 x 64 MB
    for (int s = 0; s < 2; s++) {
        long n = sizes[s], reps = (1L << 28) / n;   // 2^28 element updates in total
        float *x = malloc(n * sizeof *x), *y = malloc(n * sizeof *y);
        for (long i = 0; i < n; i++) { x[i] = 1.0f; y[i] = 0.0f; }
        double t0 = now();
        for (long r = 0; r < reps; r++) saxpy(n, 0.5f, x, y);
        double t = now() - t0;
        // 2 flops and 12 bytes (load x, load y, store y) per element
        printf("n = %8ld: y[0] = %.0f, %.2f GFLOP/s, %.1f GB/s\n",
               n, y[0], 2.0 * n * reps / t / 1e9, 12.0 * n * reps / t / 1e9);
        free(x); free(y);
    }
    return 0;
}
// -O0:
// n =     4096: y[0] = 32768, 1.45 GFLOP/s, 8.7 GB/s
// n = 16777216: y[0] = 8, 1.39 GFLOP/s, 8.4 GB/s
// -O3 -fno-vectorize -fno-slp-vectorize:
// n =     4096: y[0] = 32768, 6.02 GFLOP/s, 36.1 GB/s
// n = 16777216: y[0] = 8, 3.41 GFLOP/s, 20.5 GB/s
// -O3 (remark: vectorized loop (vectorization width: 4, interleaved count: 4)):
// n =     4096: y[0] = 32768, 31.12 GFLOP/s, 186.7 GB/s
// n = 16777216: y[0] = 8, 8.21 GFLOP/s, 49.2 GB/s

The roofline of the A100 and the kernels of the worked example:

# The roofline of an NVIDIA A100 (40 GB): attainable FLOP/s = min(peak, intensity * bandwidth)
B = 1.555e12                                  # HBM bandwidth, bytes/s
roofs = {'FP32': 19.5e12, 'FP16 tensor': 312e12}
for name, P in roofs.items():
    print(f'{name}: ridge point {P / B:.1f} FLOP/byte')
# FP32: ridge point 12.5 FLOP/byte
# FP16 tensor: ridge point 200.6 FLOP/byte

def matmul(n, size):                          # C = A B for n x n matrices: 2n^3 flops, each matrix moved once
    return 2 * n**3, 3 * n * n * size
kernels = {                                   # (flops, bytes) per call, 32-bit floats unless stated
    'vector add, z = x + y':  (1, 12),        # per element: load x, load y, store z
    'saxpy, y = a x + y':     (2, 12),
    'matmul n = 64, fp32':    matmul(64, 4),
    'matmul n = 4096, fp32':  matmul(4096, 4),
    'matmul n = 4096, fp16':  matmul(4096, 2),
}
for name, (flops, nbytes) in kernels.items():
    I = flops / nbytes
    P = roofs['FP16 tensor'] if 'fp16' in name else roofs['FP32']
    att = min(P, I * B)
    print(f'{name:24s} I = {I:8.3f} FLOP/byte  attainable {att / 1e12:7.3f} TFLOP/s  '
          f'{"memory" if I * B < P else "compute"}-bound')
# vector add, z = x + y    I =    0.083 FLOP/byte  attainable   0.130 TFLOP/s  memory-bound
# saxpy, y = a x + y       I =    0.167 FLOP/byte  attainable   0.259 TFLOP/s  memory-bound
# matmul n = 64, fp32      I =   10.667 FLOP/byte  attainable  16.587 TFLOP/s  memory-bound
# matmul n = 4096, fp32    I =  682.667 FLOP/byte  attainable  19.500 TFLOP/s  compute-bound
# matmul n = 4096, fp16    I = 1365.333 FLOP/byte  attainable 312.000 TFLOP/s  compute-bound

# saxpy at memory speed: the time is set by the bytes, not the flops
n = 1 << 24
print(f'saxpy n = 2^24: {12 * n / B * 1e6:.0f} us for {12 * n / 1e6:.0f} MB; its flops alone would take {2 * n / 19.5e12 * 1e6:.1f} us')
# saxpy n = 2^24: 129 us for 201 MB; its flops alone would take 1.7 us

Next#

Instruction-, thread- and data-level parallelism are now all on the table, and the roofline says how close a computation can come to the machine’s peak. Getting there is a matter of the program: measuring where the time goes, letting the compiler do its work, and arranging the data so that the caches deliver it. The next note does this for a matrix product, step by step, from loop order to blocking.

References#