---
title: Accelerator lab
heading: Roofline analysis, a systolic array's cycle model and GPU occupancy, in Python
eyebrow: S4 · Lesson 42 · Accelerator lab
xp: 60
---

::: hook
Choosing or designing an accelerator starts with three quick models: the roofline says whether a kernel is limited by arithmetic or by memory; a cycle model of a systolic array says how much of its peak a matrix multiply of a given shape can use; and an occupancy calculator says how many warps a GPU kernel keeps resident, which decides whether memory latency is hidden. This lab writes all three and applies them to the shapes that come up in practice.
:::

::: play
- The curve is the utilization of an n × n weight-stationary systolic array on a matrix multiply with M rows streamed per tile, $M/(M + n + 2(n - 1))$, counting n cycles to load each tile's weights and $2(n - 1)$ to fill and drain.
- Small batches waste most of a big array: with M = 64 a 256 × 256 array is busy under 10% of the time.
- The lab adds tiling over the other two dimensions, which can waste more.
:::

```sim plot
view: graph
x: M = 1..4096 log
y: u = 0..1
slider: n = 32..512 step 32 = 256
plot: M/(M + n + 2*(n - 1)) | label: utilization
```

::: predict
## A 256 × 256 systolic array multiplies a 64 × 256 matrix by a 256 × 256 weight matrix: one tile, 64 rows streamed. Loading the tile's weights takes 256 cycles and filling and draining 510. What fraction of its peak does it use?

- [ ] About 80%
- [ ] About 25%
- [x] About 8%
- [ ] 100%: the matrix fits exactly

::: reveal
The useful work is $64 \times 256 \times 256$ multiply-accumulates; the array could do $256^2$ per cycle, and the pass takes $256 + 64 + 510 = 830$ cycles: $64/830 = 7.7\%$. The weights fit perfectly, but 64 rows can't amortize loading them and pushing data through 256 stages.
:::
:::

::: nameit
## Roofline

For a kernel of W operations moving Q bytes on a machine with peak P and bandwidth B: intensity $I = W/Q$, attainable rate $\min(P, BI)$, and time $W/\min(P, BI)$; memory-bound if $BI < P$.

## Systolic tiling

An M × K by K × N multiply on an n × n weight-stationary array needs $\lceil K/n\rceil\lceil N/n\rceil$ weight tiles. Each takes n cycles to load, then M cycles to stream the rows plus $2(n - 1)$ to fill and drain:
$$\text{cycles} = \left\lceil\frac Kn\right\rceil\left\lceil\frac Nn\right\rceil\big(n + M + 2(n - 1)\big), \qquad \text{utilization} = \frac{MKN}{n^2\cdot\text{cycles}}$$

## GPU occupancy

A block of T threads is $\lceil T/32\rceil$ warps. An SM fits as many blocks as its registers, its shared memory, its block slots and its warp slots all allow:
$$\text{blocks} = \min\left(\left\lfloor\frac{R}{32r\,w_b}\right\rfloor, \left\lfloor\frac{S}{s}\right\rfloor, B_\text{max}, \left\lfloor\frac{W_\text{max}}{w_b}\right\rfloor\right)$$
for r registers per thread, s bytes of shared memory per block and $w_b$ warps per block; occupancy is resident warps over $W_\text{max}$.
:::

::: check
kind: python

## Write `roofline(P, B, ops, nbytes)`: with P in GFLOP/s and B in GB/s, return (attainable GFLOP/s, 'memory' or 'compute', run time in seconds).

```python starter
def roofline(P, B, ops, nbytes):
    return (P, 'compute', 0.0)
```

```python solution
def roofline(P, B, ops, nbytes):
    I = ops / nbytes
    att = min(P, B * I)
    bound = 'memory' if B * I < P else 'compute'
    return (att, bound, ops / (att * 1e9))
```

```python tests
a, b, t = roofline(2000, 200, 2e9, 12e9)
assert abs(a - 33.33) < 0.01 and b == 'memory' and abs(t - 0.06) < 1e-9, "A DAXPY-like kernel: 33 GFLOP/s, memory-bound, 60 ms."
a2, b2, t2 = roofline(2000, 200, 1e12, 1e10)
assert a2 == 2000 and b2 == 'compute' and abs(t2 - 0.5) < 1e-9, "Intensity 100: compute-bound at peak."
```

::: right
Right. The bound type tells which optimization can help: raise intensity for memory-bound kernels, use the arithmetic better for compute-bound ones.
:::
:::

::: check
kind: python

## Write `systolic(M, K, N, n)`: return (cycles, utilization) for an M × K by K × N multiply on an n × n weight-stationary array, by the tiling model.

```python starter
def systolic(M, K, N, n):
    return (0, 1.0)
```

```python solution
import math

def systolic(M, K, N, n):
    tiles = math.ceil(K / n) * math.ceil(N / n)
    cycles = tiles * (n + M + 2 * (n - 1))
    return (cycles, M * K * N / (n * n * cycles))
```

```python tests
c, u = systolic(64, 256, 256, 256)
assert c == 830 and abs(u - 0.0771) < 1e-4, "The predict: 830 cycles, 7.7%."
c2, u2 = systolic(1000, 256, 256, 256)
assert abs(u2 - 0.566) < 1e-3, "A batch of 1000: 57%."
c3, u3 = systolic(1000, 300, 300, 256)
assert c3 == 4 * 1766 and u3 < u2 / 2, "300 wide: four tiles, mostly empty: under half the 256-wide case."
```

::: right
Right. Shapes that just miss a multiple of the array size waste the most; compilers pad or reshape layers to fit.
:::
:::

::: check
kind: python

## Write `occupancy(regs, smem, threads, R=65536, S=102400, Wmax=64, Bmax=32)`: the fraction of an SM's warp slots a kernel fills, for `regs` registers per thread, `smem` bytes of shared memory per block (0 for none) and `threads` per block.

```python starter
def occupancy(regs, smem, threads, R=65536, S=102400, Wmax=64, Bmax=32):
    return 1.0
```

```python solution
import math

def occupancy(regs, smem, threads, R=65536, S=102400, Wmax=64, Bmax=32):
    wb = math.ceil(threads / 32)
    by_regs = R // (regs * 32 * wb)
    by_smem = S // smem if smem else Bmax
    blocks = min(by_regs, by_smem, Bmax, Wmax // wb)
    return blocks * wb / Wmax
```

```python tests
assert occupancy(32, 0, 256) == 1.0, "32 registers: every warp slot."
assert occupancy(64, 0, 256) == 0.5, "64 registers: registers run out at half."
assert occupancy(32, 48 * 1024, 256) == 0.25, "48 KB of shared memory per block: two blocks fit."
assert occupancy(128, 0, 128) == 0.25, "128 registers: a quarter."
```

::: right
Right. Whichever resource runs out first sets the occupancy; tuning a kernel means finding which one it is.
:::
:::

::: explain
## Why can a systolic array that matches a layer's weight matrix exactly still run at a small fraction of its peak?

::: model
A weight-stationary array must first load a tile of weights into its cells, then stream input rows through, and data takes about 2n cycles to enter, cross and leave an n × n array. Those load, fill and drain cycles are fixed costs per tile, while useful work grows with the number of rows streamed. If the batch is small, say 64 rows on a 256 × 256 array, the fixed costs are ten times the useful cycles, so the array is idle most of the time even though every cell holds a real weight. Large batches, or designs that overlap loading the next tile with streaming the current one, amortize those costs.
:::
:::
