Skip to main content

Hello, Roofline

Five lines of code to predict whether a model is memory-bound or compute-bound.

start
beginner
Learn to use MLSys·im’s analytical roofline model to predict ML model performance on any hardware. The foundation for all ML systems reasoning.

The Question

An engineer has a model and a GPU. Before writing any code, training anything, or renting any cloud instance, which hardware resource will be the bottleneck?

This tutorial teaches the single most important skill in ML systems: using the roofline model to answer that question in under a second.

NotePrerequisites

None. This is the starting point for all MLSys·im tutorials.

TipKey Terms for These Tutorials

Readers new to ML will meet the following terms throughout this tutorial series:

Term Meaning
Model A mathematical function with learned parameters (weights) that maps inputs to outputs (e.g., an image to a label)
Parameters The numbers a model learns during training. A “25M parameter” model stores 25 million numbers
Inference Running a trained model on new input to get a prediction (as opposed to training, which learns the parameters)
CNN Convolutional Neural Network, a model architecture for images (e.g., ResNet-50)
LLM Large Language Model, a model that generates text one token (roughly one word) at a time (e.g., GPT-4, Llama-3)
FP16 16-bit floating point (“half precision”), which uses 2 bytes per parameter. ML often uses reduced precision for speed
FLOP/s Floating-point operations per second, a measure of compute speed. TFLOP/s = trillion FLOP/s
HBM High Bandwidth Memory, the fast DRAM attached to a GPU (e.g., HBM2e on A100, HBM3 on H100)
Batch size How many inputs are processed together in one pass. Larger batches amortize the cost of loading weights

See the Glossary for a complete list of terms.

NoteLearning Objectives
  • Identify the performance bottleneck (memory-bound vs. compute-bound) for any model-hardware pair
  • Predict how batch size shifts the operating point along the roofline
  • Interpret the ridge point as the boundary between two performance regimes
  • Use Engine.solve as the foundational API for all MLSys·im analyses
TipBackground: The Roofline Model

The roofline model (Williams, Waterman, and Patterson, 2009) is the foundational analytical tool for predicting hardware bottlenecks. Every accelerator has two speed limits:

  1. Compute ceiling: how fast it can do arithmetic (measured in FLOP/s)
  2. Memory bandwidth ceiling: how fast it can load data from memory (measured in bytes/s)

The roofline model reduces to four lines of algebra:

\[T_{\text{compute}} = \frac{\text{FLOPs}}{\text{Peak FLOP/s}} \qquad T_{\text{memory}} = \frac{\text{Bytes}}{\text{Peak BW}}\]

\[T = \max(T_{\text{compute}},\; T_{\text{memory}})\]

\[\text{Ridge point} = \frac{\text{Peak FLOP/s}}{\text{Peak BW}} \quad [\text{FLOP/byte}]\]

A model’s arithmetic intensity (FLOPs ÷ Bytes) determines which ceiling it hits. Below the ridge point, the workload is memory-bound (starved for data). Above it, the workload is compute-bound (saturating the arithmetic units). This single classification drives every optimization decision downstream.

Caveat: The roofline is an upper bound. Real performance is always below it because of scheduling overhead, memory access patterns, and imperfect utilization. Achieving 40–60% of the roofline ceiling is considered good in practice. The model’s value lies not in predicting exact latency but in identifying the binding constraint (the resource that limits performance).

NoteConventions Used in These Tutorials
  • FLOP counting: Both the MLSys Zoo and vendor datasheets count one multiply-accumulate (MAC) as 2 FLOPs (one multiply plus one add). Some academic papers count 1 MAC = 1 FLOP, which halves both model FLOPs and hardware peak FLOP/s. Check which convention a paper uses before comparing raw numbers.
  • Peak vs. sustained specs: Passing efficiency=1.0 to Engine.solve evaluates the theoretical roofline ceiling using vendor-published peak Tensor Core throughput and peak HBM bandwidth. Real workloads typically sustain 40–70% of peak (Engine.solve defaults to efficiency=0.5 when efficiency is omitted).
  • Units: Q_ creates physical quantities with units (e.g., Q_("2 TB/s")). The ~ in format strings like :~.2f formats abbreviated unit symbols.

1. Setup

After pip install mlsysim, the import is two lines:

import mlsysim
from mlsysim import Engine

2. Pick a Model and a GPU

Pull vetted specifications from the MLSys Zoo instead of searching datasheets.

from mlsysim.show import table, info

model = mlsysim.Models.Vision.ResNet50
hardware = mlsysim.Hardware.Cloud.A100

info("Model",
     Name=f"{model.name} ({model.architecture})",
     Parameters=model.parameters,
     FLOPs_per_inf=model.inference_flops)

info("Hardware",
     Name=hardware.name,
     Peak_FP16=hardware.compute.peak_flops.to('TFLOPs/s'),
     HBM_BW=hardware.memory.bandwidth.to('TB/s'))
── Model ───────────────────────────────────
Name:           ResNet-50 (CNN)
Parameters:     25,557,032 param
FLOPs per inf:  8,200,000,000 flop
── Hardware ────────────────────────────────
Name:       NVIDIA A100
Peak FP16:  312 TFLOPs/s
HBM BW:     2.04 TB/s

In the Zoo, ResNet-50 has 25.6M parameters and 8.2 GFLOP per single-image forward pass, while the NVIDIA A100 provides 312 TFLOP/s of FP16 Tensor Core throughput, 2.04 TB/s (2039 GB/s) of HBM2e bandwidth, and 80 GiB of capacity.


3. Solve: One Line, One Answer

The Engine.solve method applies the roofline model. It calculates which of the two speed limits the workload hits first and returns latency, throughput, and the bottleneck classification.

# One line: model + hardware + config → theoretical roofline prediction
profile = Engine.solve(
    model=model,
    hardware=hardware,
    batch_size=1,          # Single image inference
    precision="fp16",      # Half-precision (16-bit floating point)
    efficiency=1.0         # Theoretical roofline ceiling
)

info(Bottleneck=profile.bottleneck,
     Arithmetic_Intensity=f"{profile.arithmetic_intensity.to('flop/byte'):~.1f}",
     Latency=profile.latency.to('ms'),
     Throughput=f"{profile.throughput.to('1/s').magnitude:.0f} images/sec")
Bottleneck:            Memory
Arithmetic Intensity:  84.5 flop / B
Latency:               0.063 ms
Throughput:            15983 images/sec

At batch size 1, ResNet-50 performs 8.2 GFLOP and transfers both model weights (51.1 MB at 2 bytes per parameter) and intermediate residual feature maps, yielding an arithmetic intensity of 84.5 FLOP/byte. Because 84.5 FLOP/byte sits well below the A100’s theoretical ridge point of 153.0 FLOP/byte, batch-1 inference is memory-bound.

Sanity check: Comparing the memory-transfer and compute bounds from the Background equations shows why memory traffic governs batch-1 latency:

  • \(T_{\text{memory (weights)}} = 51\.1\;\text{MB} \div 2\.04\;\text{TB/s} = 0\.025\;\text{ms}\)
  • \(T_{\text{compute}} = 8\.2\;\text{GFLOP} \div 312\;\text{TFLOP/s} = 0\.026\;\text{ms}\)
  • Including intermediate feature-map reads and writes raises total HBM transfer time to \(0\.048\;\text{ms} > T_{\text{compute}}\), and adding the GPU’s \(0\.015\;\text{ms}\) hardware dispatch overhead gives the reported \(0\.063\;\text{ms}\) latency.

ResNet-50 at batch 1 sits at roughly half the A100’s ridge point (84.5 vs. 153.0 FLOP/byte), so a modest increase in batch size (between batch 4 and batch 16) amortizes weight loads enough to cross into the compute-bound regime.

Computing arithmetic intensity from first principles: This ratio extends the analysis to any model, not only those in the Zoo. The formula is FLOPs ÷ Bytes. Compare two different workloads at batch size 1:

  • ResNet-50 (batch 1): 8.2 GFLOP across weights and feature maps = 84.5 FLOP/byte → moderately memory-bound on A100 (153.0 FLOP/byte ridge), crossing into compute-bound by batch 16
  • LLM decode (batch 1): Each token performs 2 FLOPs per parameter and loads 2 bytes per parameter = 1.0 FLOP/byte → deeply memory-bound (explored in Tutorial 2)

For an unfamiliar model, compute this ratio first. It reveals the regime before any code runs.


4. Sweep Batch Size: Watch the Regime Shift

Increasing the batch size shows when the bottleneck changes. More images per batch means more computation per weight load, which increases arithmetic intensity past the 153.0 FLOP/byte ridge point.

rows = []
for batch in [1, 4, 16, 32, 64, 128, 256]:
    p = Engine.solve(
        model=model,
        hardware=hardware,
        batch_size=batch,
        precision="fp16",
        efficiency=1.0
    )
    rows.append([
        batch,
        p.bottleneck,
        f"{p.arithmetic_intensity.to('flop/byte'):~.1f}",
        f"{p.throughput.to('1/s').magnitude:.0f}/s",
        p.latency.to('ms'),
    ])

table(["Batch", "Bottleneck", "Arithmetic Intensity", "Throughput", "Latency"], rows)
Batch  Bottleneck  Arithmetic Intensity  Throughput   Latency
─────────────────────────────────────────────────────────────
1          Memory         84.5 flop / B     15983/s  0.063 ms
4          Memory        139.8 flop / B     30755/s  0.130 ms
16        Compute        167.1 flop / B     36738/s  0.436 ms
32        Compute        172.7 flop / B     37382/s  0.856 ms
64        Compute        175.7 flop / B     37712/s   1.70 ms
128       Compute        177.2 flop / B     37880/s   3.38 ms
256       Compute        178.0 flop / B     37964/s   6.74 ms

The roofline plot below shows where batch-1 ResNet-50 sits relative to the ridge point (the crossover between memory-bound and compute-bound regimes).

from mlsysim.viz.plots import plot_roofline

# The plot_roofline function takes the hardware node and a list of workloads
fig, ax = plot_roofline(hardware, workloads=[model])

ImportantKey Insight

The roofline model predicts performance without running a single experiment. The answer is determined by two ratios: the workload’s arithmetic intensity and the hardware’s ridge point. Batch size is the primary knob that moves a workload along the roofline. At small batches the workload is memory-bound, and at large batches it is compute-bound. The ridge point is the most efficient operating point. Every optimization decision starts with knowing which side of the ridge the workload is on.

WarningPitfall: Assuming Peak FLOP/s Determines Inference Speed

A common mistake is selecting hardware based on peak FLOP/s alone. LLM decode at batch size 1 performs about 1 FLOP per byte loaded, so it is deeply memory-bound, and the 312 TFLOP/s compute ceiling is irrelevant. A GPU with half the FLOP/s but the same bandwidth would deliver identical decode latency. Always check the regime before comparing specs.


Where This Clicks in the Textbook

Vol I · Ch 11Foundation

Derives the Roofline model, arithmetic intensity, and ridge points from systolic-array and HBM physics.

Vol I · Ch 5Workload Math

Counts layer FLOPs, parameter bytes, and intermediate feature-map traffic that set arithmetic intensity.

Vol I · Ch 12Measurement

Shows how to validate analytical Roofline bounds against hardware counters without measurement traps.

Next Steps

Back to top