Count the operations before timing the matrix
Benchmark one matmul shape on CPU and GPU, compute its FLOPs by hand, and see why a tiny kernel launch can hide the hardware.
A matrix multiplication of shape (m, n, k) performs 2 * m * n * k
floating-point operations, counting one multiply and one add as two. That count
is fixed by the problem. The time is not: it depends on the device, the layout,
the precision and the launch overhead. A performance number without the shape and
the operation count is not interpretable.
This example benchmarks one small shape across NumPy on CPU, PyTorch on CPU, and
PyTorch on CUDA when a GPU is present. On this machine the GPU result was not
faster, because 64 x 128 x 256 is only about 4.2 million FLOPs and the kernel
launch dominates. That is the lesson, not a GPU ranking. The example also shows
the warm-up and synchronisation that a timing claim needs.
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch07/matmul_bench.py --shapes 64,128,256 --jsonPython 3.11 or later with NumPy and PyTorch. The CPU rows run anywhere; the CUDA
row is optional and appears only when torch.cuda.is_available() is true. No
model download, network or credentials are required. It finishes immediately.
Implementation
The GPU timing synchronises before and after the call, warms up three times, and takes the minimum of five iterations. The FLOPs helper uses the exact shape, not a guessed peak. A benchmark that omits any of those choices is measuring something else.
def gflops_for_matmul(m: int, n: int, k: int, seconds: float) -> float:
if seconds <= 0:
return 0.0
flops = 2.0 * m * n * k
return flops / (seconds * 1e9)
def benchmark_torch(shape: List[int], device: str, warmup: int = 3, iterations: int = 5) -> BenchmarkResult:
m, n, k = shape
a = torch.randn(m, k, device=device)
b = torch.randn(k, n, device=device)
for _ in range(warmup):
_ = torch.matmul(a, b)
if device.startswith("cuda"):
torch.cuda.synchronize()
times = []
for _ in range(iterations):
if device.startswith("cuda"):
torch.cuda.synchronize()
start = time.perf_counter()
c = torch.matmul(a, b)
if device.startswith("cuda"):
torch.cuda.synchronize()
times.append(time.perf_counter() - start)
seconds = min(times)
return BenchmarkResult(
shape=shape,
backend="torch",
device=device,
seconds=seconds,
gflops=gflops_for_matmul(m, n, k, seconds),
metadata={"warmup": warmup, "iterations": iterations},
)Expected outcome
Observed in one run of the command above (exit 0), with a CUDA device present. These are single-run minima, not stable performance claims:
| Backend | Device | Shape (m, n, k) |
Time (s) | Reported GFLOP/s |
|---|---|---|---|---|
| NumPy | CPU | 64, 128, 256 | 0.0000398 | 105.38 |
| PyTorch | CPU | 64, 128, 256 | 0.0000293 | 143.15 |
| PyTorch | CUDA | 64, 128, 256 | 0.0000320 | 131.07 |
The hand calculation is 2 * 64 * 128 * 256 = 4,194,304 FLOPs. Dividing by
3.2e-5 s gives about 131 GFLOP/s, matching the CUDA row. The GPU was slower
than the CPU row here because the problem is too small to amortise launch
overhead and because these are different implementations, not a controlled
comparison of devices.
Mechanism and limitations
Documented: run benchmarks NumPy on CPU, PyTorch on CPU, and PyTorch on
CUDA only when available. benchmark_torch warms up, synchronises CUDA around
the timed region, and takes the minimum of five iterations. benchmark_numpy
uses float32 arrays and the same warm-up and iteration counts. The tests check
both backends run, the FLOPs helper is positive, JSON serialisation, and that a
small PyTorch matmul agrees with NumPy.
Observed: the command exited 0 and produced the three rows above. The
targeted tests.test_ch07_matmul is part of the canonical suite; no independent
test count is claimed here.
Not shown: a GPU’s peak throughput, a large-shape crossover, memory bandwidth, precision effects, or a comparison with cuBLAS. A single small shape cannot rank hardware. The GPU row is optional and will be absent on a CPU-only machine, so the page’s default teaching path is the CPU rows and the arithmetic.
Challenge this result
Run --shapes 512,512,512 and --shapes 4096,4096,4096. Compute the FLOPs for
each before running. Predict the shape at which the CUDA row overtakes the CPU
row, then compare. If the GPU is still slower at 512, check whether the timing
includes a synchronisation that the CPU path does not need. Explain why “the GPU
is faster” is not a testable statement without a shape and a measurement point.
Source and verification
Canonical source:
examples/ch07/matmul_bench.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch07_matmul.py
.
Chapter: Matrix Multiplication and GPU Execution
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15,
NumPy and PyTorch 2.6.0+cu124; it is not a portable hardware benchmark.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.