Lecture 6 · Vector and Scalar Units: Everything the Matrix Unit Cannot Do

Hardware Accelerators for Machine Learning · Lecture 06。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

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’s numfmt. 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:

  1. 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.
  2. 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.
  3. 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).
  4. 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.
  5. Decide how accurate a function must be: why softmax forgives a constant error, and why bf16 rounding of probabilities sets the floor.
  6. 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.
  7. 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).
  8. 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

AssumedIntroduced hereDeveloped later
Lecture 1: roofline, instruction overhead (70 pJ)Amdahl’s law for accelerators, vector ops per MACmemory traffic of unfused operators (L10)
Lecture 2: pipelining, latency vs II, software pipeliningvector units: lanes, chaining, decoupled dispatch, interleavingthe global buffer feeding the vector unit (L7)
Lecture 4: number formats, MX/NVFP4, HW2’s prologue/epiloguefunction approximation: range reduction, minimax, NewtonFlashAttention’s online softmax (L10)
Lecture 5: systolic arrays, outputs per cyclescalar core, VLIW, Little’s lawGPU 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

SymbolMeaning
LLALU lanes: elements one vector ALU instruction processes per cycle
SSSFU lanes: special-function (exp, 1/x, 1/√x, tanh) results per cycle
vlenelements in one vector register (the longest vector instruction)
chimecycles one vector instruction occupies its pipe: ⌈vlen / L⌉
element groupthe elements one pipe processes in one cycle
KKreduction length of a GEMM: MACs per output element
SFUspecial-function unit
ulpunit in the last place: the spacing of representable numbers
bitscorrect 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:

OperationPer elementWhy it is hard for a matrix unit
RMSNorm / LayerNormsquare, 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)·sinelement-wise with a permutation
softmaxmax (reduction), subtract, exp, sum (reduction), 1/x, scaletwo reductions, one transcendental per element
SiLU(gate)·up (SwiGLU)sigmoid or tanh, two multipliesa transcendental per element
residual addone addtrivial but memory-heavy
quantize / dequantize (FP8, MX)block max, exponent, scale, roundreductions over blocks, format conversion

Script 01 counts the work of each from the vector programs of vector_unit.py (§4):

KernelALU ops / elementSFU ops / element
rmsnorm3.060
softmax4.001.00
swiglu4.001.00
residual1.000
mx_quantize5.160
rope (assumed)3.000

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 prefillSizeShare of operationsShare of time
GEMMs4.64 × 10¹¹ MACs99.94%89.3%
softmax67.1 M elements0.04%6.6%
SiLU(gate)·up29.4 M elements0.02%2.9%
RMSNorm × 216.8 M elements0.01%0.6%
RoPE10.5 M elements0.00%0.4%
residual × 216.8 M elements0.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 KK produces one output per KK MACs, so a matrix unit doing PP MACs per cycle emits P/KP/K outputs per cycle. Whatever follows the GEMM must process that many elements per cycle:

vector rate needed=PK×operations per output\text{vector rate needed} = \frac{P}{K} \times \text{operations per output}

Script 01, Part 5 applies it to a ResNet-50 bottleneck block and to attention:

LayerKVector ops per MACOutputs per cycleVector / matrix time (serial)
1×1 conv 256→64 + ReLU2560.003925625%
3×3 conv 64→64 + ReLU5760.001711411%
1×1 conv 64→256 + residual + ReLU640.03121,024200%
Llama layer, prefill 2,048 (all)4,096 / 14,3360.0013–12%
attention softmax128 (head_dim)0.0195256200%

Two lessons:

  • CNNs need little vector work per MAC. ReLU after a convolution with KK 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 K=64K = 64, a serialized ReLU + residual add would cost twice the matrix time.)
  • Attention needs a real vector unit. Each score costs only 2×2 \times 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 ff of the time is accelerated by a factor ss and the rest is not:

speedup=1(1−f)+f/s  ≤  11−f\text{speedup} = \frac{1}{(1 - f) + f/s} \;\le\; \frac{1}{1-f}

For an accelerator, ff is the GEMM share of the time and ss 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 / cycleLayer timeSpeedupVector share
4,096109 ms1.00×0.7%
16,38427.8 ms3.91×2.9%
65,536 (reference)7.55 ms14.4×10.7%
262,1442.50 ms43.5×32.5%
1,048,5761.55 ms70.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 4×dh4 \times d_h FLOPs per score (2dh2 d_h for QKᵀ, 2dh2 d_h for PV) and one exp. Compare with what the hardware delivers per exp it can compute (script 01, Part 3):

MachineMatrix FLOP/sexp/sFLOP per expexp/matmul time: dhd_h = 64128256
H100 SXM989.4 T3.86 T2561.000.500.25
reference core137.6 T0.13 T1,0244.002.001.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 dh=128d_h = 128 the exponentials take half as long as the matrix multiplications; at dh=64d_h = 64 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 ff of the exps to the ALU lanes balances the two pipes when (4+6f)/L=(1−f)/S(4 + 6f)/L = (1 - f)/S. On the reference core that gives f=0.29f = 0.29 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):

WorkloadMACs/cycleMatrix partVector partSerializedOverlappedGain
prefill 2,04865,5366.74 ms811 µs7.55 ms6.74 ms1.12×
prefill 2,048262,1441.69 ms811 µs2.50 ms1.69 ms1.48×
decode b6465,5361.62 ms40.9 µs1.66 ms1.62 ms1.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:

  1. 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.
  2. A short polynomial evaluated by Horner’s rule, (((cdt+cd−1)t+… )t+c0)(((c_d t + c_{d-1}) t + \dots) t + c_0): dd multiply-adds for degree dd.
  3. Newton–Raphson iterations, which double the number of correct bits per step (for 1/x and 1/√x).
  4. 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

ex=2xlog⁡2e=2n⋅2f,n=⌊xlog⁡2e⌋,  f∈[0,1)e^x = 2^{x \log_2 e} = 2^{n} \cdot 2^{f}, \qquad n = \lfloor x \log_2 e \rfloor,\; f \in [0, 1)

Multiplying by 2n2^n is an addition to the exponent field of the result — free in hardware. Only 2f2^f on [0,1)[0, 1) needs approximating, and it lies in [1,2)[1, 2): a smooth function on a short interval. Script 02, Part 1 (inputs in [−30,0][-30, 0], the softmax range):

DegreeTaylor at 0Chebyshev interpolationMinimax (Remez)Minimax + Cody–WaiteArea (µm², 45 nm)
12.7 bits4.75.15.123,768
24.98.89.29.235,652
37.513.313.713.747,536
410.417.617.818.559,420
513.519.019.022.471,304
616.719.119.123.083,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 d+2d + 2 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 xlog⁡2ex \log_2 e is rounded to float32, and half an ulp of y≈40y \approx 40 is 2−192^{-19}, which becomes a relative error of the result. Cody–Waite reduction computes ff as (x−nln⁡2hi−nln⁡2lo)log⁡2e(x - n \ln 2_{hi} - n \ln 2_{lo}) \log_2 e, where ln⁡2hi\ln 2_{hi} has few enough bits that nln⁡2hin \ln 2_{hi} 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 223(xlog⁡2e+127)2^{23}(x \log_2 e + 127) and reinterpreting its bits as a float32 gives 2n(1+f)2^n (1 + f): range reduction plus the linear “polynomial” 2f≈1+f2^f \approx 1 + f, 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 dd on segments of width hh has an error proportional to hd+1h^{d+1}. Halving the segment width buys d+1d + 1 bits. Script 02, Part 2 measures it for 2f2^f (bits gained per doubling of the table, from 1 to 4 segments):

Degree 0 (pure table)Degree 1Degree 2Degree 3
0.972.133.143.94

A pure table needs 2b2^{b} entries for bb 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:

TargetMax rel. errorCheapest designTable bitsArea µm²Latency
bf162⁻⁸128-entry table of 2f2^f4,09614,7518
fp162⁻¹¹8 linear segments51224,12612
fp32-class2⁻²²32 quadratic segments + Cody–Waite3,07261,57024

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 1/x1/x: write ∣x∣=m⋅2e|x| = m \cdot 2^e with m∈[1,2)m \in [1, 2), look up a seed r≈1/mr \approx 1/m in a table, and refine:

r←r (2−mr)r \leftarrow r\,(2 - m r)

This is Newton’s method on g(r)=1/r−mg(r) = 1/r - m. If r=(1+ϵ)/mr = (1 + \epsilon)/m, one step gives (1−ϵ2)/m(1 - \epsilon^2)/m: the relative error is squared, so the correct bits double. For 1/x1/\sqrt{x} the step is r←r(1.5−0.5 mr2)r \leftarrow r(1.5 - 0.5\,m r^2) (error →≈1.5ϵ2\to \approx 1.5\epsilon^2), with the exponent made even so that 4k=2k\sqrt{4^k} = 2^k stays an exponent operation. Script 02, Part 3:

FunctionSeedSeed only+1 Newton+2 NewtonArea (1 step)Latency (1 step)
1/x16 entries5.0 bits10.120.019,942 µm²11
1/x256 entries9.018.022.725,31811
1/x16 entries, linear11.121.722.932,18515
1/√x64 entries6.412.322.628,71814
1/√xmagic constant, no table4.99.217.731,46817

The “magic constant” is the fast inverse square root of Quake III: subtracting the bit pattern of xx, 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 [−10,10][-10, 10]):

ApproximationMax abs. errorArea µ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 segments6.3 × 10⁻⁵28,069
SiLU = x/(1 + e⁻ˣ), cubic exp + 2-step reciprocal1.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, e~i=(1+δ)exi\tilde e_i = (1 + \delta) e^{x_i}, the factor cancels:

(1+δ) exi∑j(1+δ) exj=exi∑jexj\frac{(1+\delta)\, e^{x_i}}{\sum_j (1+\delta)\, e^{x_j}} = \frac{e^{x_i}}{\sum_j e^{x_j}}

Only the variation of the error across inputs matters. Script 02, Part 5 runs attention with 64 queries, 1,024 keys and dh=64d_h = 64, and measures the output error relative to float64:

expexp rel. errorDiffuse, fp32 PDiffuse, bf16 PPeaked, fp32 PPeaked, bf16 P
exact (float32)–8.7e-81.7e-31.2e-71.5e-3
exact × 1.033.0e-28.9e-81.7e-31.2e-71.5e-3
bit trick (minimax shift)3.6e-22.0e-22.1e-21.2e-21.2e-2
degree 13.0e-22.2e-22.2e-21.4e-21.4e-2
degree 21.7e-31.3e-32.1e-37.1e-41.6e-3
degree 37.6e-55.6e-51.7e-33.3e-51.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 n≤n \le 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):

OpPipeDispatchedFirst groupLast groupReady
vld xld0013
vredmax → s_maxalu12533
vsub x − s_maxalu2333640
vexpsfu3375271
vredsum → s_sumalu4597199
srecipscalar59999118
vmul e · s_invalu6118121125
vstst7123125127

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 / programgelusoftmaxrmsnormresidual
strict in-order, no chaining1.613.002.232.64
strict in-order, chaining1.202.321.921.76
strict in-order, chaining, 4 rows interleaved1.131.171.211.77
dispatch queues, chaining1.202.321.921.76
dispatch queues, chaining, 4 rows interleaved1.011.011.011.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 lanesSFU lanessoftmaxswiglugelurmsnorm
1616250252375204
164395285454204
1611,145 (SFU-bound)1,0351,204204
64161357812072
644323 (SFU-bound)26630772

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):

KernelRows interleavedn = 32641282565121,0242,048
softmax112.507.254.132.561.911.441.23
softmax43.382.131.381.091.08regsregs
rmsnorm17.334.632.821.911.491.281.18
rmsnorm42.481.521.051.011.011.06regs

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 expLatencyCycles, 1 row at a timeCycles, 4 interleavedMax error / max p
degree 1113,6592,1871.1e-2
degree 3193,9152,2193.0e-5
degree 5 + Cody–Waite354,4272,2835.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:

vlenLoop controlIssue widthInstructions / elementCycles / 1,000 elBindingInstr. energy pJ/el
16software loop10.688712issue48.1
16hardware loop + AGU10.562587issue39.4
16hardware loop + AGU20.562493latency39.4
64software loop10.172379ALU12.0
256hardware loop + AGU10.035377ALU2.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):

KernelRows interleavedIssue 1Issue 2Issue 4
gelu4893889887
gelu16813685650
softmax42,3492,3452,343
softmax16877809801

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 2−X2^{-X} (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, ∑i(saai)(sbbi)=sasb∑iaibi\sum_i (s_a a_i)(s_b b_i) = s_a s_b \sum_i a_i b_i 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, K⋅NK \cdot N, amortized over the M rows.
  • B. In an epilogue on the vector unit: the matrix unit emits one partial sum per block, M⋅N⋅K/32M \cdot N \cdot K/32 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 sasbs_a s_b once per block (Lecture 4). The vector unit only quantizes the activations, M⋅KM \cdot K 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):

GEMMA. prologue on VUB. epilogue on VUC. in the matrix unit
prefill, M = 2,0480.09×2.00×0.02×
decode, M = 643.00×2.00×0.02×
decode, M = 1192×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):

MachineMemoryWeights per cycleVector ops needed / cycleLanesNeeded / available
reference core600 GB/s1,0763,2271,0243.15
H100 SXM (fp32 lanes)3,350 GB/s3,44610,33816,8960.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

  1. 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.
  2. 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 2dh2 d_h MACs.
  3. 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 dhd_h = 128 (FlashAttention-3 overlaps them; moving 29% of them to FMA lanes speeds softmax up 1.4× in our model).
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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 dhd_h = 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 dhd_h = 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 dhd_h = 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, 2f2^f and the result.

Answer

y=−3.2×1.442695=−4.616624y = -3.2 \times 1.442695 = -4.616624; n=⌊y⌋=−5n = \lfloor y \rfloor = -5; f=y−n=0.383376f = y - n = 0.383376; 2f=e0.383376ln⁡2=e0.265738=1.304382^f = e^{0.383376 \ln 2} = e^{0.265738} = 1.30438; result =1.30438×2−5=0.0407619= 1.30438 \times 2^{-5} = 0.0407619. The exact value is 0.0407622. Only 2f2^f on [0, 1) needed a polynomial; 2−52^{-5} is an exponent field of 127 − 5 = 122.

Exercise 5 (bits per doubling). Explain why halving the segment width of a degree-dd piecewise polynomial gains d+1d + 1 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 dd on an interval of width hh is ∣f(d+1)(ξ)∣/(d+1)!×∏(x−xi)|f^{(d+1)}(\xi)| / (d+1)! \times \prod (x - x_i), which scales as hd+1h^{d+1}. Halving hh divides the error by 2d+12^{d+1}: d+1d + 1 bits. The constant f(d+1)f^{(d+1)} 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 f=f = frac(xlog⁡2e)(x \log_2 e). 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 x1=0x_1 = 0 (f = 0: the trick is exact, error 0) and x2x_2 with f≈0.44f \approx 0.44 (where 1+f1 + f overestimates 2f2^f by 6.1%), e.g. x2=0.44ln⁡2=0.305x_2 = 0.44 \ln 2 = 0.305. Then the ratio p2/p1p_2/p_1 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 PVPV, and the max-subtracted largest logit always has f=0f = 0. 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 QKTQK^T 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.

← 返回课程目录