Maps to: Stanford CS 217 Hardware Accelerators for Machine Learning (Winter 2026), Lecture 6 · Thu 01/22/2026 · Vector and Scalar Units. Project proposals are out. Lab 2 (out since Lecture 5) is the design of a vector processing unit: the block this lecture builds in software. Reading: the schedule lists no reading for this session. These notes draw on:
- Hennessy & Patterson, Computer Architecture: A Quantitative Approach, the chapter on vector architectures (lanes, chaining, strip-mining);
- T. Norrie et al., The design process for Google’s training chips: TPUv2 and TPUv3, IEEE Micro 2021 (the vector unit and VLIW bundles of a TPU core);
- J. Shah et al., FlashAttention-3, 2024 (exp throughput vs tensor-core throughput on H100);
- S. Oberman and M. Siu, A high-performance area-efficient multifunction interpolator, ARITH 2005 (table + quadratic special-function units);
- J.-M. Muller, Elementary Functions: Algorithms and Implementation (range reduction, minimax polynomials);
- N. Schraudolph, A fast, compact approximation of the exponential function, Neural Computation 1999;
- the OCP Microscaling (MX) specification and Lecture 4 (HW2’s prologue vs epilogue scaling).
Basis: The slides are not public. This lecture follows the session title, the schedule’s description of Lab 2 and HW2, and the sources above. The experiments use a cycle-level vector-unit simulator and a library of hardware function approximations written for these notes (
vector_unit.py,approx.py). The simulator’s results are checked against numpy, and its MX quantizer against Lecture 4’snumfmt. The “reference core” is a model with stated assumptions, not a product. The experiments do not reflect what was said in class. Code:code/lecture06/(4 scripts + 2 modules; each runs in 1–3 seconds) Reading time: 3–4 hours including running the code
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- List the non-GEMM operations of a transformer and a CNN — softmax, normalization, activations, residuals, rotary embeddings, quantization — and count their vector work per element.
- Apply Amdahl’s law to an accelerator: show why a faster matrix unit hands the critical path to the vector unit, and size the vector unit (lanes, SFU lanes) for a given matrix unit.
- Explain the requirement vector rate = (MACs per cycle / K) × operations per output, and why attention’s exp is the hardest case (FlashAttention-3’s problem on H100).
- Build hardware approximations of exp, 1/x, 1/√x, GELU and SiLU from range reduction, tables, minimax polynomials and Newton–Raphson; predict their accuracy (bits per table doubling = degree + 1) and cost.
- Decide how accurate a function must be: why softmax forgives a constant error, and why bf16 rounding of probabilities sets the floor.
- Describe a vector unit: lanes, vector registers, pipes, special-function units, reduction trees. Explain what chaining, dispatch queues and interleaving each buy on an in-order machine.
- Explain why accelerators keep a scalar core, why vector instructions should be long, and why wide vector units need VLIW bundles and lots of independent work (Little’s law).
- Decide where MX block scales are applied (prologue, vector-unit epilogue, inside the matrix unit) from the vector unit’s throughput — HW2’s question from the other side.
0.2 Prerequisites and scope
| Assumed | Introduced here | Developed later |
|---|---|---|
| Lecture 1: roofline, instruction overhead (70 pJ) | Amdahl’s law for accelerators, vector ops per MAC | memory traffic of unfused operators (L10) |
| Lecture 2: pipelining, latency vs II, software pipelining | vector units: lanes, chaining, decoupled dispatch, interleaving | the global buffer feeding the vector unit (L7) |
| Lecture 4: number formats, MX/NVFP4, HW2’s prologue/epilogue | function approximation: range reduction, minimax, Newton | FlashAttention’s online softmax (L10) |
| Lecture 5: systolic arrays, outputs per cycle | scalar core, VLIW, Little’s law | GPU SFUs and warps (L11) |
0.3 Map
§1 the non-GEMM work of ML; vector ops per MAC; the CNN contrast ← code 01 (Parts 1, 5)
§2 Amdahl's law for accelerators; attention's exp; overlap ← code 01 (Parts 2-4)
§3 computing nonlinear functions: range reduction, tables, polynomials, ← code 02
Newton-Raphson, GELU/SiLU; how accurate is accurate enough
§4 anatomy of a vector unit; a softmax row cycle by cycle; chaining, ← code 03
queues, interleaving; sizing; row length
§5 the scalar core, the instruction stream, VLIW, Little's law ← code 04 (Parts 1-2)
§6 where MX block scales are applied (HW2 revisited) ← code 04 (Parts 3-5)
§7 summary §8 pitfalls §9 exercises §10 further reading §11 next lecture
0.4 Notation
| Symbol | Meaning |
|---|---|
| ALU lanes: elements one vector ALU instruction processes per cycle | |
| SFU lanes: special-function (exp, 1/x, 1/√x, tanh) results per cycle | |
| vlen | elements in one vector register (the longest vector instruction) |
| chime | cycles one vector instruction occupies its pipe: ⌈vlen / L⌉ |
| element group | the elements one pipe processes in one cycle |
| reduction length of a GEMM: MACs per output element | |
| SFU | special-function unit |
| ulp | unit in the last place: the spacing of representable numbers |
| bits | correct bits of an approximation: −log2(max relative error) |
1. The work the matrix unit cannot do
1.1 Intuition: the kitchen and the pass
A restaurant kitchen has a huge grill line (the matrix unit) and one person at the pass who plates, seasons and garnishes every dish (the vector unit). When the grill line doubles, the restaurant does not serve twice as many dishes: plates pile up at the pass. Plating is only a few seconds per dish — a tiny fraction of the “work” — but it is done by far fewer hands. An accelerator is the same. The non-GEMM operations are a negligible share of the arithmetic, but they run on hardware that is tens of times narrower than the matrix unit.
1.2 The inventory
Every transformer layer contains, besides its GEMMs:
| Operation | Per element | Why it is hard for a matrix unit |
|---|---|---|
| RMSNorm / LayerNorm | square, sum (reduction), 1/√x, scale (and subtract the mean) | a reduction across a row, then a nonlinear function of the result |
| rotary embedding (RoPE) | x·cos + swap(x)·sin | element-wise with a permutation |
| softmax | max (reduction), subtract, exp, sum (reduction), 1/x, scale | two reductions, one transcendental per element |
| SiLU(gate)·up (SwiGLU) | sigmoid or tanh, two multiplies | a transcendental per element |
| residual add | one add | trivial but memory-heavy |
| quantize / dequantize (FP8, MX) | block max, exponent, scale, round | reductions over blocks, format conversion |
Script 01 counts the work of each from the vector programs of vector_unit.py (§4):
| Kernel | ALU ops / element | SFU ops / element |
|---|---|---|
| rmsnorm | 3.06 | 0 |
| softmax | 4.00 | 1.00 |
| swiglu | 4.00 | 1.00 |
| residual | 1.00 | 0 |
| mx_quantize | 5.16 | 0 |
| rope (assumed) | 3.00 | 0 |
1.3 Share of operations vs share of time
Take one Llama 3 8B decoder layer and a reference core: a TPU v4-core-sized matrix unit (4 × 128 × 128 = 65,536 bf16 MACs per cycle at 1.05 GHz, from the TPU v4 paper) next to a vector unit of our choosing: 1,024 fp32 lanes and 128 SFU lanes (1/8 as many, the ratio of a GPU SM). Element-wise data is assumed to stay on chip; Lecture 10 deals with its memory traffic. Script 01, Part 1:
| 2,048-token prefill | Size | Share of operations | Share of time |
|---|---|---|---|
| GEMMs | 4.64 × 10¹¹ MACs | 99.94% | 89.3% |
| softmax | 67.1 M elements | 0.04% | 6.6% |
| SiLU(gate)·up | 29.4 M elements | 0.02% | 2.9% |
| RMSNorm × 2 | 16.8 M elements | 0.01% | 0.6% |
| RoPE | 10.5 M elements | 0.00% | 0.4% |
| residual × 2 | 16.8 M elements | 0.00% | 0.2% |
The non-GEMM work is 0.1% of the operations but 11% of the time. The matrix unit has 64× more MACs than the vector unit has lanes, so a vector operation “costs” 64 MACs of time. In decode (batch 64, 2,048 tokens of context) the layer streams weights and the KV cache from memory: it is memory-bound, and the vector work is only 2.5% of the time.
1.4 Vector operations per MAC
A cleaner way to see the requirement: a GEMM with reduction length produces one output per MACs, so a matrix unit doing MACs per cycle emits outputs per cycle. Whatever follows the GEMM must process that many elements per cycle:
Script 01, Part 5 applies it to a ResNet-50 bottleneck block and to attention:
| Layer | K | Vector ops per MAC | Outputs per cycle | Vector / matrix time (serial) |
|---|---|---|---|---|
| 1×1 conv 256→64 + ReLU | 256 | 0.0039 | 256 | 25% |
| 3×3 conv 64→64 + ReLU | 576 | 0.0017 | 114 | 11% |
| 1×1 conv 64→256 + residual + ReLU | 64 | 0.0312 | 1,024 | 200% |
| Llama layer, prefill 2,048 (all) | 4,096 / 14,336 | 0.0013 | – | 12% |
| attention softmax | 128 (head_dim) | 0.0195 | 256 | 200% |
Two lessons:
- CNNs need little vector work per MAC. ReLU after a convolution with in the hundreds needs one simple operation per output. TPU v1 applied activations in a fixed-function pipeline at the array’s output, running in parallel with the array, so it added no time. (Short reductions are the exception: after a 1×1 convolution with , a serialized ReLU + residual add would cost twice the matrix time.)
- Attention needs a real vector unit. Each score costs only head_dim MACs (QKᵀ and PV), and needs 4 ALU operations plus one exp. This is why TPU v2 and later, and every AI GPU, have programmable vector units with fast special functions.
2. Amdahl’s law for accelerators
2.1 The law
If a fraction of the time is accelerated by a factor and the rest is not:
For an accelerator, is the GEMM share of the time and the growth of the matrix unit. The non-GEMM share does not shrink, so it grows as a fraction.
2.2 Growing the matrix unit
Script 01, Part 2 grows the matrix unit of the reference core and keeps the vector unit (2,048-token prefill of one layer):
| MACs / cycle | Layer time | Speedup | Vector share |
|---|---|---|---|
| 4,096 | 109 ms | 1.00× | 0.7% |
| 16,384 | 27.8 ms | 3.91× | 2.9% |
| 65,536 (reference) | 7.55 ms | 14.4× | 10.7% |
| 262,144 | 2.50 ms | 43.5× | 32.5% |
| 1,048,576 | 1.55 ms | 70.0× | 52.2% |
From the reference core, a 16× larger matrix unit makes the layer only 4.87× faster: half of the remaining time is vector work. At the largest size the matrix part also hits the memory floor (streaming the layer’s weights at 600 GB/s takes 0.73 ms).
How many lanes keep the vector share at or below 10%? With SFU lanes = lanes / 8: 2,048 lanes for the reference matrix unit, 8,192 for one 4× larger (Figure 01_amdahl.png, right). The vector unit must grow with the matrix unit.
2.3 Attention’s exp
Attention performs FLOPs per score ( for QKᵀ, for PV) and one exp. Compare with what the hardware delivers per exp it can compute (script 01, Part 3):
| Machine | Matrix FLOP/s | exp/s | FLOP per exp | exp/matmul time: = 64 | 128 | 256 |
|---|---|---|---|---|---|---|
| H100 SXM | 989.4 T | 3.86 T | 256 | 1.00 | 0.50 | 0.25 |
| reference core | 137.6 T | 0.13 T | 1,024 | 4.00 | 2.00 | 1.00 |
The H100 exp rate is computed as 132 SMs × 16 special-function results per SM per clock × 1.83 GHz. The FlashAttention-3 paper quotes the same contrast: 989 TFLOPS of matmul vs 3.9 TFLOPS of special functions. At the exponentials take half as long as the matrix multiplications; at just as long. FlashAttention-3 therefore overlaps the softmax of one tile with the GEMMs of another. Faster tensor cores (FP8, Blackwell) make it worse, and FlashAttention-4 is reported to compute part of its exponentials with a polynomial on the FMA units.
Our model can quantify that trick. Softmax needs 4 ALU operations and 1 exp per score. A range-reduced cubic exp (§3.2) costs about 6 ALU operations. Moving a fraction of the exps to the ALU lanes balances the two pipes when . On the reference core that gives and 1.40× faster softmax (5.58 vs 7.81 cycles per 1,000 scores).
2.4 Overlap
If the vector unit works on one tile while the matrix unit works on another, the layer takes max(matrix, vector) instead of the sum (script 01, Part 4):
| Workload | MACs/cycle | Matrix part | Vector part | Serialized | Overlapped | Gain |
|---|---|---|---|---|---|---|
| prefill 2,048 | 65,536 | 6.74 ms | 811 µs | 7.55 ms | 6.74 ms | 1.12× |
| prefill 2,048 | 262,144 | 1.69 ms | 811 µs | 2.50 ms | 1.69 ms | 1.48× |
| decode b64 | 65,536 | 1.62 ms | 40.9 µs | 1.66 ms | 1.62 ms | 1.03× |
Overlap hides the smaller part, never the larger, so it gains at most 2× (when the parts are equal). It also has costs: independent work (the next tile must not depend on this tile’s softmax), buffers for both tiles, and synchronization between the units — the scalar core’s job (§5).
3. Computing nonlinear functions in hardware
3.1 The toolkit
A special-function unit has three cheap ingredients and one trick:
- A table (ROM) indexed by the top bits of the input: one read, no arithmetic. Accuracy grows by about one bit per doubling of the table.
- A short polynomial evaluated by Horner’s rule, : multiply-adds for degree .
- Newton–Raphson iterations, which double the number of correct bits per step (for 1/x and 1/√x).
- Range reduction (the trick): map any input onto a short interval where the table and polynomial work, using cheap exponent manipulations.
Combinations are the rule: a small table chooses a segment, and a low-degree polynomial is evaluated in the offset inside the segment. Oberman and Siu’s multifunction interpolator, the design behind GPU special-function units, uses a table plus a quadratic.
3.2 exp by range reduction
Multiplying by is an addition to the exponent field of the result — free in hardware. Only on needs approximating, and it lies in : a smooth function on a short interval. Script 02, Part 1 (inputs in , the softmax range):
| Degree | Taylor at 0 | Chebyshev interpolation | Minimax (Remez) | Minimax + Cody–Waite | Area (µm², 45 nm) |
|---|---|---|---|---|---|
| 1 | 2.7 bits | 4.7 | 5.1 | 5.1 | 23,768 |
| 2 | 4.9 | 8.8 | 9.2 | 9.2 | 35,652 |
| 3 | 7.5 | 13.3 | 13.7 | 13.7 | 47,536 |
| 4 | 10.4 | 17.6 | 17.8 | 18.5 | 59,420 |
| 5 | 13.5 | 19.0 | 19.0 | 22.4 | 71,304 |
| 6 | 16.7 | 19.1 | 19.1 | 23.0 | 83,188 |
Three lessons:
- How the polynomial is fitted matters as much as its degree. A Taylor series is exact at one point and bad at the other end of the interval. A minimax polynomial minimizes the worst error. By Chebyshev’s equioscillation theorem, its error reaches its maximum at points with alternating signs, and the Remez exchange algorithm (
approx.remez) finds it by moving those points until the error levels out. Interpolating at Chebyshev nodes gets within a small factor of it. - The reduction can be the accuracy limit. Without care, the error stops at about 19 bits whatever the degree. The product is rounded to float32, and half an ulp of is , which becomes a relative error of the result. Cody–Waite reduction computes as , where has few enough bits that is exact. It costs two more FMAs and reaches 22.4 bits at degree 5.
- The cheapest exp is a bit trick. Schraudolph (1999) noticed that computing the integer and reinterpreting its bits as a float32 gives : range reduction plus the linear “polynomial” , in one FMA. Its error is 6.1%, or 3.6% with a minimax shift (4.8 bits).
3.3 Tables vs polynomials
A piecewise polynomial of degree on segments of width has an error proportional to . Halving the segment width buys bits. Script 02, Part 2 measures it for (bits gained per doubling of the table, from 1 to 4 segments):
| Degree 0 (pure table) | Degree 1 | Degree 2 | Degree 3 |
|---|---|---|---|
| 0.97 | 2.13 | 3.14 | 3.94 |
A pure table needs entries for bits — 16 bits would take 65,536 entries — while a quadratic reaches 20.8 bits with 16 segments. The script also searches for the smallest-area exp unit meeting each accuracy target:
| Target | Max rel. error | Cheapest design | Table bits | Area µm² | Latency |
|---|---|---|---|---|---|
| bf16 | 2⁻⁸ | 128-entry table of | 4,096 | 14,751 | 8 |
| fp16 | 2⁻¹¹ | 8 linear segments | 512 | 24,126 | 12 |
| fp32-class | 2⁻²² | 32 quadratic segments + Cody–Waite | 3,072 | 61,570 | 24 |
For bf16 a table is cheapest; for higher precision, a small table plus a polynomial. Area grows slowly with accuracy, latency faster: the operations form one dependent chain.
3.4 Reciprocal and reciprocal square root: Newton–Raphson
To compute : write with , look up a seed in a table, and refine:
This is Newton’s method on . If , one step gives : the relative error is squared, so the correct bits double. For the step is (error ), with the exponent made even so that stays an exponent operation. Script 02, Part 3:
| Function | Seed | Seed only | +1 Newton | +2 Newton | Area (1 step) | Latency (1 step) |
|---|---|---|---|---|---|---|
| 1/x | 16 entries | 5.0 bits | 10.1 | 20.0 | 19,942 µm² | 11 |
| 1/x | 256 entries | 9.0 | 18.0 | 22.7 | 25,318 | 11 |
| 1/x | 16 entries, linear | 11.1 | 21.7 | 22.9 | 32,185 | 15 |
| 1/√x | 64 entries | 6.4 | 12.3 | 22.6 | 28,718 | 14 |
| 1/√x | magic constant, no table | 4.9 | 9.2 | 17.7 | 31,468 | 17 |
The “magic constant” is the fast inverse square root of Quake III: subtracting the bit pattern of , shifted right by one, from 0x5f3759df halves and negates the exponent (and roughly corrects the mantissa). That gives a 3.4% seed with no table at all. Newton steps trade table area for latency: each step adds 2–3 multiplies in series.
3.5 GELU and SiLU
Script 02, Part 4 (absolute error on ):
| Approximation | Max abs. error | Area µm² |
|---|---|---|
| GELU, tanh formula (GPT-2’s) | 4.7 × 10⁻⁴ | 54,568 (plus the tanh) |
| GELU ≈ x·σ(1.702x) | 2.0 × 10⁻² | 15,400 |
| GELU, 64 linear segments on [−8, 8] | 3.1 × 10⁻³ | 14,751 |
| GELU, 64 quadratic segments | 6.3 × 10⁻⁵ | 28,069 |
| SiLU = x/(1 + e⁻ˣ), cubic exp + 2-step reciprocal | 1.7 × 10⁻⁵ | 98,946 |
| SiLU, 64 quadratic segments on [−10, 10] | 4.9 × 10⁻⁵ | 28,069 |
bf16 rounds a value near 1 with an error of up to 3.9 × 10⁻³. The sigmoid form of GELU is visibly worse than that; the tanh form and piecewise quadratics are not. A dedicated piecewise SiLU is 3.5× smaller than one composed from a general exp and reciprocal — but the composed one reuses the SFU that softmax needs anyway. Fixed function vs reuse is a recurring trade-off.
3.6 How accurate is accurate enough?
Softmax divides by a sum of the same exponentials. If every exp is off by the same relative factor, , the factor cancels:
Only the variation of the error across inputs matters. Script 02, Part 5 runs attention with 64 queries, 1,024 keys and , and measures the output error relative to float64:
| exp | exp rel. error | Diffuse, fp32 P | Diffuse, bf16 P | Peaked, fp32 P | Peaked, bf16 P |
|---|---|---|---|---|---|
| exact (float32) | – | 8.7e-8 | 1.7e-3 | 1.2e-7 | 1.5e-3 |
| exact × 1.03 | 3.0e-2 | 8.9e-8 | 1.7e-3 | 1.2e-7 | 1.5e-3 |
| bit trick (minimax shift) | 3.6e-2 | 2.0e-2 | 2.1e-2 | 1.2e-2 | 1.2e-2 |
| degree 1 | 3.0e-2 | 2.2e-2 | 2.2e-2 | 1.4e-2 | 1.4e-2 |
| degree 2 | 1.7e-3 | 1.3e-3 | 2.1e-3 | 7.1e-4 | 1.6e-3 |
| degree 3 | 7.6e-5 | 5.6e-5 | 1.7e-3 | 3.3e-5 | 1.5e-3 |
A 3% constant error changes nothing. Fused attention kernels round P to bf16 before multiplying by V, and that rounding alone sets a floor of about 1.7 × 10⁻³. A degree-3 exp is indistinguishable from an exact one; degree 2 adds a little; degree 1 is ten times worse. That is consistent with reports that FlashAttention-4 uses a cubic polynomial.
The same experiment shows why softmax subtracts the row maximum first. Mathematically it changes nothing. Numerically, fp16’s exp overflows above ln(65504) = 11.1: at score scale 4, 83% of rows become inf/NaN without the subtraction. The subtraction costs a reduction (§4.2), and it is the reason softmax needs two passes over a row — or an online algorithm (Lecture 10).
4. Anatomy of a vector unit
4.1 The blocks
instruction stream (from the scalar core)
│
┌─────────────▼──────────────┐
│ dispatch: in order, W/cycle │
└──┬──────┬──────┬──────┬────┘
queue ▼ ▼ ▼ ▼ ▼ (8 entries per pipe)
┌──────┐ ┌──────┐ ┌────────────┐ ┌──────┐ ┌────────┐
│ load │ │store │ │ ALU: L lanes│ │ SFU: │ │ scalar │
│ pipe │ │ pipe │ │ add mul fma │ │ S │ │ unit │
└──┬───┘ └──▲───┘ │ max cvt ... │ │ lanes│ └───┬────┘
│ │ └──────┬──────┘ └──┬───┘ │
▼ │ ▼ ▼ ▼
┌──────────────────────────────────────────┐ scalar regs
│ vector register file: n_vregs x vlen │◄─(broadcast)
└──────────────────────────────────────────┘
│ reduction: L lanes → adder tree (log2 L levels) → scalar
local vector memory (bf16 activations, MX codes, ...)
vector_unit.VUConfig has 16 ALU lanes, 4 SFU lanes, 32 registers of 256 elements, ALU latency 4, SFU latency 19 (the cubic exp of §3.2), 64 bytes per cycle of loads and of stores, chaining, and dispatch queues of 8. One instruction processes vlen elements in ⌈n/width⌉ element groups, one group per cycle. A reduction runs its groups through the ALU lanes and then an adder tree across the lanes: log2 L levels of the ALU latency.
4.2 A softmax row, cycle by cycle
Script 03, Part 1 traces one 64-element row (vlen 64):
| Op | Pipe | Dispatched | First group | Last group | Ready |
|---|---|---|---|---|---|
| vld x | ld | 0 | 0 | 1 | 3 |
| vredmax → s_max | alu | 1 | 2 | 5 | 33 |
| vsub x − s_max | alu | 2 | 33 | 36 | 40 |
| vexp | sfu | 3 | 37 | 52 | 71 |
| vredsum → s_sum | alu | 4 | 59 | 71 | 99 |
| srecip | scalar | 5 | 99 | 99 | 118 |
| vmul e · s_inv | alu | 6 | 118 | 121 | 125 |
| vst | st | 7 | 123 | 125 | 127 |
127 cycles for 16 ALU + 16 SFU groups of work. The row is a dependent chain: the max reduction needs 28 cycles after its last group (a 4-level tree across 16 lanes plus 2 levels to combine the pipelined partial sums, each 4 cycles), the subtraction waits for it, and so on. Chaining shows in one place: the sum starts at cycle 59, while the exp is still producing (4 results per cycle). Correctness: every kernel matches numpy to within 1 × 10⁻⁷ relative to its largest output.
4.3 Chaining, queues and interleaving
Three mechanisms remove three kinds of stalls:
- Chaining (Cray-1, 1976): a dependent instruction starts as soon as the first elements it needs are ready, instead of waiting for the whole vector.
- Decoupled dispatch queues: instructions are dispatched in order into small queues in front of each pipe, and each pipe starts its instructions when ready. A load can then run ahead of arithmetic.
- Interleaving rows (software pipelining, Lecture 2): the compiler processes several rows together, each in its own registers, so that one row’s latencies are filled with other rows’ work.
Script 03, Part 2 (16 rows × 256 elements, 16 SFU lanes; cycles / throughput bound):
| Machine / program | gelu | softmax | rmsnorm | residual |
|---|---|---|---|---|
| strict in-order, no chaining | 1.61 | 3.00 | 2.23 | 2.64 |
| strict in-order, chaining | 1.20 | 2.32 | 1.92 | 1.76 |
| strict in-order, chaining, 4 rows interleaved | 1.13 | 1.17 | 1.21 | 1.77 |
| dispatch queues, chaining | 1.20 | 2.32 | 1.92 | 1.76 |
| dispatch queues, chaining, 4 rows interleaved | 1.01 | 1.01 | 1.01 | 1.06 |
The mechanisms only work together. Queues alone change nothing, because one row at a time every instruction depends on the previous one. Interleaving on a strict in-order machine helps but cannot let a load overtake a stalled instruction. Together they reach the throughput bound. In hardware terms: chaining needs per-element-group readiness tracking; queues need buffers in front of each pipe; interleaving needs registers (4 rows of softmax in flight use 4× the registers) and a compiler that schedules it.
4.4 Sizing ALU and SFU lanes
Script 03, Part 3 runs 32 rows × 1,024 elements with 2 rows interleaved, in cycles per 1,000 elements:
| ALU lanes | SFU lanes | softmax | swiglu | gelu | rmsnorm |
|---|---|---|---|---|---|
| 16 | 16 | 250 | 252 | 375 | 204 |
| 16 | 4 | 395 | 285 | 454 | 204 |
| 16 | 1 | 1,145 (SFU-bound) | 1,035 | 1,204 | 204 |
| 64 | 16 | 135 | 78 | 120 | 72 |
| 64 | 4 | 323 (SFU-bound) | 266 | 307 | 72 |
Exp-heavy kernels need SFU lanes in proportion to their ALU work: about one SFU lane per four ALU lanes for softmax. Norms do not care. When the ALU and SFU are equally loaded (16 and 4 lanes for softmax), the dependences between them keep the unit well above its bound. A unit sized for one kernel mix is unbalanced for another.
4.5 Row length
Each row pays its reductions’ tree latency and the scalar reciprocal or rsqrt once, whatever its length. Script 03, Part 4 (16 ALU lanes, 8 SFU lanes; cycles / bound):
| Kernel | Rows interleaved | n = 32 | 64 | 128 | 256 | 512 | 1,024 | 2,048 |
|---|---|---|---|---|---|---|---|---|
| softmax | 1 | 12.50 | 7.25 | 4.13 | 2.56 | 1.91 | 1.44 | 1.23 |
| softmax | 4 | 3.38 | 2.13 | 1.38 | 1.09 | 1.08 | regs | regs |
| rmsnorm | 1 | 7.33 | 4.63 | 2.82 | 1.91 | 1.49 | 1.28 | 1.18 |
| rmsnorm | 4 | 2.48 | 1.52 | 1.05 | 1.01 | 1.01 | 1.06 | regs |
Short rows are latency-bound; interleaving helps until the registers run out (“regs”). Short rows are common in practice: per-head normalizations, the softmax of a short prompt, the 32-element blocks of MX quantization.
4.6 The SFU inside the unit
Script 03, Part 5 plugs approx.py’s exponentials into the unit (16 rows × 512, 8 SFU lanes; SFU latency = the approximation’s latency):
| SFU exp | Latency | Cycles, 1 row at a time | Cycles, 4 interleaved | Max error / max p |
|---|---|---|---|---|
| degree 1 | 11 | 3,659 | 2,187 | 1.1e-2 |
| degree 3 | 19 | 3,915 | 2,219 | 3.0e-5 |
| degree 5 + Cody–Waite | 35 | 4,427 | 2,283 | 5.6e-8 |
A longer polynomial costs 21% one row at a time but only 4% with 4 rows interleaved. Latency is hidden by independent work; throughput is not. An SFU designer can spend pipeline stages on accuracy, as long as the compiler provides parallel rows.
5. The scalar core and the instruction stream
5.1 Why keep a scalar core?
A matrix unit and a vector unit compute; something must control them:
- loops and addresses: which tile comes next, where it lives in the buffer, when the loop ends;
- synchronization: wait until a DMA transfer has landed, signal the matrix unit that a tile of weights is ready, wait for its results;
- data-dependent decisions: sequence lengths, early exits, sparse indices;
- scalar arithmetic: 1/sum in softmax, 1/√(mean) in a norm, scale factors.
None of this needs throughput, but all of it must not steal issue slots from the vector unit. Accelerators therefore pair the vector unit with a small scalar core that issues bundles of scalar, vector, matrix and memory operations.
5.2 Amortizing instructions: long vectors and hardware loops
Lecture 1 showed that a simple core spends ~70 pJ to fetch, decode and control an instruction whose arithmetic costs ~1 pJ. Vector instructions amortize that cost over vlen elements. Script 04, Part 1 runs gelu (6 ALU ops + 1 tanh per element) on 16 lanes, 8 rows interleaved instruction by instruction:
| vlen | Loop control | Issue width | Instructions / element | Cycles / 1,000 el | Binding | Instr. energy pJ/el |
|---|---|---|---|---|---|---|
| 16 | software loop | 1 | 0.688 | 712 | issue | 48.1 |
| 16 | hardware loop + AGU | 1 | 0.562 | 587 | issue | 39.4 |
| 16 | hardware loop + AGU | 2 | 0.562 | 493 | latency | 39.4 |
| 64 | software loop | 1 | 0.172 | 379 | ALU | 12.0 |
| 256 | hardware loop + AGU | 1 | 0.035 | 377 | ALU | 2.5 |
The arithmetic itself costs 6.3 pJ per element. With 16-element vectors (one cycle per instruction) the instruction stream binds and costs 8× the arithmetic’s energy. Hardware loops (a loop counter in hardware, no branch instruction) and address-generation units (AGUs: strided addresses computed in hardware) remove the scalar bookkeeping. Long vectors make the rest negligible: each 256-element instruction occupies its pipe for 16 cycles.
5.3 Wide vector units need VLIW — and parallelism
A TPU-style vector unit is the opposite extreme: it applies one instruction to a whole 2-D register (8 sublanes × 128 lanes = 1,024 elements) in one cycle. TPU v2/v3 issue 322-bit VLIW bundles with 2 scalar slots, 4 vector slots (2 for loads/stores), 2 matrix slots (push, pop) and 1 miscellaneous slot (Norrie et al.). Script 04, Part 2 models a 1,024-lane unit with 1,024-element registers (64 rows, cycles; pipe bound 384 for gelu, 256 for softmax):
| Kernel | Rows interleaved | Issue 1 | Issue 2 | Issue 4 |
|---|---|---|---|---|
| gelu | 4 | 893 | 889 | 887 |
| gelu | 16 | 813 | 685 | 650 |
| softmax | 4 | 2,349 | 2,345 | 2,343 |
| softmax | 16 | 877 | 809 | 801 |
Single issue cannot feed such a unit: gelu issues 10 instructions per row for 6 cycles of ALU work. Wider bundles help — but every configuration stays latency-bound (gelu at 1.7×, softmax at 3.1× of the pipe bound with 16 rows in flight). A reduction across 1,024 lanes is a 10-level tree, so each softmax row is a chain of well over 100 cycles that does only a few cycles of work. Little’s law: to keep a unit busy, the work in flight must equal throughput × latency. Here that means dozens of rows of 1,024 elements — hundreds of KiB of registers. Wide-and-short vector units need VLIW issue, big register files and a compiler that finds parallel rows. (Our simple compiler also does not overlap successive groups of rows; a modulo scheduler, Lecture 2, would get closer.)
6. Where block scales are applied (HW2 revisited)
6.1 MX quantization on the vector unit
Every GEMM with MX inputs needs its activations quantized first. For each block of 32: take the maximum |x| (a segmented reduction), extract its exponent, subtract the element format’s emax, clamp to the E8M0 range, broadcast it back, scale by (an exponent subtraction) and round to the element format. Script 04, Part 3 runs this on the vector unit and compares with Lecture 4’s numfmt.mx_quantize: bit-exact for MXFP8, MXFP6 and MXFP4. It costs 5.16 ALU operations per element, and dequantization 3.00. The per-block steps run on the short vector of block maxima, one element per 32, before it is expanded; done after the expansion, they would cost 4 more operations per element.
6.2 Three places to apply the scales
In a block-scaled dot product, for every block. The scales can be applied:
- A. In a prologue on the vector unit: dequantize the MXFP4 weights to bf16, then run a bf16 GEMM. The cost is per weight element, , amortized over the M rows.
- B. In an epilogue on the vector unit: the matrix unit emits one partial sum per block, of them, and the vector unit scales and adds them.
- C. Inside the matrix unit: the array sums each block in integer arithmetic and applies once per block (Lecture 4). The vector unit only quantizes the activations, elements.
Script 04, Part 4 (the 4,096 × 14,336 MLP up-projection on the reference core; vector/matrix time = vector ops per MAC × 64):
| GEMM | A. prologue on VU | B. epilogue on VU | C. in the matrix unit |
|---|---|---|---|
| prefill, M = 2,048 | 0.09× | 2.00× | 0.02× |
| decode, M = 64 | 3.00× | 2.00× | 0.02× |
| decode, M = 1 | 192× | 2.00× | 0.02× |
B is never viable: 1/32 operation per MAC is 2× the matrix time at any batch, and it multiplies the data leaving the array by K/32 = 128. A is fine in prefill and hopeless in decode. C costs almost nothing on the vector unit. Lecture 4 showed it is also 10× cheaper per MAC (0.156 vs 1.63 pJ at 45 nm). Block-scaled formats need block scaling in the matrix unit: that is what MX-capable tensor cores do.
6.3 Decode: dequantizing at memory speed
In decode, MXFP4 weights arrive from memory at bandwidth / 4.25 bits per weight, and a vector unit doing prologue dequantization must keep up (script 04, Part 5):
| Machine | Memory | Weights per cycle | Vector ops needed / cycle | Lanes | Needed / available |
|---|---|---|---|---|---|
| reference core | 600 GB/s | 1,076 | 3,227 | 1,024 | 3.15 |
| H100 SXM (fp32 lanes) | 3,350 GB/s | 3,446 | 10,338 | 16,896 | 0.61 |
The reference core would be vector-bound in decode: the narrow format saves memory time only for the vector unit to lose it again. Even an H100 would spend most of its CUDA-core throughput on conversion in this simple count. Real weight-only-quantization kernels use packed conversions that handle several values per instruction, precisely because this cost is so visible. Narrow formats pay off only when the matrix unit consumes them natively.
7. Summary
- The non-GEMM operations of a transformer — softmax, norms, activations, RoPE, residuals, quantization — are ~0.1% of the operations but ~11% of the time on a core whose matrix unit has 64× more MACs than its vector unit has lanes.
- Vector rate needed = (MACs per cycle / K) × operations per output. CNN activations after long reductions need little (a pipelined fixed-function unit sufficed for TPU v1); attention’s softmax needs 4 ALU ops and an exp per MACs.
- Amdahl: from the reference core, a 16× matrix unit gives 4.87×. Keeping vector work ≤ 10% takes 2,048 lanes at 65,536 MACs/cycle and 8,192 at 262,144. On H100, exponentials take half the matmul time of attention at = 128 (FlashAttention-3 overlaps them; moving 29% of them to FMA lanes speeds softmax up 1.4× in our model).
- Special functions = range reduction + small table + short polynomial (+ Newton for 1/x, 1/√x). Each table doubling buys degree + 1 bits; minimax fits beat Taylor by several bits; the float32 reduction limits exp to ~19 bits unless Cody–Waite is used.
- Accuracy: softmax cancels constant errors; with P rounded to bf16, a cubic exp is as good as an exact one. Max subtraction is mandatory in fp16.
- A vector unit reaches its throughput only with chaining, decoupled dispatch queues and interleaved rows together (gelu 1.61× → 1.01× of its bound). Short rows are latency-bound; SFU latency is hidden by interleaving, SFU throughput is not.
- The scalar core runs loops, addresses and synchronization. Long vectors, hardware loops and AGUs cut instructions per element from 0.69 to 0.035. A 1,024-lane, one-cycle-per-instruction unit needs VLIW issue and — by Little’s law — many rows in flight.
- MX scaling belongs in the matrix unit: per-block rescaling on the vector unit costs 2× the matrix time; prologue dequantization is fine in prefill but 3× at M = 64, and in decode a vector unit cannot dequantize MXFP4 weights at memory speed.
8. Common pitfalls
- “Non-GEMM operations are 0.1% of the FLOPs, so they don’t matter.” Their share of time is set by the width ratio of the units (§1.3, §2.2).
- “Make the matrix unit bigger.” Without a matching vector unit, Amdahl caps the gain (4.87× for 16×, §2.2).
- “exp must be accurate to the last bit.” Softmax cancels constant errors, and bf16 rounding of P hides anything below ~2⁻⁹ (§3.6).
- “A Taylor series is a good polynomial.” It is exact at one point; a minimax polynomial of the same degree has several more bits (§3.2).
- “More polynomial terms fix accuracy.” Not if the range reduction is the error source (§3.2).
- “Chaining is enough.” On an in-order machine, chaining, queues and interleaving each fix a different stall (§4.3).
- “A wider vector unit is a faster vector unit.” Wider means fewer instructions per element but longer reduction trees and more work needed in flight (§5.3).
- “Block scales can be applied in software afterwards.” Per-block partial sums cost 1/32 operation per MAC on the vector unit (§6.2).
9. Exercises
Exercise 1 (Amdahl with a memory floor). From script 01, the reference core’s prefill layer takes 6.74 ms of matrix time and 0.811 ms of vector time, and streaming the layer’s weights takes 0.73 ms. Predict the speedup of a 16× larger matrix unit, and the limit as the matrix unit grows without bound.
Answer
Matrix time at 16× = max(6.74/16, 0.73) = max(0.42, 0.73) = 0.73 ms: the weight streaming now binds. Layer time = 0.73 + 0.811 = 1.54 ms; speedup 7.55/1.54 = 4.9× (script: 4.87×, from the unrounded numbers). As the matrix unit grows further, nothing changes: the limit is 7.55 / (0.73 + 0.811) ≈ 4.9×. Without the memory floor it would be 7.55/0.811 = 9.3× — Amdahl’s 1/(1 − f) with f = 89.3%.
Exercise 2 (vector rate). A core with 65,536 MACs per cycle runs a GEMM with K = 4,096 followed by RMSNorm-like work (3 ALU ops per output). How many ALU lanes keep up? Repeat for attention with = 128 (softmax: 4 ALU + 1 SFU per score).
Answer
GEMM: 65,536 / 4,096 = 16 outputs per cycle × 3 = 48 lanes. Attention: each score costs 2 × 128 = 256 MACs (QKᵀ and PV), so 65,536 / 256 = 256 scores per cycle → 1,024 ALU lanes and 256 SFU lanes. The reference core’s 1,024 lanes suffice for the ALU work, but its 128 SFU lanes are half of what attention needs: the 2.00 in §2.3.
Exercise 3 (FP8 attention). On H100, FP8 tensor cores double the matmul FLOPs while the SFU rate stays the same. What is the exp/matmul time ratio for = 64 and 128? What does this mean for the attention kernel?
Answer
FLOP per exp doubles to ~512. Ratio = 512 / (4 d_h): 2.0 at = 64 and 1.0 at 128. The kernel becomes exp-bound: even perfect overlap cannot beat the SFU time. Options: compute some exps with polynomials on the FMA units (§2.3), reduce the number of exps, or rescale less often in online softmax.
Exercise 4 (range reduction by hand). Compute exp(−3.2) the way exp_rr does: n, f, and the result.
Answer
; ; ; ; result . The exact value is 0.0407622. Only on [0, 1) needed a polynomial; is an exponent field of 127 − 5 = 122.
Exercise 5 (bits per doubling). Explain why halving the segment width of a degree- piecewise polynomial gains bits. Why does script 02 measure 3.94 instead of 4 for degree 3, and why do the curves flatten at ~23 bits?
Answer
The interpolation error of degree on an interval of width is , which scales as . Halving divides the error by : bits. The constant also varies between segments, so measured gains differ slightly from the theory; and at high accuracy the float32 arithmetic (rounding of coefficients and of Horner’s steps, ~2⁻²³–2⁻²⁴) adds an error floor that no table can remove.
Exercise 6 (Newton steps). Starting from a 4-entry reciprocal table (3.2 bits, script 02), how many Newton steps reach float32 accuracy? What does each step cost in latency on the model of §3.4?
Answer
Bits roughly double: 3.2 → 6.3 → 12.7 → ~23 (the script measures 6.3 and 12.7 after one and two steps). Three steps reach float32, each a multiply, a subtraction and a multiply in series: 3 + 4 + 3 = 10 cycles per step, 30 cycles in all — vs a 256-entry table (9 bits) that needs two steps. The table-size vs latency trade-off.
Exercise 7 (when errors do not cancel). The bit-trick exp has a relative error that depends only on frac. Construct two logits for which softmax with this exp is wrong by about 6%, and explain why the error in §3.6’s attention experiment is 2 × 10⁻², not 6 × 10⁻².
Answer
Take (f = 0: the trick is exact, error 0) and with (where overestimates by 6.1%), e.g. . Then the ratio is 6.1% too high: the probabilities are off by ~3% each, in opposite directions. In a real row the errors of many logits average out in the sum and partly cancel in the output , and the max-subtracted largest logit always has . The measured output error is a weighted average, not the worst case.
Exercise 8 (issue-bound or ALU-bound?). gelu needs 6 ALU instructions, 1 SFU instruction, 1 load and 1 store per chunk of vlen elements, plus 2 scalar bookkeeping instructions per load. On 16 ALU lanes with single issue, which resource binds for vlen = 16 and vlen = 256? Compare with script 04, Part 1.
Answer
Per chunk: 9 vector + 2 scalar = 11 instructions. vlen = 16: issue needs 11 cycles per chunk, the ALU 6 × 1 = 6 → issue-bound, 11/16 = 0.69 cycles per element (script: 712 cycles per 1,000, issue). vlen = 256: issue 11 cycles, ALU 6 × 16 = 96 → ALU-bound, 0.375 cycles per element (script: 377). Long vectors turn instruction overhead into a rounding error.
Exercise 9 (Little’s law). On the 1,024-lane unit of §5.3 (ALU latency 4, SFU latency 19, 256 SFU lanes), estimate the dependent chain of one 1,024-element softmax row and the number of rows that must be in flight to keep the ALU busy. How many KiB of registers is that (3 registers of 1,024 fp32 values per row)?
Answer
Roughly: load 2 + max-reduce (1 group + 10 tree levels → ~44 cycles) + subtract 4 + exp (4 groups + 19) + sum-reduce (~44 after the last exp) + reciprocal 19 + multiply 4 + store 2 ≈ 145 cycles, for 4 ALU cycles of work. Little’s law: about 145/4 ≈ 36 rows in flight, × 3 registers × 4 KiB = ~430 KiB of vector registers. Script 04 gives 16 rows 64 registers and still runs at 3.1× its bound. Hardware answers: a faster cross-lane reduction (fewer, wider tree levels), more registers, or overlapping softmax with other work.
Exercise 10 (when is prologue dequantization acceptable?). On the reference core, prologue dequantization of MXFP4 weights costs 3 vector operations per weight element. For which M does it cost at most 10% of the matrix time? Which serving regimes satisfy that?
Answer
Vector/matrix time = (3/M) × 64 ≤ 0.1 → M ≥ 1,920. Prefill of long prompts satisfies it; decode never does (M = batch, rarely above a few hundred). Weight-only quantization with on-the-fly dequantization is therefore a decode technique only if the dequantization is very cheap (packed conversions) or done by the matrix unit.
Exercise 11 (programming: a RoPE kernel). Add a vswap operation to vector_unit.py (out[2i] = −a[2i+1], out[2i+1] = a[2i]) and a k_rope kernel computing y = x·cos + swap(x)·sin from arrays x, c, s. Check it against numpy, and compare its work_per_element with the 3 ALU operations script 01 assumes.
Answer
Program per chunk: three loads (x, c, s), vswap t ← x, vmul t ← t · s, vfma y ← x · c + t, store. Work: 3 ALU operations per element, as assumed, and 6 bytes of loads (bf16 x, cos, sin). In a real kernel cos and sin depend only on the position and the dimension, not the head, so they can stay in registers across the 32 + 8 heads: loads fall to ~2 bytes per element. The numpy check: compute pairs (x₀ cos − x₁ sin, x₁ cos + x₀ sin).
Exercise 12 (programming: online softmax). Write a kernel that computes softmax with ONE pass over the input for the statistics: keep a running maximum m and a running sum ℓ; for each chunk with maximum m′, set ℓ ← ℓ·exp(m − m′) + Σ exp(x − m′). Then a second pass writes exp(x − m)/ℓ. Count ALU and SFU operations per element and compare with the three-pass kernel. Why is this the heart of FlashAttention (Lecture 10)?
Answer
Pass 1 per element: max-reduce (1), subtract (1), exp (1 SFU), sum-reduce (1); per chunk a scalar exp and a multiply-add for the rescale. Pass 2: subtract (1), exp (1 SFU, recomputed), multiply (1). Total ~6 ALU + 2 SFU vs 4 + 1 for the three-pass kernel that keeps the exps in registers. Online softmax costs MORE arithmetic but reads the input only twice and never needs the whole row at once. In attention the row is a row of that does not fit on chip, and fusing pass 2 with the PV product means the probabilities are never written to memory: FlashAttention trades cheap recomputation for expensive memory traffic.
10. Further reading
- J. L. Hennessy, D. A. Patterson, Computer Architecture: A Quantitative Approach, chapter on vector architectures (Cray-1 chaining, lanes, strip-mining).
- T. Norrie et al., “The design process for Google’s training chips: TPUv2 and TPUv3”, IEEE Micro 41(2), 2021.
- J. Shah, G. Bikshandi, Y. Zhang, V. Thakkar, P. Ramani, T. Dao, “FlashAttention-3: fast and accurate attention with asynchrony and low-precision”, 2024.
- S. F. Oberman, M. Y. Siu, “A high-performance area-efficient multifunction interpolator”, ARITH 2005.
- J.-M. Muller, Elementary Functions: Algorithms and Implementation, 3rd ed., Birkhäuser 2016 — range reduction (Cody–Waite), minimax and Remez.
- N. N. Schraudolph, “A fast, compact approximation of the exponential function”, Neural Computation 11(4), 1999.
- S. Kim et al., “I-BERT: integer-only BERT quantization”, ICML 2021 — integer polynomial approximations of GELU, exp and softmax.
- OCP Microscaling Formats (MX) v1.0 specification, 2023.
11. Next lecture
Lecture 7, Memory systems, follows the data. The matrix and vector units of Lectures 5 and 6 are fed from a hierarchy of registers, PE buffers, a global buffer, and HBM or DRAM. We will build a banked SRAM and watch strided accesses collide on banks; model DRAM rows, banks and refresh; double-buffer transfers against compute; and derive how much off-chip traffic a tiled GEMM needs for a given buffer size (the √S law). Lab 3’s global buffer with a near-memory processor closes the loop: some of this lecture’s vector work — reductions, element-wise operations — can be done next to the SRAM instead of after moving the data.