Lecture 9 · Efficiently Evaluating DNNs on GPUs: Transformers and ConvNets

Parallel Computing · Lecture 09。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

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

本篇目录

Maps to: Stanford CS149 Fall 2025, Lecture 9 (Oct 21), slide deck 09_dnneval (75 slides). Context for Programming Assignments 4 (a fused conv + max-pool on an AI accelerator) and 5 (fast CUDA kernels). Sources: the public Fall 2025 slides; the 2023 lecture video; K. Goto and R. van de Geijn, “Anatomy of High-Performance Matrix Multiplication” (2008); T. Dao et al., “FlashAttention” (2022). Every experiment and number below was written for these notes and run on the author’s machine (Apple M4 Pro; clang 21, macOS 27; numpy 2.5). Code: code/lecture09/. Reading time: ~80 minutes for the prose; ~10 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain what a deep neural network (深度神经网络, DNN) computes: fully-connected layers as matrix-vector products, convolution layers (卷积层) as filters applied over an image with many channels and filters, activations and pooling.
  2. Show that a convolution layer is a dense matrix multiplication (稠密矩阵乘, GEMM) (im2col (图像转列), “explicit GEMM”), state what materializing it costs, and how implicit GEMM (隐式 GEMM) avoids that.
  3. Raise the arithmetic intensity of matrix multiplication by blocking (分块) at every level (cache, registers, SIMD), and explain why a register-blocked micro-kernel (寄存器分块微内核) is the decisive step.
  4. Explain operator fusion (算子融合) and quantify the traffic it removes (conv + scale/bias + pool; softmax).
  5. Compute attention (注意力) without storing the N × N matrix (FlashAttention), using the online softmax (在线 softmax) rescaling rule, and explain how on-chip memory size sets its traffic.
  6. Say why GPUs suit DNNs, and why that question leads to specialized hardware (Lecture 10).

0.2 Prerequisites and scope

  • Prerequisites: Lecture 3 (bandwidth-bound programs), Lecture 6 (roofline, blocking, loop fusion), Lecture 7 (GPU shared memory, warps), Lecture 8 (thinking in whole-array operations).
  • Scope: the systems side of evaluating DNNs: how to make their kernels run near peak. What the networks learn is a topic for machine learning courses; here they are just computations. PA4 asks you to fuse a convolution with max pooling on an AI accelerator, and PA5 to write fast CUDA kernels. These notes teach the techniques with different code and give no solutions.

0.3 Section → code map

SectionIdeaDemo in code/lecture09/
§2–§3convolution = GEMM; im2col’s cost; arithmetic intensity of layers01_conv_as_gemm.py
§4blocking a matrix multiply, from 2.5 to 573 GFLOP/s02_gemm_ladder
§6fusion: softmax with 5 passes vs 103_softmax_fusion
§7attention without the N × N matrix04_flash_attention.py

Run them all with cd code/lecture09 && make run (~5 seconds). The C++ demos need macOS on Apple silicon; the Python demos need numpy.

0.4 Notation

  • Convolution layers use NVIDIA’s symbols (slide 29): batch N, input channels C, output channels (filters) K, filter size R × S, input H × W, output P × Q.
  • For attention: sequence length N, embedding size d; Q, K, V are N × d. Matrix multiply C = A B with A: M × K, B: K × N. GFLOP/s counts a multiply-add as 2 FLOPs.

1. Things you already know, and should remember

Slides 3–11 restate the previous lectures in one picture, because, in the slide’s words, “if you know the previous slide, you know almost everything you need to know about the software side of performance optimization of modern AI.”

  • Pipelining (slide 4): overlap loading the next data with computing on the current data. The price is on-chip storage for both, called double buffering (双缓冲).
  • The roofline (slides 6–8): a program’s throughput is bounded by min(peak compute, bandwidth × arithmetic intensity). A machine with more compute but the same memory moves the ridge point to the right. More programs then become bandwidth-bound.
  • Loop fusion (slide 9): computing E = D + (A + B) × C in one loop instead of three raises the intensity from 1/3 to 3/5 (Lecture 6 measured 1.8×).
  • The review (slide 10):
    • when communication and computation overlap, the machine’s two throughputs and the program’s intensity decide whether it is bandwidth-bound or compute-bound;
    • overlapping costs footprint (buffers on chip);
    • faster hardware makes programs more bandwidth-bound;
    • higher intensity (a program change) makes them more compute-bound.

Slide 11’s footnote adds the hardware side, which Lecture 10 develops: data movement costs energy, and chip area spent on storage cannot be spent on compute, so buffers should be as small as possible.


2. What a deep neural network computes

2.1 Circuits of multiply-adds

Slide 13 writes an expression, max(max(0, a·b + c·d) + e·f + g·h, i·j), as a graph of multiplies, adds and maxes. A DNN is such a graph, very large and very regular.

The basic unit, or “neuron” (slide 14), has n inputs and n + 1 parameters (weights wᵢ and a bias b) and computes f(Σ xᵢ wᵢ + b). f is a nonlinearity, e.g. the rectified linear unit (ReLU) f(x) = max(0, x), or a sigmoid. A machine-learning reading: a binary classifier. A computational reading: “it is just a circuit!”

Units are arranged in layers (slide 15). In a fully-connected layer every unit sees every input. A layer of 4 units with 3 inputs is (slide 16)

y = f(W x + b), with W a 4 × 3 matrix: a matrix-vector product plus an elementwise f.

2.2 Convolutions

Slide 17’s C code applies a 3 × 3 filter with weights 1/9 to a 1024 × 1024 image. It is a blur: each output pixel is the average of its 3 × 3 neighbourhood. In a convolutional layer (slide 19), units are locally connected (each output sees a 3 × 3 window) and share the same parameters (the same 3 × 3 weights everywhere). Different weights detect different patterns. The filters [−1 0 1; −2 0 2; −1 0 1] and its transpose respond to horizontal and vertical gradients, i.e. edges (slide 20). A filter is a pattern detector, and an output pixel is the strength of its response.

Real layers apply many filters at once (slides 21–22): 96 filters of 11 × 11 × 3 on an RGB image produce 96 response maps. With multiple input channels, each filter is 3D (R × S × C) and sums over the channels (slide 28). Layers alternate with ReLU and pooling (slide 23: keep the max of each 2 × 2 region, which reduces the data 4×).

Slide 25 writes a batched convolution layer as a seven-deep loop nest: images, output rows, output columns, filters, then the input channels and the R × S window. It has significant data reuse: every weight is reused at every output position, and every input value by every filter and by up to R × S output positions.


3. Convolution as matrix multiplication

3.1 im2col: the “explicit GEMM”

Slides 26–29 turn the loop nest into one matrix multiply. Build a matrix with one row per output position (N·P·Q rows), holding the R × S × C input values under the filter there; this is im2col. Stack the K filters as columns of an (R·S·C) × K matrix. Then

outputs (N·P·Q × K) = im2col(input) (N·P·Q × R·S·C) × filters (R·S·C × K).

The output positions near the border use zero-padding (slide 26).

01_conv_as_gemm.py, Part A computes a 3 × 3 layer (batch 8, 58 × 58 × 64 input, 64 filters, 1.85 GFLOP) both ways. With small-integer data the arithmetic is exact, and the outputs are identical. The GEMM here is (25,088 × 576) × (576 × 64).

3.2 Why GEMM is the heart of DNNs

Slides 30–32: matrix multiplication is the kernel of fully-connected layers (batched), convolutional layers (via im2col), and the attention blocks of a transformer, where Q Kᵀ and P V are matrix products. Optimize GEMM, and you have optimized most of a DNN’s arithmetic.

But which layers can run near peak? Demo 01, Part B computes the best-case arithmetic intensity (every byte moved once) against the author’s ridge point of ~3.3 FLOP/byte (Lecture 6):

layerFLOP/bytebound
fully connected 4096 → 4096, batch 10.5memory
fully connected 4096 → 4096, batch 6431compute
conv 3 × 3, 56 × 56 × 64 → 64, batch 1128compute
MobileNet depthwise 3 × 3, 112 × 112 × 642.2memory
MobileNet pointwise 1 × 1, 32 → 6410.6compute
attention scores Q Kᵀ, N = 4096, d = 6431compute

A batch-1 fully-connected layer is a matrix-vector product: each weight is used once, so it is memory-bound on every machine. That is why generating text one token at a time with a large language model is bandwidth-bound. Batching turns it into a matrix-matrix product with 60× the intensity. Depthwise convolutions have little reuse. Slide 40’s MobileNet table makes the point that different layers of one DNN may need different strategies: some are GEMMs, some are bandwidth problems. “Ugh for library implementers!”

3.3 The cost of materializing im2col

Slide 33: to use an off-the-shelf GEMM library, you must materialize the input matrix. For a convolution layer that increases DRAM traffic by a factor of R × S and needs a lot of extra storage. In demo 01 the im2col matrix is 8.4× the input (110 MiB vs. 13 MiB). And our “direct” version, one GEMM per filter tap applied to a shifted view of the input with no copy, is 1.9× faster than building im2col and doing one big GEMM. The copy costs more than the bigger GEMM saves.

The production fix is implicit GEMM (slides 42–43): never build the full matrix in DRAM. Materialize only a sub-block of it at a time in on-chip (shared) memory, then run a well-tuned shared-memory GEMM on that block. That adds no off-chip storage and no extra DRAM traffic. Libraries such as NVIDIA’s CUTLASS (slide 44) provide the building blocks: fast shared-memory and warp-level GEMMs, iterators that load blocks and index tensors, reductions.


4. Making matrix multiplication fast

4.1 The textbook loop has low arithmetic intensity

Slide 34:

for (int j = 0; j < M; j++)
    for (int i = 0; i < N; i++)
        for (int k = 0; k < K; k++)
            C[j][i] += A[j][k] * B[k][i];

What is the problem? Low arithmetic intensity: it does not exploit temporal locality in its accesses to A and B. Each multiply-add loads B[k][i] from a new cache line, since the loop walks down a column, and that value is gone from the cache before it is needed again.

02_gemm_ladder climbs from this loop to the machine’s peak on 960 × 960 floats (1.77 GFLOP per multiply). Each result is checked against a double-precision reference; differences of ~1e-6 are float rounding from different summation orders:

stepthreadsGFLOP/s% of measured peak
1. textbook i-j-k (slide 34)12.52%
2. loop interchange i-k-j13130%
3. cache-blocked 64 × 64 (slide 35)12726%
4. packing + 8 × 12 NEON register-blocked micro-kernel1111~100%
5. the same on 8 performance cores857389%
Apple Accelerate cblas_sgemm(library)3,711576% of the NEON peak

4.2 Loop interchange

Swapping the two inner loops (i, k, j) makes the innermost loop walk along a row of B and of C, contiguously, with A[i][k] a constant. Same arithmetic, different order: the compiler vectorizes it, and it runs 12× faster. It is still limited by loading and storing C for every multiply-add.

4.3 Cache blocking

Slide 35: compute a partial result for a block of C while the required blocks of A and B stay in the cache. Each value loaded is then reused BLOCKSIZE times. Slide 35’s self-check asks whether you want as big a BLOCKSIZE as possible. No: the blocks of A, B and C must fit in the cache together. Slide 36 blocks hierarchically, once per cache level, and notes that “not shown: final level of blocking for register locality”.

On this machine cache blocking alone did little. At 960 × 960 all three matrices (3.5 MiB each) already fit in the 16 MiB L2, and the blocked version’s shorter inner loops cost more than they save (27 vs. 31 GFLOP/s). At 2400 × 2400 (21 MiB each) blocking gains 1.16×. The real limit of steps 2–3 is not the cache but the inner loop: two loads and a store for each vector multiply-add.

4.4 Register blocking: the decisive step

Slides 37–39 vectorize within a block, choosing which dimension maps to SIMD lanes. Scheme (3) keeps a SIMD_WIDTH × SIMD_WIDTH chunk of C in vector registers and, for each k, multiplies a vector of A by broadcast elements of B. The innermost operations are all independent.

Demo 02’s step 4 is that idea in the form high-performance libraries use (the GotoBLAS/BLIS design):

  • a micro-kernel keeps an 8 × 12 block of C in 24 NEON registers. For each k it loads 8 values of A and 12 of B (5 vector loads) and does 24 vector multiply-adds (96 FMAs), multiplying B vectors by single lanes of A (vfmaq_laneq_f32). The FMA-to-load ratio, not the cache, now sets the speed;
  • around it, A and B are packed: copied into contiguous panels (MR rows of A and NR columns of B per panel), so that the micro-kernel streams through memory in the order it needs. Blocks of KC = 256 rows of B and MC = 128 rows of A are sized for the L1 and L2 caches. Packing is O(n²) extra work that makes the O(n³) part fast.

One core: 111 GFLOP/s, 44× the textbook loop, at its measured peak. That measurement varies by ~10% between runs, so the micro-kernel lands at 104–115% of it. Eight cores, each computing its own rows of C: 573 GFLOP/s, 89% of their measured peak.

4.5 The library, and a surprise

Apple’s Accelerate library does the same multiply in 0.5 ms: 3.7 TFLOP/s, about 5× the NEON peak of all 8 performance cores. It is not using the NEON units. The M4 has dedicated matrix-multiply hardware (Arm’s Scalable Matrix Extension, “AMX” in Apple’s earlier chips) that only libraries like Accelerate drive. The vendor library is fast here because of a specialized unit, not only because of better code. That is Lecture 10’s topic, and it is on the author’s laptop.

4.6 Libraries and DSLs

Slides 41–54 survey how this is done in practice:

  • Libraries: cuBLAS/cuDNN (NVIDIA), and chip-specific libraries such as AWS NKI (slide 51). cuDNN offers several convolution algorithms (implicit GEMM, explicit GEMM, FFT, Winograd; slide 54) and picks one per layer shape.
  • CUTLASS (slide 44): C++ templates for building custom GEMM-based layers (shared-memory GEMMs, warp-level GEMMs, tile iterators), for shapes cuDNN has not tuned.
  • Triton (slides 45–46, 53): a Python DSL in which you write operations on blocks of tensors (load a block into shared memory, compute on it), and the compiler handles threads and memory details. A full matmul has two levels of blocking.
  • ThunderKittens (slide 47): a CUDA library of tile-based primitives (asynchronous tile loads and stores, special memory layouts) to make expert programmers more productive.

Slides 48–49 add a GPU constraint: an 80-SM V100 needs a lot of parallel work to fill. A convolution with batch 1 and 64 × 64 outputs (2 MB of output) runs at a much lower fraction of peak than one with batch 32 and 256 × 256 outputs (1 GB of output). Small layers cannot occupy the machine.


5. Reflection: blocking everywhere

The same idea appears at every level, each time to raise the arithmetic intensity seen by the level below:

levelwhat is blockedreuse it creates
registersan 8 × 12 tile of Ceach loaded A value used 12 times, each B value 8 times
L1/L2 (or GPU shared memory)KC × NC panels of B, MC × KC blocks of Aeach panel reused for many micro-tiles
DRAM ↔ chiptiles of im2col built on chip (implicit GEMM)no R × S blow-up in DRAM traffic
across operatorsfusion (§6), FlashAttention (§7)intermediates never leave the chip

6. Fusion

6.1 Memory traffic between operations

Slide 56: a convolution followed by scale/bias and a 2 × 2 max pool. Imagine dumping 1 GB of convolution outputs to memory, reading them back to scale them, and reading them again to pool them. Better:

  • apply the per-element scale + bias immediately after each element is computed by the conv;
  • compute each max-pool output as soon as its 2 × 2 region of conv outputs exists.

Then the only data that leaves the chip is the pooled output, a quarter of the size. Slide 57 shows the scale/bias fused into the conv’s last line (output = tmp * scale + bias). Fusing the max pool is left as an exercise: block the output loops so that a 2 × 2 region is produced together. This is PA4’s task on an AI accelerator.

6.2 Softmax, unfused and fused

Slides 58–59: softmax over each row x of an M × N matrix, softmax(x) = f(x) / l(x) with m(x) = maxᵢ xᵢ, f(x)ᵢ = exp(xᵢ − m(x)) and l(x) = Σᵢ f(x)ᵢ. Written as separate whole-matrix operations (m = rowmax(S); T = S − m; E = exp(T); l = rowsum(E); P = E / l), the entire M × N matrix is read or written at every step: reads 5MN + 2M elements, writes 3MN + 2M. Fused (load a row, compute its whole softmax, store it) it reads MN and writes MN, assuming one row fits in on-chip storage.

03_softmax_fusion (4096 × 4096 floats = 64 MiB; Accelerate’s vectorized exp in all versions, so the arithmetic is identical):

versionthreadstimetraffic (model)GB/s
unfused: 5 whole-matrix passes83.7 ms512 MiB144
fused: one row at a time81.7 ms128 MiB77
chunked statistics (slide 63)83.0 ms192 MiB67
unfused110.8 ms512 MiB50
fused18.5 ms128 MiB16

On 8 threads, fusion removes 75% of the traffic and halves the time. The unfused passes run at 144 GB/s, near the memory system’s limit: each does about one operation per 8 bytes. The fused version runs at only 77 GB/s, because it is now limited by computing 16M exponentials. Removing one bound reveals the next. On one core the gain is smaller (1.3×), since one core cannot pull enough bandwidth for memory to dominate. On a GPU, with far more compute per byte, fusion matters even more.

6.3 Fusion in frameworks

Slides 66–69:

  • Old style: library writers hard-coded a few fused operations (TensorFlow’s fused batch-norm, for example).
  • More flexible: cuDNN’s “backend” API takes a graph of operations, and a compiler generates a fused implementation that runs without intermediate trips through memory.
  • Compilers such as torch.compile automatically schedule and fuse a whole model’s operations.

This is Lecture 13’s topic: domain-specific languages and compilers that decide blocking and fusion.


7. Attention, and FlashAttention

7.1 The N² problem

Slides 61–62: a transformer’s attention module takes Q, K, V (each N × d, N tokens with d features) and computes

S = Q Kᵀ (N × N), P = softmax of each row of S, O = P V (N × d).

N can be thousands of tokens or more. The naive implementation stores S and P: N² space, “trouble!!!”. At N = 65,536, that is 32 GiB in float32. Every element of the N × N matrices also goes out to memory and back, between the first matmul, the softmax and the second matmul.

7.2 Softmax in chunks

Slide 63’s observation: split x into chunks x⁽¹⁾, x⁽²⁾. Then

  • m(x) = max(m(x⁽¹⁾), m(x⁽²⁾));
  • l(x) = e^(m(x⁽¹⁾) − m(x)) · l(x⁽¹⁾) + e^(m(x⁽²⁾) − m(x)) · l(x⁽²⁾);
  • f(x) = [e^(m(x⁽¹⁾) − m(x)) f(x⁽¹⁾), e^(m(x⁽²⁾) − m(x)) f(x⁽²⁾)].

So softmax can be computed in chunks. Each chunk’s results were computed relative to its own max; once the global max is known, they are rescaled by e^(m(chunk) − m). Demo 03’s “chunked statistics” row confirms that the result matches the fused one (max relative difference 4e-7, float rounding).

7.3 Fused attention

Slide 64: for each block of query rows Qᵢ, loop over blocks j of keys and values:

load blocks Q_i, K_j^T, V_j, O_i
S_ij = Q_i K_j^T                                   (a small tile of scores)
m_new = max(m_i, rowmax(S_ij));  P_ij = exp(S_ij - m_new)
l_i = exp(m_i - m_new) * l_i + rowsum(P_ij)
O_i = exp(m_i - m_new) * O_i + P_ij V_j            (rescale the running output, add)
m_i = m_new
... after the last block: O_i /= l_i

The N² matrix is never materialized, which saves memory footprint. Each step reads three blocks (Qᵢ, Kⱼ, Vⱼ), does two small matrix multiplies and a few row reductions, and accumulates into an Oᵢ block that stays on chip. That saves bandwidth through high arithmetic intensity. The price is a little extra computation: the running output is rescaled at every step.

04_flash_attention.py implements both in numpy (d = 64, float32). The tiled version matches the naive one to 5e-8 at N = 1,024 and 4,096, and never holds more than one 128 × 128 tile of scores. The naive version holds 128 MiB of S and P at N = 4,096. A traffic model in the style of the FlashAttention paper gives the DRAM traffic (in floats):

Nnaiveflash, 96 KB on chipflash, 192 KBflash, 768 KB
4,0966.8e72.6e71.1e73.2e6
65,5361.7e106.5e92.6e95.7e8

The naive version moves Θ(N²) floats. FlashAttention moves Θ(N² d² / M): each of the N / Br query blocks streams all of K and V once, and the block height Br grows with the on-chip memory M. With 192 KB it moves 6.6× less than naive at N = 65,536; halving the on-chip memory costs 2.5× more traffic. The size of the on-chip memory sets the arithmetic intensity: blocking, again.

Plan vs reality. In numpy on the CPU the tiled version is not faster (0.047 vs. 0.044 s at N = 4,096): Python loops over 1,024 blocks add overhead, and the CPU’s caches hide part of the naive version’s traffic. On GPUs, where the N × N matrices stream through HBM, the FlashAttention paper reports several-fold speedups. Tiling is also the only way to fit long sequences at all. Slide 65 shows FlashAttention written with ThunderKittens tiles.


8. Other tricks, and why GPUs (and why not)

Slide 70: low precision. Weights and activations in 16 and 8 bits are common, 4 bits is arriving, and in the extreme 1 bit. Fewer bits per value means less memory traffic and cheaper arithmetic, so higher effective intensity and throughput. Lecture 10 looks at number formats and their hardware cost.

Slide 71 lists three families of optimization:

  1. Better algorithms: design better models (depth, filter widths, number of filters, stride), often by automatic search for efficient topologies;
  2. Software optimization: good scheduling of the performance-critical operations (blocking, fusion), mostly done by hand, with much research on automating it (Lecture 13);
  3. Approximation: compressing models, lower precision.

Slides 72–73: why are GPUs a good platform for DNNs? The core matrix-matrix computations have high arithmetic intensity, which suits flop-rich GPU architectures; they are data-parallel and SIMD-friendly; GPUs have high memory bandwidth for the layers that are not; and highly optimized kernel libraries exist (cuDNN).

Slide 74 asks the follow-up: why might a GPU be a sub-optimal platform? Hint: is a general-purpose processor really needed? Section 4.5 already gave a hint. On the author’s laptop the dedicated matrix unit does a matrix multiply 6.5× faster than all the general-purpose SIMD cores combined. Slide 75 previews the zoo of specialized accelerators (TPU, Apple Neural Engine, tensor cores, Cerebras, SambaNova…), the subject of Lecture 10.


Summary

  • A DNN is a large, regular circuit of multiply-adds: fully-connected layers are matrix-vector products (matrix-matrix when batched), convolutions apply many 3D filters at every position, attention multiplies Q, K and V.
  • Convolution = GEMM: im2col turns a conv layer into one matrix multiply with identical results. Materializing im2col costs R × S times the input; implicit GEMM builds tiles of it on chip instead.
  • GEMM performance comes from blocking at every level: loop order (12×), cache blocking (little on this machine), and above all register blocking. An 8 × 12 micro-kernel with packed operands reaches one core’s peak, 44× the textbook loop; 573 GFLOP/s on 8 cores. Apple’s library reaches 3.7 TFLOP/s on dedicated matrix hardware.
  • Arithmetic intensity differs by layer: batch-1 FC layers and depthwise convolutions are memory-bound, while batched FC, convolutions and attention matmuls are compute-bound. Different layers need different strategies.
  • Fusion removes passes over memory: softmax goes from 5MN + 2M reads to MN, and from 3.7 to 1.7 ms on 8 cores. Then the next bound (computing exp) appears.
  • FlashAttention combines tiling with the online softmax to compute attention without ever storing the N × N matrix. Its DRAM traffic falls in proportion to the on-chip memory.

Common pitfalls

  • Writing the textbook triple loop and blaming the compiler. Loop order alone is worth 12×; register blocking another 3.5×.
  • Blocking for the cache and stopping there. On modern cores the register level often matters most.
  • Materializing intermediates (im2col matrices, attention scores, unfused elementwise ops) that could stay on chip.
  • Judging a layer’s speed by its FLOPs. A batch-1 FC layer is limited by bytes, not FLOPs.
  • Measuring against an assumed peak. Measure the peak and the bandwidth (Lecture 6), and check results against a reference.
  • Expecting a tiled algorithm to win in an interpreter. Python loop overhead and large CPU caches can hide what tiling buys on a GPU.

Exercises

  1. im2col size. A conv layer has a 224 × 224 × 3 input (padded), 64 filters of 7 × 7 × 3, stride 1, batch 32. How big is the im2col matrix in float32, compared with the input?

    AnswerRows: 32 × 224 × 224 = 1,605,632; columns: 7 × 7 × 3 = 147. Size ≈ 236M floats ≈ 944 MB, against an input of 32 × 224 × 224 × 3 × 4 B ≈ 19 MB: 49× (= R × S) larger.
  2. Intensity of an FC layer. A 4096 → 4096 fully-connected layer with batch B, float32. Write the arithmetic intensity as a function of B, and find the B at which it crosses a ridge point of 3.3 FLOP/byte.

    AnswerFLOPs = 2 · 4096² · B. Bytes = 4 · (4096² + 2 · 4096 · B). Intensity = 2 · 4096² B / (4 · 4096 (4096 + 2B)) = 2048 B / (4096 + 2B). Setting it to 3.3: 2048 B = 3.3 (4096 + 2B), so B ≈ 6.6. From batch ~7 on, the layer is compute-bound on this machine.
  3. Register blocking. A micro-kernel keeps an MR × NR block of C in registers and, per k, loads MR values of A and NR values of B. How many FMAs per loaded float does it do? Compare 8 × 12 with 4 × 4 and 1 × 16, and say which constraint stops MR and NR from growing forever.

    AnswerMR · NR / (MR + NR): 8 × 12 gives 96/20 = 4.8; 4 × 4 gives 2; 1 × 16 gives 16/17 ≈ 0.94. The register file stops it: MR × NR / 4 accumulator vectors plus the loaded operands must fit in 32 NEON registers (8 × 12 uses 24 + 5).
  4. Softmax traffic. Derive slide 59’s count of 5MN + 2M reads and 3MN + 2M writes for the five-step softmax.

    Answerrowmax: read MN, write M. Subtract: read MN + M, write MN. exp: read MN, write MN. rowsum: read MN, write M. Divide: read MN + M, write MN. Reads 5MN + 2M; writes 3MN + 2M.
  5. Online softmax. Chunks x⁽¹⁾ = [1, 3] and x⁽²⁾ = [2, 5]. Compute m and l for each chunk, combine them with slide 63’s rule, and check against the direct computation.

    AnswerChunk 1: m₁ = 3, l₁ = e^(1−3) + e^0 = 1.1353. Chunk 2: m₂ = 5, l₂ = e^(2−5) + 1 = 1.0498. Combined: m = 5, l = e^(3−5) · 1.1353 + e^0 · 1.0498 = 0.1536 + 1.0498 = 1.2034. Directly: e^(−4) + e^(−2) + e^(−3) + 1 = 0.0183 + 0.1353 + 0.0498 + 1 = 1.2034. ✓
  6. FlashAttention traffic. With d = 64 and Bc = 64, how tall can a query block be if 256 KB (64K floats) of on-chip memory must hold Qᵢ, Oᵢ, Kⱼ, Vⱼ and Sᵢⱼ? About how many times are K and V read for N = 32,768?

    Answer2 · Br · 64 + 2 · 64 · 64 + Br · 64 ≤ 65,536, so 192 Br ≤ 57,344 and Br ≤ 298. K and V are read N / Br ≈ 110 times each, instead of the naive version writing and reading two 32,768² matrices.
  • PA4, Fused Conv + MaxPool on Trainium2: implement a convolution layer on an AI accelerator, then fuse the max pool into it (§6.1). Tiling into the accelerator’s on-chip memories and avoiding round trips to device memory are exactly this lecture’s ideas, on different hardware (Lecture 11 covers its programming model).
  • PA5, Make the World’s Fastest CUDA Kernels: performance engineering of GPU kernels; blocking, fusion and arithmetic intensity are the tools.

These notes provide no solutions. The demos use a different machine (CPU and numpy) and different kernels.

Further reading

  • The Fall 2025 slides for this lecture and the 2023 lecture video.
  • K. Goto and R. A. van de Geijn, “Anatomy of High-Performance Matrix Multiplication”, ACM TOMS 34(3), 2008; and F. G. Van Zee and R. A. van de Geijn, “BLIS: A Framework for Rapidly Instantiating BLAS Functionality”, ACM TOMS 41(3), 2015. The packed micro-kernel design of demo 02.
  • S. Chetlur et al., “cuDNN: Efficient Primitives for Deep Learning”, 2014. Implicit GEMM for convolutions.
  • P. Tillet, H. T. Kung and D. Cox, “Triton: An Intermediate Language and Compiler for Tiled Neural Network Computations”, MAPL 2019.
  • M. Milakov and N. Gimelshein, “Online normalizer calculation for softmax”, 2018.
  • T. Dao, D. Y. Fu, S. Ermon, A. Rudra and C. Ré, “FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness”, NeurIPS 2022 (and FlashAttention-2/3).
  • B. F. Spector et al., “ThunderKittens: Simple, Fast, and Adorable AI Kernels”, 2024.

Preview of Lecture 10 — Hardware specialization

The GEMM ladder ended with a hint: a dedicated matrix unit on the same chip does the work 6.5× faster than all the general-purpose SIMD cores together. Lecture 10 asks why. Where does the energy of an instruction go? (Mostly not into the arithmetic.) How do specialized processors (DSPs, FPGAs, ASICs, GPU tensor cores, Google’s TPU with its systolic array) amortize that overhead? And what do you give up for a 100× gain in efficiency?


术语表 (Glossary, English → 中文)

English中文
deep neural network (DNN)深度神经网络
neuron / unit, weights, bias神经元 / 单元,权重,偏置
ReLU (rectified linear unit)修正线性单元
fully-connected layer全连接层
convolution layer / filter卷积层 / 滤波器(卷积核)
channel / feature map通道 / 特征图
pooling (max pool)池化(最大池化)
batch批次
GEMM (general matrix multiply)通用矩阵乘
im2col / explicit GEMM图像转列 / 显式 GEMM
implicit GEMM隐式 GEMM
materialize (an intermediate)物化(把中间结果存入内存)
loop interchange循环交换
blocking / tiling (cache, register)分块(缓存级、寄存器级)
micro-kernel / packing微内核 / 数据打包
register blocking寄存器分块
vendor library (cuBLAS, cuDNN, Accelerate)厂商库
domain-specific language (DSL)领域专用语言
operator fusion算子融合
softmax / online softmaxsoftmax / 在线 softmax
attention, query / key / value注意力,查询 / 键 / 值
FlashAttention闪电注意力(分块融合注意力)
on-chip memory (SRAM) / HBM片上存储 / 高带宽显存
double buffering双缓冲
low precision / quantization低精度 / 量化
depthwise / pointwise convolution逐通道卷积 / 逐点卷积
matrix unit (SME, AMX, tensor core)矩阵计算单元
← 返回课程目录