Pidoku

The Roofline Model in Practice

Module 22 Lesson 22.b 1h Difficulty 3/5

Prerequisites 2.f, 6.a, 12.f

2.f and 6.a teach the roofline and how to place one kernel on it. This lesson uses it on a whole inference step: compute the step’s physical floor, compare it with what you measure, and let the gap tell you where to work.


Before you start: words you need#

WordPlain meaning
RooflineA chart of the best speed a chip can reach for a given ratio of arithmetic to memory traffic (6.a).
Arithmetic intensity (I)FLOPs done per byte moved from memory. Low means memory-bound; high means compute-bound.
Ridge pointThe intensity where the two limits meet: peak FLOP/s ÷ peak bandwidth. About 295 FLOP/byte on an H100 in BF16.
Floor (speed of light)The shortest time a piece of work could possibly take on this chip: the larger of FLOPs ÷ peak FLOP/s and bytes ÷ peak bandwidth.
% of roofFloor ÷ measured time. 90% means only 10% is left to gain without changing the work itself.
Kernel groupAll kernels of one kind in a step added together, for example every layer’s down_proj matrix multiply.
GEMMGeneral matrix multiply; in decode, the weight matrix times a small batch of vectors (11.c).

1. What is it?#

A table with one row per kind of work in an inference step:

kernel group | FLOPs | bytes | intensity | floor time | measured time | % of roof

and one last row for the whole step. It is the most useful single artifact you can produce about an inference system, because it answers three questions at once:

  • How close to the physics are we? The whole-step row.
  • Where is the remaining gap? The rows with low % of roof.
  • What kind of fix can close it? The intensity column says whether a row is memory- or compute-bound, and so which fixes can help (22.c).

2. Why does it matter?#

Because without a floor, a measured number means nothing. “Decode takes 9.5 ms” could be excellent or terrible. “Decode takes 9.5 ms and the floor is 7.1 ms” says you are at 75% of the physics, the remaining 25% is worth looking at, and no software change will ever get below 7.1 ms without reading fewer bytes.

It also stops a common waste: optimising a kernel that is already at its roof. A kernel at 88% of the memory roof has at most 12% left to give, however clever the tuning.


3. Simple analogy#

A delivery route with a speed limit. The floor is distance ÷ speed limit: the fastest the van can legally do the route. If the driver takes 75 minutes on a route whose floor is 71, there is little to gain from a better driver; to go faster you need a shorter route (fewer bytes) or a higher limit (more bandwidth). If the driver takes 150 minutes, something is wrong (wrong turns, long stops) and the driver is worth watching.

The per-row view is the same thing per street: most streets are driven near the limit, and one street with a traffic light every ten metres (many tiny kernels) is where the time goes.


4. Tiny example: the floor of one decode step#

Llama-3.1-8B, BF16, batch 32, 2,048 tokens of context per sequence, one H100 SXM (989 TFLOP/s dense BF16, 3.35 TB/s):

Weights read per step:   ~7.5 B parameters × 2 bytes   = 15.0 GB
KV cache read per step:  32 seqs × 2,048 tokens × 128 KiB per token (12.f) = 8.6 GB
Total bytes:             ~23.8 GB
Floor:                   23.8 GB ÷ 3.35 TB/s           = 7.1 ms per step
                         32 tokens per step            → at most ~4,500 tok/s

Intensity of the weight GEMMs is 2 FLOPs × 32 sequences ÷ 2 bytes = 32 FLOP/byte, far below the ridge point of 295, so this step is memory-bound and the bytes term sets the floor. If you measure 9.5 ms per step, you are at 75% of the roof.


5. Technical explanation#

Building the table#

For each kernel group you need FLOPs, bytes and measured time.

  • FLOPs and bytes from the model. For a weight GEMM in decode: FLOPs = 2 × parameters × batch, bytes ≈ parameters × bytes per weight. For attention: bytes = the KV cache read (12.f), FLOPs = 4 × context × heads × head dimension per sequence per layer. This is fast and needs no tools.
  • FLOPs and bytes from the profiler. Nsight Compute measures what the implementation actually did, including extra traffic from poor reuse. ncu --set roofline collects the counters and draws the chart; 6.a and 6.d show how to read it. Use this for the kernels where your calculation and the measured time disagree.
  • Measured time from a timeline. Nsight Systems (22.h) gives total time per kernel name over a few steps. Divide by the number of steps.

Sum each column over all kernels of a group. The whole-step row adds the floors of all rows; it is not the floor of the summed FLOPs and bytes, because different rows can be limited by different resources.

Reading the rows#

ROW                                   DIAGNOSIS                     WHAT HELPS
low I, 80–95% of roof                 memory-bound, done            read fewer bytes: quantize
                                                                    weights (13.b) or KV (13.h),
                                                                    batch more
low I, below ~60% of roof             memory-bound, inefficient     the kernel: access pattern,
                                                                    vector loads, split-K, more
                                                                    blocks in flight (6.b, 6.c)
high I, 70–90% of roof                compute-bound, done           fewer FLOPs, lower precision
                                                                    (FP8 / FP4 tensor cores)
high I, well below roof               compute-bound, inefficient    tensor cores actually used?
                                                                    tiling, wave quantization
tiny bytes, far below roof            latency- or launch-bound      fusion (13.j), CUDA graphs
                                                                    (13.k)

The middle column matters most: the same regime can be “done” or “inefficient”. A memory-bound kernel at 88% of its roof is finished; one at 35% has a fixable problem.

What realistic “done” looks like#

No kernel reaches 100% of the datasheet. Large streaming reads on H100 and B200 typically reach 80–92% of the quoted HBM bandwidth; dense GEMMs typically reach 70–85% of the quoted tensor throughput. Measure your own ceiling once with a plain copy kernel or nvbandwidth, and use that as the roof if you want “% of achievable” rather than “% of datasheet”. Say which you used.


6. Under the hood: the table as a program#

The program builds the table for the example in section 4. The FLOPs and bytes are computed from the model’s shapes. The “measured” column is an illustrative set of timeline numbers, typical of a reasonably tuned engine; replace it with your own.

Go
// steproof.go: the speed-of-light table for one decode step, and how far
// each group of kernels sits from it.
//
// Model: Llama-3.1-8B shapes, BF16 weights and KV cache.
// Hardware: H100 SXM, 989 TFLOP/s dense BF16, 3.35 TB/s HBM.
package main

import "fmt"

const (
	peakFLOPs = 989e12  // FLOP/s
	peakBW    = 3.35e12 // bytes/s
	bytesPer  = 2.0     // BF16

	layers, hidden, heads, kvHeads, headDim = 32, 4096, 32, 8, 128
	ffn, vocab                              = 14336, 128256
	batch, ctx                              = 32, 2048
)

type op struct {
	name       string
	flops      float64
	bytes      float64
	measuredUS float64 // illustrative timeline numbers, microseconds
}

func gemm(name string, in, out, nLayers int, measuredUS float64) op {
	params := float64(in) * float64(out) * float64(nLayers)
	return op{name, 2 * params * batch, params * bytesPer, measuredUS}
}

func main() {
	kv := float64(kvHeads * headDim)
	attnBytes := 2 * ctx * kv * bytesPer * layers * batch                // read K and V
	attnFLOPs := 2 * 2 * float64(ctx) * heads * headDim * layers * batch // QK^T and PV
	smallBytes := 10.0 * batch * hidden * bytesPer * layers              // norms, residuals, RoPE...

	ops := []op{
		gemm("qkv_proj", hidden, hidden+2*int(kv), layers, 560),
		gemm("o_proj", hidden, hidden, layers, 380),
		gemm("gate_up_proj", hidden, 2*ffn, layers, 2560),
		gemm("down_proj", ffn, hidden, layers, 1290),
		gemm("lm_head", hidden, vocab, 1, 370),
		{"attention (KV read)", attnFLOPs, attnBytes, 3700},
		{"norms+act+rope (~160 kernels)", 4 * smallBytes, 2 * smallBytes, 640},
	}

	fmt.Printf("ridge point = %.0f FLOP/byte\n\n", peakFLOPs/peakBW)
	fmt.Printf("%-30s %8s %8s %6s %9s %9s %7s\n",
		"kernel group", "GFLOP", "GB", "I", "floor us", "meas us", "of roof")
	var tf, tb, tfloor, tmeas float64
	for _, o := range ops {
		floor := 1e6 * max(o.flops/peakFLOPs, o.bytes/peakBW)
		fmt.Printf("%-30s %8.1f %8.2f %6.1f %9.0f %9.0f %6.0f%%\n",
			o.name, o.flops/1e9, o.bytes/1e9, o.flops/o.bytes, floor, o.measuredUS, 100*floor/o.measuredUS)
		tf, tb, tfloor, tmeas = tf+o.flops, tb+o.bytes, tfloor+floor, tmeas+o.measuredUS
	}
	fmt.Printf("%-30s %8.1f %8.2f %6.1f %9.0f %9.0f %6.0f%%\n",
		"WHOLE STEP", tf/1e9, tb/1e9, tf/tb, tfloor, tmeas, 100*tfloor/tmeas)
	fmt.Printf("\nfloor: %.2f ms/step -> %.0f tok/s at batch %d\n", tfloor/1e3, batch*1e6/tfloor, batch)
	fmt.Printf("meas:  %.2f ms/step -> %.0f tok/s at batch %d\n", tmeas/1e3, batch*1e6/tmeas, batch)
}

Output:

ridge point = 295 FLOP/byte

kernel group                      GFLOP       GB      I  floor us   meas us of roof
qkv_proj                           51.5     1.61   32.0       481       560     86%
o_proj                             34.4     1.07   32.0       321       380     84%
gate_up_proj                      240.5     7.52   32.0      2244      2560     88%
down_proj                         120.3     3.76   32.0      1122      1290     87%
lm_head                            33.6     1.05   32.0       314       370     85%
attention (KV read)                34.4     8.59    4.0      2564      3700     69%
norms+act+rope (~160 kernels)       0.3     0.17    2.0        50       640      8%
WHOLE STEP                        515.0    23.77   21.7      7095      9500     75%

floor: 7.09 ms/step -> 4510 tok/s at batch 32
meas:  9.50 ms/step -> 3368 tok/s at batch 32

How to read it:

  • The GEMMs are done. At 84–88% of the memory roof, no tuning will gain more than a few percent. The only lever is fewer bytes: FP8 weights halve their 15 GB.
  • Attention is the biggest gap. 1.1 ms of the 2.4 ms total gap. At 2,048 tokens of context the KV cache is already 8.6 GB, more than half the weights; at longer contexts it dominates. Look at the attention backend (18.c) and KV quantization (13.h).
  • The small kernels are 8% of roof. Their bytes are trivial, but 160 launches of a few microseconds each add up to 0.6 ms. This is a launch and latency problem, not a bandwidth one: fusion (13.j) and CUDA graphs (13.k) fix it, quantization does not.
  • The whole step is at 75%. A decent engine. A whole step below about 50% means something structural is wrong (22.c, 22.k case 3).

7. Performance implications#

  • Batch moves rows along the intensity axis. Weight GEMM intensity is about the batch size in BF16 (2 FLOPs × batch ÷ 2 bytes). At batch 32 it is 32; near batch 300 it reaches the H100 ridge and the GEMMs turn compute-bound (22.c).
  • Attention does not move with batch. Each sequence reads its own KV cache, so its intensity stays near the number of query heads per KV head (4 here with GQA, 12.g). Batching amortises weights, never KV.
  • Context length moves the balance. Double the context and the attention row doubles while the GEMM rows stay put.
  • Precision moves both axes. FP8 weights halve GEMM bytes and double intensity; FP8 tensor cores double the compute roof.
  • The hierarchical roofline (6.a) matters when a kernel seems to beat the HBM roof: it is being fed from L2 or shared memory, and that level’s roof applies. Check with Nsight Compute’s DRAM, L2 and L1 byte counters.

8. Production implications#

  • Build the table once per model and GPU type and keep it with the deployment. Rebuild it when the batch size or context length you run at changes a lot.
  • Track the whole-step % of roof as a regression metric. A drop from 75% to 50% after an upgrade means a kernel fell back, a graph capture failed, or a layout broke.
  • Use it to reject proposals. “This cuts FLOPs by 40%” is worth nothing for a row at the memory roof. Say so with the table.
  • Use it in procurement. “Our decode GEMMs are at 87% of the HBM roof” is the quantitative form of “software is exhausted; the next step is more bandwidth (H200, B200, Rubin) or fewer bytes”. “We are at 35%” means do not buy hardware yet.
  • State the roof you used: datasheet or measured, dense or sparse.

9. Common mistakes#

  1. Using peak FLOPs that include 2:4 sparsity. It doubles the roof and halves your apparent efficiency. Use dense numbers.
  2. Summing FLOPs and bytes for the whole model and plotting one point. A step contains rows in different regimes; one point hides all of them.
  3. Computing intensity from the algorithm instead of the implementation. Unfused chains move the same tensor through memory several times.
  4. Forgetting the KV cache. At long context it is most of the bytes.
  5. Forgetting writes. Bytes = reads + writes. Small for GEMMs, large for elementwise kernels.
  6. Treating 100% as the goal. 85–90% of a memory roof is done.
  7. Using the roofline before step 3 of 22.a. If the GPU is idle half the time, kernel positions are irrelevant.

10. Hands-on exercise#

  1. Run steproof.go. Change ctx to 8192 and then 32768. At what context does attention become more than half the floor?
  2. Set bytesPer to 1 for the weights only (FP8 weights, BF16 KV). You will need a second constant. How much does the floor drop? Why less than half?
  3. Change batch to 256. Which rows are now compute-bound (intensity above 295)? Does the max(...) in the floor pick the compute term?
  4. Replace the measured column with real numbers: profile a decode step of your engine with Nsight Systems (22.h), sum time per kernel name, and divide by the number of steps.
  5. For the row with the lowest % of roof that is not the small-kernel row, run ncu --set roofline on one instance of that kernel. Does the profiler’s byte count match your calculation?

11. Interview questions#

  1. How do you compute the physical floor of one decode step? What dominates it at short and at long context?
  2. A GEMM is at 88% of the memory roof. What can still make it faster?
  3. A group of kernels is at 8% of roof but moves almost no bytes. What is wrong, and what fixes it?
  4. Why does batching raise the intensity of weight GEMMs but not of attention?
  5. Why should the whole-step floor be the sum of per-row floors rather than one calculation on the summed FLOPs and bytes?
  6. How would you use this table in a hardware purchase discussion?

12. Further reading#

Checked on 12 November 2026.

  • S. Williams, A. Waterman, D. Patterson, “Roofline: An Insightful Visual Performance Model for Multicore Architectures”, Communications of the ACM 52(4), 2009.
  • Nsight Compute Profiling Guide: the roofline sections and hierarchical roofline charts.
  • NVIDIA nvbandwidth: measure the bandwidth your GPU actually reaches.
  • Lessons 6.a (the roofline on one kernel), 12.f (KV bytes per token), 22.c (what the regime means for fixes).

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in