Phase 08 / Performance diagnosis
Reason with HLO and the roofline model
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 95 minutes · CPU practice
Locate matrix multiplication and activation in StableHLO. Derive the operation and minimum byte counts for a declared matrix contract.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Read an XProf trace
Hardware: CPU
Setup help: Python, notebook, or Cloud TPU VM
Use the tested CPU packages (the recorded environment uses Python 3.14.3). Other Python versions require separate checks. Hardware receipts apply only to their recorded source, environment, hardware, and cases; they do not qualify every lesson or TPU configuration. See the TPU performance and hardware evidence guide. The optional Cloud TPU specialization explains target-specific execution boundaries. Logical CPU devices practice partitioning; they do not simulate TPU performance.
Download the repository ZIP or use your existing checkout. Extract it and open a terminal in the folder containing requirements-cpu.txt. The beginner ZIP is separate; these lessons use the full repository folder.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txtpy -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txtAfter activation, run the complete worked example from that same folder:
python phases/08-performance/04-reason-with-hlo-and-the-roofline-model/code/main.py.\.venv\Scripts\python.exe phases/08-performance/04-reason-with-hlo-and-the-roofline-model/code/main.pyFor an incremental build, create main.py in your own practice folder, append each build block in order, and run python main.py with this environment active. Keep that file separate from the downloaded reference solution.
Download this lesson’s notebook. Open it with a Python kernel using the course environment. Run cells from the top after restarting the kernel; experiments depend on earlier definitions.
For local Jupyter, first install the course requirements using the Local Python steps, then use your environment’s Python to start Jupyter:
python -m pip install jupyterlab
python -m jupyter lab.\.venv\Scripts\python.exe -m pip install jupyterlab
.\.venv\Scripts\python.exe -m jupyter labSelect the downloaded performance-04.ipynb file in JupyterLab. The notebook contains reference solutions; make your prediction and attempt each practice task before opening them. Restart the kernel before changing logical device setup.
The worked reference for this lesson is CPU-validated. Some references explicitly configure logical CPU devices; setting JAX_PLATFORMS does not adapt them to a TPU. Follow the execution matrix and reviewed multi-host example before attempting a target run.
For accelerator preparation, study TPU setup, observed runtime receipts, checkpointed jobs and precision and retained traces. Current receipts cover bounded v5e1 launch, resume, and precision checks; four single-device Pallas cases; and a four-device v5e collective fixture. Each receipt is limited to its recorded source, environment, cases, and hardware. It does not qualify all lessons or TPU configurations. Cloud provisioning is optional for CPU learning.
Check: StableHLO contains the declared dot and activation. The matmul accounting is operations and minimum bytes; the hypothetical ceilings begin near , , then GFLOP/s. CPU times vary.
Revisit the guided CPU setup · Open 19: TPU Setup. Package instructions are CPU instructions; Windows and accelerator environments need their own validation.
What you will be able to do
- Locate matrix multiplication and activation in StableHLO.
- Derive the operation and minimum byte counts for a declared matrix contract.
- Identify the compute-versus-bandwidth transition in a hypothetical roofline.
- Explain why measured throughput can fall below either ceiling.
The problem
A matrix multiplication appears in your Python code, but what reaches the compiler and what might limit its speed? We will inspect a lowered program, calculate an explicit work/traffic model, and compare that model with synchronized CPU measurements without confusing a ceiling with a prediction.
The idea
A roofline compares arithmetic work with data movement under stated compute and bandwidth assumptions. It helps us predict which resource may constrain a workload. It is a model to test against measurements, not a hardware benchmark by itself.
Read a roofline as a conditional bound
A roofline turns two assumed budgets into a conditional ceiling. With 100 GB/s bandwidth and 1000 GFLOP/s compute, the curves meet at 10 FLOP/byte. At intensity 2 FLOP/byte, the bandwidth line gives 200 GFLOP/s, so the lower of the two budgets is the bound for this model.
This is a hypothetical calculation, not a performance result. Use it to predict whether more reuse could raise the modeled bound; verify any implementation change with compiler output and a synchronized measurement of the same workload.
Read the contract before the compiler text
The measured example multiplies by , yielding , then applies tanh. Lowering this specific input contract produces StableHLO containing dot_general and tanh in the recorded run. Read these operation meanings and tensor types before interpreting compiler cost fields; names and lowering details can vary by version and backend.
Count work with a stated convention
For dimensions , count one multiply and one addition per inner-product term: floating-point operations. For the declared matrix shapes, that gives 8192 matmul operations. The count omits tanh and uses a conventional two-operations-per-term accounting, so label its scope if you turn it into a throughput estimate.
Compiler estimates report a separate backend-specific view of work. Neither one is a measured device trace.
Minimum traffic is an assumption you can challenge
Assume each float32 input is read once and the output is written once. The matrix shapes then imply bytes and intensity operations per byte for matmul-only work.
This minimum omits tanh, intermediates, repeated reads, cache effects and layout changes. It is an accounting assumption that you can challenge with compiler estimates or traffic evidence, not a claim that exactly 3584 bytes moved.
Find the corner in a hypothetical roofline
The plotted roofline assumes 100 billion operations/s and 20 billion bytes/s, so the transition is at 5 operations/byte. Below that ridge, the bandwidth ceiling rises with intensity; above it, the combined ceiling stays at the compute cap. For the square-size cases, the first two plotted bounds are about 26.67 and 53.33 GFLOP/s; at intensity 5 the model reaches 100 GFLOP/s.
Use that slope change to predict the effect of doubling reuse in a bandwidth-limited case. It raises the modeled bound only until the compute ceiling; it does not guarantee a faster measured program.
Compare measurements only after checking equivalence
The executable is compared with an independent NumPy product and tanh, then warmed and timed with output synchronization. The recorded CPU samples vary substantially, which is expected to matter for this tiny workload; the calculation's hypothetical GFLOP/s ceilings are not measured CPU throughput.
For a real roofline, select budgets for the actual device and precision, name the memory level, and gather traffic evidence. Keep dtype, shape and operation equivalent when comparing measured results.
A hypothetical roofline bends at the compute budget
Predict before looking: Which square-matrix cases lie below the transition intensity?
Read the figure
The x-axis is minimum-traffic arithmetic intensity in operations per byte; the y-axis is a hypothetical ceiling in GFLOP/s. The bandwidth series rises as intensity times the assumed 20 GB/s, the compute series stays at 100 GFLOP/s, and the combined curve follows the lower series. These lines are model budgets, not device measurements. The first two cases give about 26.67 and 53.33 GFLOP/s; at the ridge of 5 operations/byte, the ceiling reaches 100.
Connect it to the computation
The plotted square cases use a simple one-read/one-write traffic estimate: larger matrices have higher modeled reuse, so their bandwidth ceiling rises until it meets the compute cap. The lesson's rectangular matmul separately has modeled intensity operations/byte under the same minimum-traffic convention; compare that location with the curve only as an estimate. Next predict whether doubling the modeled intensity would remain below the ridge, then measure an equivalent implementation before claiming improvement.
Figure data and execution details
Open full-size figureDownload data and provenance
The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.
Your build: Create a separate main.py in your practice folder. Append each block in order and run python main.py in the lesson environment. The downloaded script is the complete reference, so keep it separate from your attempt.
1 Inspect a specialized lowered computation
Create a Python file in the course environment. Add this block after the preceding block, then run the assembled file.
# Step 1 — Inspect a specialized lowered computation: StableHLO establishes the operation and shape contract.
import time
import numpy as np
import jax
import jax.numpy as jnpStableHLO establishes the operation and shape contract. Numerical equality is checked after compiling that same lowered program.
2 Calculate an explicitly hypothetical model
Create a Python file in the course environment. Add this block after the preceding block, then run the assembled file.
# Step 2 — Calculate an explicitly hypothetical model
def workload(a,b):return jnp.tanh(a@b)
a=jnp.arange(32*16,dtype=jnp.float32).reshape(32,16)/512
b=jnp.arange(16*8,dtype=jnp.float32).reshape(16,8)/128
# Wrap with `jax.jit` (`lowered`) so XLA traces and compiles the function.
lowered=jax.jit(workload).lower(a,b)
# Trace or lower the function to inspect its compiler representation (`stablehlo`).
stablehlo=str(lowered.compiler_ir(dialect='stablehlo'))
assert 'dot_general' in stablehlo and 'tanh' in stablehlo
# Trace or lower the function to inspect its compiler representation (`executable`).
executable=lowered.compile()
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_allclose(executable(a,b),np.tanh(np.asarray(a)@np.asarray(b)),rtol=2e-5,atol=2e-5)
print('StableHLO operations present: dot_general and tanh')
print('Compiler estimates (backend-specific):',executable.cost_analysis())The square-matrix simplification supplies an independent arithmetic check. The hardware budgets are illustrative constants.
Explain the APIs in this step
jnp.arange(n, dtype=...): Creates a 1-D JAX array of evenly spaced values[0, 1, ..., n-1]on the target device.array.reshape(new_shape): Reorganizes tensor axes without changing the total element count (array.size).jax.jit(fn) / @jax.jit: Traces a function for its input signatures and compiles it; changed shapes, dtypes, or static arguments can trigger another compilation.np.testing.assert_allclose(actual, desired, rtol=..., atol=...): Checks a host-side numerical expectation and raisesAssertionErrorwhen values differ beyond tolerance.
3 Keep runtime observations separate
Create a Python file in the course environment. Add this block after the preceding block, then run the assembled file.
# An analytic traffic model, not a measurement of this CPU.
def contract(m,k,n,itemsize=4):
if min(m,k,n,itemsize)<=0:raise ValueError('positive dimensions and itemsize required')
flops=2*m*k*n # conventional multiply-add count; excludes tanh
minimum_bytes=itemsize*(m*k+k*n+m*n)
return flops,minimum_bytes,flops/minimum_bytes
sizes=np.array([8,16,32,64,128])
intensity=np.array([contract(int(n),int(n),int(n))[2] for n in sizes])
np.testing.assert_allclose(intensity,sizes/6)
peak=100e9
bandwidth=20e9 # hypothetical budgets, not device specifications
memory_ceiling=bandwidth*intensity
roofline=np.minimum(peak,memory_ceiling)
np.testing.assert_allclose(roofline[:2]/1e9,[80/3,160/3])
assert np.all(roofline[2:]==peak)Warm samples measure the current CPU, while the work count remains a matmul-only convention. The code never asserts a speedup or hardware saturation.
Explain the APIs in this step
np.testing.assert_allclose(actual, desired, rtol=..., atol=...): Checks a host-side numerical expectation and raisesAssertionErrorwhen values differ beyond tolerance.
4 Keep runtime observations separate
Create a Python file in the course environment. Add this block after the preceding block, then run the assembled file.
# Step 4 — Keep runtime observations separate
executable(a,b).block_until_ready()
times=[]
for _ in range(5):
# Wait for device work to finish before timing it or comparing its result on the host.
# Wait for device work to finish before timing it or comparing its result on the host.
# Wait for device work to finish before timing it or comparing its result on the host.
start=time.perf_counter()
executable(a,b).block_until_ready()
times.append(time.perf_counter()-start)
flops,minimum_bytes,ai=contract(32,16,8)
print('Local CPU samples seconds:',times)
print('Matmul-only accounting:',{'flops':flops,'minimum_bytes':minimum_bytes,'flops_per_byte':ai})
print('Hypothetical ceilings GFLOP/s:',(roofline/1e9).tolist())Warm samples measure the current CPU, while the work count remains a matmul-only convention. The code never asserts a speedup or hardware saturation.
Explain the APIs in this step
output.block_until_ready(): Waits for asynchronous device work on this array to finish, which is needed before measuring completed computation time.
View the cumulative build in main.py
These blocks append in order to your separate practice file.
# Step 1 — Inspect a specialized lowered computation: StableHLO establishes the operation and shape contract.
import time
import numpy as np
import jax
import jax.numpy as jnp
# Step 2 — Calculate an explicitly hypothetical model
def workload(a,b):return jnp.tanh(a@b)
a=jnp.arange(32*16,dtype=jnp.float32).reshape(32,16)/512
b=jnp.arange(16*8,dtype=jnp.float32).reshape(16,8)/128
# Wrap with `jax.jit` (`lowered`) so XLA traces and compiles the function.
lowered=jax.jit(workload).lower(a,b)
# Trace or lower the function to inspect its compiler representation (`stablehlo`).
stablehlo=str(lowered.compiler_ir(dialect='stablehlo'))
assert 'dot_general' in stablehlo and 'tanh' in stablehlo
# Trace or lower the function to inspect its compiler representation (`executable`).
executable=lowered.compile()
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_allclose(executable(a,b),np.tanh(np.asarray(a)@np.asarray(b)),rtol=2e-5,atol=2e-5)
print('StableHLO operations present: dot_general and tanh')
print('Compiler estimates (backend-specific):',executable.cost_analysis())
# An analytic traffic model, not a measurement of this CPU.
def contract(m,k,n,itemsize=4):
if min(m,k,n,itemsize)<=0:raise ValueError('positive dimensions and itemsize required')
flops=2*m*k*n # conventional multiply-add count; excludes tanh
minimum_bytes=itemsize*(m*k+k*n+m*n)
return flops,minimum_bytes,flops/minimum_bytes
sizes=np.array([8,16,32,64,128])
intensity=np.array([contract(int(n),int(n),int(n))[2] for n in sizes])
np.testing.assert_allclose(intensity,sizes/6)
peak=100e9
bandwidth=20e9 # hypothetical budgets, not device specifications
memory_ceiling=bandwidth*intensity
roofline=np.minimum(peak,memory_ceiling)
np.testing.assert_allclose(roofline[:2]/1e9,[80/3,160/3])
assert np.all(roofline[2:]==peak)
# Step 4 — Keep runtime observations separate
executable(a,b).block_until_ready()
times=[]
for _ in range(5):
# Wait for device work to finish before timing it or comparing its result on the host.
# Wait for device work to finish before timing it or comparing its result on the host.
# Wait for device work to finish before timing it or comparing its result on the host.
start=time.perf_counter()
executable(a,b).block_until_ready()
times.append(time.perf_counter()-start)
flops,minimum_bytes,ai=contract(32,16,8)
print('Local CPU samples seconds:',times)
print('Matmul-only accounting:',{'flops':flops,'minimum_bytes':minimum_bytes,'flops_per_byte':ai})
print('Hypothetical ceilings GFLOP/s:',(roofline/1e9).tolist())Run the example
python3 phases/08-performance/04-reason-with-hlo-and-the-roofline-model/code/main.pyAbout this command
This shortcut uses an activated macOS/Linux course environment in the repository folder. For Windows, use the explicit interpreter command in “Setup help” above. The script includes worked examples and reference solutions.
Inspect the complete assembled example
# Step 1 — Inspect a specialized lowered computation: StableHLO establishes the operation and shape contract.
import time
import numpy as np
import jax
import jax.numpy as jnp
# Step 2 — Calculate an explicitly hypothetical model
def workload(a,b):return jnp.tanh(a@b)
a=jnp.arange(32*16,dtype=jnp.float32).reshape(32,16)/512
b=jnp.arange(16*8,dtype=jnp.float32).reshape(16,8)/128
# Wrap with `jax.jit` (`lowered`) so XLA traces and compiles the function.
lowered=jax.jit(workload).lower(a,b)
# Trace or lower the function to inspect its compiler representation (`stablehlo`).
stablehlo=str(lowered.compiler_ir(dialect='stablehlo'))
assert 'dot_general' in stablehlo and 'tanh' in stablehlo
# Trace or lower the function to inspect its compiler representation (`executable`).
executable=lowered.compile()
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_allclose(executable(a,b),np.tanh(np.asarray(a)@np.asarray(b)),rtol=2e-5,atol=2e-5)
print('StableHLO operations present: dot_general and tanh')
print('Compiler estimates (backend-specific):',executable.cost_analysis())
# An analytic traffic model, not a measurement of this CPU.
def contract(m,k,n,itemsize=4):
if min(m,k,n,itemsize)<=0:raise ValueError('positive dimensions and itemsize required')
flops=2*m*k*n # conventional multiply-add count; excludes tanh
minimum_bytes=itemsize*(m*k+k*n+m*n)
return flops,minimum_bytes,flops/minimum_bytes
sizes=np.array([8,16,32,64,128])
intensity=np.array([contract(int(n),int(n),int(n))[2] for n in sizes])
np.testing.assert_allclose(intensity,sizes/6)
peak=100e9
bandwidth=20e9 # hypothetical budgets, not device specifications
memory_ceiling=bandwidth*intensity
roofline=np.minimum(peak,memory_ceiling)
np.testing.assert_allclose(roofline[:2]/1e9,[80/3,160/3])
assert np.all(roofline[2:]==peak)
# Step 4 — Keep runtime observations separate
executable(a,b).block_until_ready()
times=[]
for _ in range(5):
# Wait for device work to finish before timing it or comparing its result on the host.
# Wait for device work to finish before timing it or comparing its result on the host.
# Wait for device work to finish before timing it or comparing its result on the host.
start=time.perf_counter()
executable(a,b).block_until_ready()
times.append(time.perf_counter()-start)
flops,minimum_bytes,ai=contract(32,16,8)
print('Local CPU samples seconds:',times)
print('Matmul-only accounting:',{'flops':flops,'minimum_bytes':minimum_bytes,'flops_per_byte':ai})
print('Hypothetical ceilings GFLOP/s:',(roofline/1e9).tolist())Expected result: StableHLO contains the declared dot and activation. The matmul accounting is operations and minimum bytes; the hypothetical ceilings begin near , , then GFLOP/s. CPU times vary.
Recorded output and runtime details
Reference output captured from executing the complete lesson script (code/main.py) and its assertions in the course CPU environment.
StableHLO operations present: dot_general and tanh
Compiler estimates (backend-specific): {'bytes accessed1{}': 512.0, 'bytes accessed': 5632.0, 'utilization0{}': 2.0, 'flops': 8192.0, 'bytes accessedout{}': 2048.0, 'utilization1{}': 1.0, 'transcendentals': 256.0, 'bytes accessed0{}': 3072.0}
Local CPU samples seconds: [5.924981087446213e-05, 5.21661713719368e-05, 5.2374787628650665e-05, 5.312496796250343e-05, 5.566701292991638e-05]
Matmul-only accounting: {'flops': 8192, 'minimum_bytes': 3584, 'flops_per_byte': 2.2857142857142856}
Hypothetical ceilings GFLOP/s: [26.666666666666664, 53.33333333333333, 100.0, 100.0, 100.0]
StableHLO operations present: dot_general and tanh
Compiler estimates (backend-specific): {'bytes accessed': 5632.0, 'bytes accessed0{}': 3072.0, 'flops': 8192.0, 'bytes accessed1{}': 512.0, 'utilization1{}': 1.0, 'utilization0{}': 2.0, 'bytes accessedout{}': 2048.0, 'transcendentals': 256.0}
Local CPU samples seconds: [5.029095336794853e-05, 8.283276110887527e-05, 4.158308729529381e-05, 3.808317705988884e-05, 7.008295506238937e-05]
Matmul-only accounting: {'flops': 8192, 'minimum_bytes': 3584, 'flops_per_byte': 2.2857142857142856}
Hypothetical ceilings GFLOP/s: [26.666666666666664, 53.33333333333333, 100.0, 100.0, 100.0]
Ceilings with twice minimum traffic GFLOP/s: [13.333333333333332, 26.666666666666664, 53.33333333333333, 100.0, 100.0]
Changed contract: 27648 8064 3.4285714285714284 bandwidth-limited in the hypothetical model
Arithmetic unchanged; modeled traffic halved and intensity doubled.
PASS: performance-04
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Double the assumed data movement
# Experiment — Double the assumed data movement: The work is unchanged; doubling transferred bytes halves intensity.
reduced=intensity/2
revised=np.minimum(peak,bandwidth*reduced)
np.testing.assert_allclose(revised[:2],roofline[:2]/2)
assert revised[-1]==peak
print('Ceilings with twice minimum traffic GFLOP/s:',(revised/1e9).tolist())Expected: The first bandwidth-limited ceilings halve; a sufficiently intense case stays compute-limited.
The work is unchanged; doubling transferred bytes halves intensity. This is a sensitivity calculation, not a measured cache miss rate.
Make it yours
Where to put your code: Modify your own main.py, or use the Make it yours cell in your downloaded notebook. Run your attempt in the declared environment and verify your prediction before opening the reference solution.
Derive the work and minimum traffic for shapes and . Compare your hand calculation with the contract function and report the hypothetical limiting budget.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- Matrix dimensions, element storage size, and a declared hardware budget.
Outputs
- FLOP count, minimum-byte estimate, arithmetic intensity, and hypothetical roofline ceiling.
Invariants to check
- State the storage and traffic assumptions; a bound is not observed throughput.
Hints
- Count multiply-add work and both input/output bytes independently.
- Change only itemsize to isolate its effect on the estimate.
import numpy as np
def roofline_contract(m, k, n, itemsize):
"""FLOP count, minimum-byte estimate, arithmetic intensity, and hypothetical roofline ceiling."""
# TODO: Count matrix FLOPs and minimum bytes from the declared dimensions and element size.
raise NotImplementedErrorReveal the reference solution
# Exercise solution: Derive the work and minimum traffic for shapes (48,24) and (24,12).
work,traffic,ratio=contract(48,24,12)
assert work==27648 and traffic==8064
np.testing.assert_allclose(ratio,24/7)
assert bandwidth*ratio<peak
print('Changed contract:',work,traffic,ratio,'bandwidth-limited in the hypothetical model')Keep the same shapes but change storage precision
Transfer
Change only the assumed element size from four bytes to two bytes. Calculate the resulting traffic and intensity, and explain why this is insufficient to predict an actual speedup.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Change only the assumed element size from four bytes to two bytes. Calculate the resulting traffic and intensity, and explain why this is insufficient to predict an actual speedup.
Outputs
- Changed byte estimate and intensity under the explicit storage assumption.
Invariants to check
- Only the bytes per element change; the operation count and shapes stay fixed.
Hints
- The model assumes both inputs and output use that element size; real accumulation and conversion may differ.
import numpy as np
def practice_keep_the_same_shapes_but_change_storage_precision(m, k, n, itemsize):
"""Implement the keep the same shapes but change storage precision check."""
# TODO: Recompute minimum traffic and arithmetic intensity with two-byte elements while holding dimensions fixed.
raise NotImplementedErrorShow a hint
The model assumes both inputs and output use that element size; real accumulation and conversion may differ.
Reveal reference solution and reasoning
# Keep the same shapes but change storage precision (Transfer)
f32,b32,i32=contract(32,16,8,4)
f16,b16,i16=contract(32,16,8,2)
assert f32==f16 and b32==2*b16
np.testing.assert_allclose(i16,2*i32)
print('Arithmetic unchanged; modeled traffic halved and intensity doubled.')Changing storage bytes in an accounting model is separate from native arithmetic support, accumulation policy, quality preservation or measured runtime improvement.
Diagnose the result
If a roofline claim looks implausible, check operation-count convention, byte units, element size, memory level and timing boundary. Inspect compiler estimates separately from measured traffic; neither should be silently relabeled as the other.
Carry forward
- Lowered text describes a specialized program, not a timeline.
- Arithmetic intensity depends on an explicit traffic model.
- A roofline is a ceiling under assumptions, not a promised runtime.
Keep your evidence
Keep StableHLO, synchronized CPU samples and independent output parity. Derive the byte/FLOP model and label the roofline peak and bandwidth as hypothetical.
Save your modified code, its output, and an explanation of your prediction. Checkpoint answers and exercise evidence are tracked separately.
Saved in this browser. Export or back up your portfolio anytime in My learning.
Reference execution: CPU validation only. This worked reference is validated on CPU. Accelerator compatibility requires a separate source review and target execution receipt. Use the execution matrix to review device selection and data ownership before adapting a separate target program. Execution matrix and target qualification.