On this page
A GPU is a graphics processor, the chip that runs most AI models. Many steps are tiny: add a fixed offset (a bias) to every number in a table, set the negative numbers to zero (ReLU, an activation), multiply every number by a constant (a scale). On a table of 16.8 million numbers, this lesson’s model of an NVIDIA A100 GPU takes 98.7 microseconds to run these as three steps and 32.9 to run them as one. The saving is not in the calculating. Each separate step carries the whole table out of the GPU’s main memory and back.
In one minute
Kernel fusion makes a model faster by running several small GPU steps (each a kernel, a program run on the GPU) as one, so their table makes one round trip to memory instead of one per step. Picture a clerk who must stamp three marks on each of 16 million forms in a basement archive, with a desk upstairs. One mark at a time means carrying the whole pile up and back three times; stamping all three marks on each batch at the desk means the pile goes up and down once. The stairs take the day and the stamping takes seconds, and a GPU step that adds, zeroes or multiplies does about one calculation per number, so memory trips set its time. Fusion pays little for a step busy calculating, such as multiplying two huge tables (a matrix multiplication).
Explore the numbers
Open the widget and drag the slider from 1 step to 8. Each orange block is one trip between memory and the chip (R read, W write). The “× faster (predicted)” line equals the number of steps. Then tick “A big matrix multiplication comes first”: the gain at 3 steps falls to 1.22×, as the multiplication’s 440.5 µs stays.
How it works
These numbers come from a byte-counting model of one NVIDIA A100 GPU (the 80 GB SXM card, memory speed 2,039 GB/s) and a 4096 by 4096 table, with figures from the data sheet. It predicts; it does not measure. As in the roofline lesson, a chip takes the longer of its time to calculate and its time to move bytes. To fuse steps is to write them as one kernel.
The picture, step by step
A table of 4096 by 4096 numbers, 2 bytes each, waits in the GPU’s main memory. Three steps must change every number: add a bias, set the negatives to zero (ReLU), and scale. Figure 1 shows the trips.
Figure 1. Three steps alone make six trips between memory and the chip; fused, two.
- Size one trip. The table holds 16,777,216 numbers of 2 bytes, so one trip, all of it one way, is 33,554,432 bytes.
- Run each step alone. A step reads the whole table and writes it all back: two trips.
- Count the trips. Three steps alone make 6 trips, 201,326,592 bytes. Fused, they make 2 trips, 67,108,864 bytes. The ratio is 3, an upper bound: the model charges every trip to main memory, but the A100’s 40 MB on-chip cache can serve some repeat trips of a 33.6 MB table, so real gains are smaller.
- Turn bytes into time. Each step does one calculation per number, 0.25 per byte moved. The ordinary circuits peak at 19.5 trillion calculations a second in 32-bit floating point (FP32), counting a multiply-and-add instruction as two. A plain add, multiply or max is one, so these steps get half, 9.75 trillion, and PyTorch normally does 16-bit math in FP32. Against 2,039 GB/s of memory the ridge is 4.8 calculations per byte, where calculating and moving take equal time. 0.25 is well below it, so time is bytes over memory speed: 98.7 µs alone, 32.9 µs fused.
- Fuse by pieces. The fused kernel takes one piece, runs all three steps on it in the chip’s fast memory, and writes it back once.
- Add a big matrix multiplication. It runs on the tensor cores, circuits built for matrix multiplication, at 312 trillion calculations a second, and a 4096 by 4096 one takes 440.5 µs, set by its calculating. Fusing the steps into its output (the code calls this the epilogue) removes their 98.7 µs, their calculating overlapping the multiplication’s: 539.2 µs falls to 440.5 µs.
Each step in code
One real line does each step. The code calls a trip a “pass”.
| Step | The code line | What it does |
|---|---|---|
| 1. Size one trip | kernel_fusion.py:44return elems * elem_bytes |
One trip is every number in the table times its size in bytes. |
| 2. Run each step alone | kernel_fusion.py:134t.loads += x.size |
The one-at-a-time run counts the whole table as read for every step. Line 136 counts the whole table as written. |
| 3. Count the trips | kernel_fusion.py:49return (2 if fused else 2 * steps) * pass_bytes(elems, elem_bytes) |
Fused is 2 trips. One at a time is 2 trips for each step. |
| 4. Turn bytes into time | kernel_fusion.py:63return max(flops / peak_flops, nbytes / bandwidth) |
A kernel takes the longer of its calculating time and its moving time. chain_time passes it the steps’ rate, 9.75 trillion. |
| 5. Fuse by pieces | kernel_fusion.py:145OPS[op](blk, v) |
Inside the loop over pieces, every step runs on the same piece before the next piece is taken. |
| 6. Add a big matrix multiplication | kernel_fusion.py:108return matmul_time() + (0.0 if fused else chain_time(steps, False)) |
The matrix multiplication’s time is always paid. Only the one-at-a-time run adds the steps’ time on top. |
A real run
Run it from the repository root:
cd lessons/why-running-gpu-steps-together-is-faster/code && python3 kernel_fusion.py
Phone readers: slide the box sideways to see every column.
table: 4096 x 4096 = 16,777,216 numbers of 2 bytes; one pass = 33,554,432 bytes
A100 ridge (FLOP/byte): 4.8 for the add, ReLU and scale steps, 153.0 for the tensor-core multiply
3 steps unfused: 6 passes, 201,326,592 bytes, 98.7 us, intensity 0.250 FLOP/byte
3 steps fused: 2 passes, 67,108,864 bytes, 32.9 us, intensity 0.750 FLOP/byte
byte ratio 3.0x, time ratio 3.0x
one-FLOP steps needed for the fused kernel to reach the ridge: 20
matmul 4096^3: 137.4 GFLOP, calculation floor 440.5 us, memory floor 49.4 us, time 440.5 us, intensity 1,365.3 FLOP/byte
matmul then 3 steps: unfused 539.2 us, fused into the epilogue 440.5 us, 1.22x, 18.3% saved
In the output, us is microseconds and a FLOP is one calculation.
- Steps 1 to 4. Intensity, calculations per byte, is 0.250 alone and 0.750 fused, below the ridge of 4.8, so the time ratio equals the byte ratio, 3.0.
- The crossover. Fused, k steps have intensity k / 4, which reaches the ridge, 4.8, at 20 steps; 19 still wait on memory. A real chain of 3 to 8 steps is well short of it.
- Step 6. The multiplication’s calculating floor is 440.5 µs, its memory floor 49.4 µs. With the steps: 539.2 µs alone, 440.5 µs fused, 1.22 times faster, 18.3% saved.
Hands on
Your turn
Predict, then run, from the code/ folder:
python3 -c "import kernel_fusion as kf; print(f'{kf.chain_time(6, False) * 1e6:.1f} {kf.chain_time(6, True) * 1e6:.1f}')"
Count the trips for 6 steps alone and fused, and write both times in microseconds. Which changed from the 3-step run?
Expected output
197.5 32.9
Six steps alone make 12 trips, so the time doubles from 98.7 µs to 197.5 µs. Fused, the table still makes 2 trips, so the time stays 32.9 µs and the gain is 6.0 times. That holds up to 19 steps; real chains are far shorter.
What this means when you build
- Count the trips before you tune. A step with about one calculation per number costs two trips of the table: k such steps cost 2k trips alone and 2 fused, so expect up to k times faster. Measure; real runs fall short.
- Fusion pays little for a big matrix multiplication. Calculating limits it, so fusing the small steps that follow into its output saves only their trips, 18.3% in this model. The roofline lesson shows how to check which limit a step hits.
- Let a compiler do it first.
torch.compile, in the PyTorch library for AI models, finds such chains, and its code writer, TorchInductor, makes fused kernels, for example in Triton, a language for GPU kernels. Write one by hand only when a profile (a measured breakdown of time) shows a chain still limited by memory trips that the compiler left alone. - Do not mix up fusion and CUDA graphs. A CUDA graph replays many GPU launches as one, saving the time the main processor spends starting each kernel. The kernels stay separate and make the same trips. Graphs fix launch overhead; fusion fixes memory trips.
- Budget for the cost. A fused kernel is custom code for one pattern and hides the in-between values. Go deeper covers two more costs.
Optionalabout 20 min
Go deeper
Optional. For readers who write Python and are comfortable with a little algebra. Numbers are 2-byte floating-point values (FP16) on the 80 GB SXM A100 card unless stated; the 40 GB cards list a memory speed of 1,555 GB/s and the 80 GB PCIe card 1,935, not 2,039. Every number below that cites no source is printed by python3 kernel_fusion.py in code/ or computed from what it prints; the CPU timings need --time.
Before you start
- Matrix multiplication: MIT OpenCourseWare 18.06SC, multiplication and inverse matrices.
- Reading Python and NumPy: NumPy: the absolute basics for beginners.
The naive approach and why it fails
Run the steps in order, each over the whole table. This is how a model written as a list of separate operations runs by default.
def run_unfused(x: np.ndarray, steps: list[Step], t: Traffic) -> None:
"""Each step sweeps the whole array: read all of it, write all of it, before the next step starts. Works in place."""
for op, v in steps:
t.loads += x.size
OPS[op](x, v)
t.stores += x.size
The result is right, and the cost is in the loop. Every step reads all x.size numbers and writes them all, so k steps move 2k tables. Each step’s own work is tiny: the A100 can calculate far faster than memory can feed it, as the roofline lesson shows. Faster calculators would not help, because they already wait. Moving fewer bytes, or having more memory bandwidth, would.
The idea: do all the steps on a piece
An elementwise step makes each output number from the one input number in the same place, so a piece of the table can go through every step without any other piece. Figure 2 shows it: read a piece once, run all the steps on the chip, write it once. In practice the chip’s many cores each take different pieces and work at the same time; the trip count does not change.
Figure 2. A fused kernel takes one piece, runs every step on it while it sits on the chip, and writes it back once. Many cores do this at once.
The roofline explains the gain. Fused, a number moves 2 bytes in and 2 bytes out, 4 bytes, and takes part in k calculations, so the intensity is k/4 calculations per byte. Unfused, each step moves 4 bytes for 1 calculation, so it is 1/4 however many steps there are. Fusion multiplies the intensity by k, which slides the job to the right on Figure 3, from A at 0.25 to B at 0.75.
Figure 3. Fusion moves a job right on the roofline. Three steps go from A to B and stay left of the dashed ridge. The matrix multiplication, C, is already on the flat roof.
B is still left of the ridge, so the fused chain still waits on memory and has less to carry. Because time follows bytes, time falls by the byte ratio, k. A fused chain of one-calculation steps has intensity k / 4, which reaches the ridge, 4.78, at about 4 × 4.78 = 19.1 steps. So 19 steps still wait on memory, the 20th is the first limited by calculating, and the run printed 20.
The 4.78 comes from the rate of these steps, 9.75 trillion calculations a second. The 312 trillion belong to the tensor cores, which run only matrix multiplications, so they do not apply to add, multiply or ReLU steps. Those run on the ordinary circuits. The Ampere architecture post lists 108 multiprocessors with 64 FP32 cores each, a 1.41 GHz boost clock and 19.5 trillion for FP32; 108 × 64 × 2 × 1.41 billion is about 19.5 trillion, where the 2 counts a fused multiply-add as two calculations. A plain add, multiply or max is one calculation, so these steps peak at half: 19.5 / 2 = 9.75 trillion. The table is FP16, but PyTorch normally does 16-bit pointwise math in FP32 (ATen’s OpMathType.h says so, and TorchInductor’s codegen_upcast_to_fp32 is on by default), so the FP32 rate applies. A kernel that did its steps in FP16 arithmetic would get half of the post’s 78 trillion, 39 trillion, and cross over at about 77 steps.
These are data-sheet peaks; real kernels run below them, so the real crossover differs a little. A test runs the three steps at 9.75, 19.5, 78 and 312 trillion and at a quarter of 9.75: all give 98.7 µs and 32.9 µs, because intensity 0.750 sits under every ridge. The lesson’s claim needs only that the steps stay memory-bound, not an exact rate.
A hand-worked example
Take six numbers, 1 to 6, and three steps: add 1, multiply by 2, subtract 3. Use pieces of two numbers. Each row is one piece going through the fused kernel.
| Piece | Read from memory | After add 1 | After multiply by 2 | After subtract 3 | Written to memory |
|---|---|---|---|---|---|
| 1 | 1, 2 | 2, 3 | 4, 6 | 1, 3 | 1, 3 |
| 2 | 3, 4 | 4, 5 | 8, 10 | 5, 7 | 5, 7 |
| 3 | 5, 6 | 6, 7 | 12, 14 | 9, 11 | 9, 11 |
The fused run reads 6 numbers and writes 6, so 12 numbers cross between memory and the chip. Run one step at a time, each step reads 6 and writes 6, which is 12 numbers a step and 36 for the three. The ratio is 36 / 12 = 3, the number of steps. The result, 1, 3, 5, 7, 9, 11, is the same either way. A test runs this exact example.
The real implementation
The fused run is a loop over pieces, with the steps inside it:
def run_fused(x: np.ndarray, steps: list[Step], t: Traffic, chunk: int) -> None:
"""Take one chunk, run every step on it while it stays in fast memory, write it back, take the next. Works in place."""
for i in range(0, x.size, chunk):
blk = x[i:i + chunk]
t.loads += blk.size
for op, v in steps:
OPS[op](blk, v)
t.stores += blk.size
Swapping the two loops of run_unfused gives this one: pieces on the outside, steps on the inside. The counters t.loads and t.stores count every number that crosses, so a test can compare them with the closed form, 2 × steps × table alone and 2 × table fused, for piece sizes that do and do not divide the table. The file has three parts: the byte and time model (lines 42 to 108), these two counting runs (lines 111 to 154), and a CPU timing (lines 157 to 187) that the next sections use. The widget repeats the model in JavaScript, and a test checks that both give the same numbers.
Where fusion pays little
A 4096 by 4096 matrix multiplication does 2 × 4096³, about 137.4 billion calculations, and needs at least one read of each input and one write of the output, 3 × 4096² × 2 bytes. Its calculating floor is 440.5 µs and its memory floor 49.4 µs, so calculating sets the time. Its intensity is 1,365.3 calculations per byte, well above the tensor-core ridge of 153.0: point C in Figure 3. The roofline lesson shows how tiling reaches that reuse.
Fusion can still help the steps that follow it. Each finished tile of the multiplication’s output sits on the chip before it is written, so the bias, activation and scale can run on the tile first. This is called an epilogue. The write of the output happens once anyway, so the steps add no trips, and the model takes their arithmetic to overlap the multiplication’s own calculating, so it adds no time. In this model that removes the steps’ 98.7 µs from 539.2 µs, leaving 440.5 µs. That is 1.22 times faster, against 3.0 times for the steps alone, because the multiplication’s 440.5 µs stays.
Figure 4. Fusing three steps cuts their time to a third. After a large multiplication, the same fusion removes only the orange part.
One step alone also gains nothing: it already makes one read and one write, and a test checks that the fused count does not charge extra.
What it costs
- One kernel per pattern. A fused kernel is written for one chain of steps. A model has many chains, so a tool must generate a kernel for each, or a person must write it.
- Harder debugging. The in-between values live in the chip’s fast memory and are gone before you can look. To find a wrong number, run the plain chain beside the fused one and compare them, as
referenceand the tests do. - In-between values may be needed later. A model being trained uses some of its in-between values again on the way back, to learn from its mistakes. A fused kernel must then write those values to memory anyway, or calculate them again later. Either way, the count of 2 trips is the best case, for a model that is only answering.
- A piece must fit. A piece and every value in flight must fit in the chip’s fast memory. The Triton fused-softmax tutorial says its kernel is built for matrices whose rows fit in the GPU’s on-chip memory.
A run on a real machine
The model counts bytes. To see fusion on real hardware without a GPU, --time runs the same idea in numpy on a CPU. A CPU has no GPU-style memory, but it has the same two levels: main memory is large and slow, and the cache next to each core is small and fast. A piece that fits in the cache plays the part of the GPU’s fast memory.
cd lessons/why-running-gpu-steps-together-is-faster/code && python3 kernel_fusion.py --time
numpy, float32, 2**25 numbers, 4 threads, chunk 262,144; best of 5 runs, in place
3 steps: step by step 3.5 ms, chunk by chunk 2.2 ms, 1.59x faster (byte count predicts 3x)
8 steps: step by step 9.0 ms, chunk by chunk 4.7 ms, 1.90x faster (byte count predicts 8x)
These timings were measured on a CPU, not a GPU, with 4 threads on 128 MiB of numbers. They change with the machine and from run to run, so yours will differ. They show the direction: running the steps piece by piece is faster, by 1.59 times at 3 steps and 1.90 times at 8. They do not reach the byte count’s 3 and 8. Two reasons are likely: on a CPU the calculating is a larger share of each step than the model assumes, and reading from the cache is fast but not free. The run does not separate them, so treat it as evidence for the direction and not as a test of the numbers.
Proof it works
From the lesson folder:
python3 -B -m pytest -q -p no:cacheprovider code/
.............................. [100%]
30 passed in 0.15s
Each test names the mistake it guards. The chip numbers equal the roofline lesson’s. The time ratio equals the byte ratio for 1 to 8 steps. The fused kernel is first limited by calculating on the 20th step, with 19 still waiting on memory (the 77th, if the steps were done in FP16 arithmetic). The three-step times come out the same at five different calculation rates. Counted traffic equals the closed form for six piece sizes, including a leftover piece, and the output equals the plain chain; this checks the counting model against its formula and is not a measurement of a GPU. The hand-worked example gives 36 against 12. One test reads this page and fails if the pasted output or a quoted number drifts from what the program prints. The widget’s JavaScript gives the same numbers as the Python on 32 cases. No test asserts a CPU timing, because timings change from machine to machine.
Where this is used
- torch.compile and TorchInductor. The TorchInductor design post says it writes Triton for NVIDIA GPUs and C++ with OpenMP for CPUs. It lists epilogue fusions after a matrix multiplication and vertical and horizontal fusions among the patterns it handles. This is the fusion of this lesson, done by a compiler.
- Triton. One common way to write fused kernels. Its fused-softmax tutorial counts a plain softmax of an M by N matrix in PyTorch at 5MN + 2M numbers read and 3MN + 2M written. A fused kernel reads MN and writes MN, which the tutorial puts at a theoretical speed-up of about 4 times. The 4 is that ratio of traffic, counted the way this lesson counts the ratio of 3.
- FlashAttention. A well-known example of fusion. It works on blocks of the attention scores on the chip, so the full table of scores never goes to main memory (the online-softmax lesson explains the trick that makes this possible). Its authors argue that attention algorithms should be IO-aware, which means counting the reads and writes between levels of GPU memory.
- CUDA graphs. NVIDIA’s introduction describes capturing many GPU operations into one graph that launches as a unit, to cut launch overhead. That is a different fix: the kernels inside still read and write as before. PyTorch’s
reduce-overheadmode fortorch.compileuses them to reduce the overhead of Python, for small batches, and its documentation adds that this can cost more memory. - A plain-language account. Horace He’s essay on deep learning performance counts the same trips for
x.cos().cos(): 4 reads and writes alone, 2 fused, a speed-up of 2 times. He adds that a fusedx.cos().cos()takes nearly the time of onecos, which is why activation functions with very different numbers of operations, such as GELU and ReLU, cost about the same.
Skills this lesson builds
- Count the memory trips of a chain of steps and predict the upper bound of the gain from fusing it as the ratio of bytes.
- Place a chain on a roofline and say why fusion raises its intensity k-fold without making a cheap chain compute-bound.
- Say when fusion pays little: a step limited by calculating, a single step, or an in-between value that a later step needs.
- Tell fusion from CUDA graphs: one removes memory trips, the other removes launch overhead.
- Check a fused version against a plain one: the same output, and counted traffic equal to a closed form.
Portfolio project: extend time_cpu in kernel_fusion.py to sweep the piece size from 4,096 to 4,194,304 numbers on your own machine, plot the speed-up against piece size, and compare the best size with your CPU’s cache sizes. Then write what the shape of the curve says about too-small and too-large pieces.
Check yourself
1. A model adds a bias, applies a ReLU and scales a 4096 by 4096 table of 2-byte numbers, on this lesson’s A100 model. How many bytes move with the three steps one at a time, and fused? How much faster are they fused?
Answer
One at a time they make 6 trips of 33,554,432 bytes, which is 201,326,592 bytes. Fused they make 2 trips, 67,108,864 bytes. Each step does about one calculation per number, 0.25 per byte, well below the ridge of 4.8, so time follows bytes: 98.7 µs against 32.9 µs, which is 3.0 times faster.
2. The same three steps follow a big matrix multiplication and are fused into its output. Why does the job speed up by only 18.3%?
Answer
The multiplication takes 440.5 µs, set by its calculating, whether or not the steps are fused. Fusion removes only the steps’ own 98.7 µs, so the total goes from 539.2 µs to 440.5 µs. The saving is 98.7 / 539.2 = 18.3%, or 1.22 times faster.
3. A teammate says CUDA graphs fuse kernels, so there is no need to write fused ones. Is that right?
Answer
No. A CUDA graph records a list of launches and replays it as one, which saves the time spent starting each kernel. The kernels stay separate, and each still reads and writes the whole table, so the trips and the bytes are the same. Fusion changes the trips; a graph changes the launch overhead. For a chain of memory-bound steps on a big table, fusion is the fix that moves fewer bytes.
4. On the A100 model a fused chain of one-calculation steps stops waiting on memory at 20 steps. Where does 20 come from?
Answer
Fused, each number moves 2 bytes in and 2 bytes out, 4 bytes, and k steps do k calculations on it, so the intensity is k / 4. The chain stops waiting when k / 4 reaches the ridge, the calculation rate divided by the 2,039 billion bytes a second of memory. These steps run at 9.75 trillion calculations a second: the 19.5 trillion for FP32, halved because a plain add, multiply or max is one calculation and the 19.5 counts a multiply-and-add as two. The ridge is about 9.75 trillion / 2,039 billion = 4.78, so k is about 4 × 4.78 = 19.1 and the first whole step past it is 20. The tensor cores’ 312 trillion belong to matrix multiplication and do not apply. A real chain of 3 to 8 steps stays far below 20.
5. In training, the ReLU’s output is needed again later. What does that do to fusion’s saving?
Answer
The fused kernel must still write that in-between value to memory, or the model must calculate it again later. Those trips come back, so the saving is smaller than the ratio of k. The count of 2 trips is the best case, for a model that only answers and does not train.
Further reading
Gentle
- Horace He, Making Deep Learning Go Brrrr From First Principles
- PyTorch, Introduction to torch.compile
- NVIDIA, Getting Started with CUDA Graphs
- NVIDIA A100 Tensor Core GPU data sheet
Deep
- Triton, Fused Softmax, a tutorial that counts the memory traffic before and after fusion
- PyTorch developers’ forum, TorchInductor: a PyTorch-native Compiler with Define-by-Run IR and Symbolic Shapes
- PyTorch, torch.compile API documentation
- Dao, T., Fu, D. Y., Ermon, S., Rudra, A., and Ré, C. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. arXiv:2205.14135
Optional
Code
Each file runs on its own. Download it, or read it here. The code is copyright 2026 spicysharkco, all rights reserved. You may run and change it on your own computer or account to follow the lesson. The Terms cover the rest, and quoted code from other projects keeps its own license.
Show code
"""Keep the numbers inside ../widget.html equal to kernel_fusion.py.
python3 embed_widget.py rewrite the data block in widget.html
python3 embed_widget.py --check exit 1 if widget.html differs (test_widget.py runs the same check)
"""
import json
import re
import sys
from pathlib import Path
import kernel_fusion as kf
WIDGET = Path(__file__).resolve().parent.parent / "widget.html"
DATA_BLOCK = re.compile(r'(<script type="application/json" id="fus-data">)(.*?)(</script>)', re.S)
def widget_data() -> dict:
return {"side": kf.SIDE, "elem_bytes": kf.FP16_BYTES, "peak_flops": kf.A100_PEAK_FLOPS, "step_flops": kf.A100_STEP_FLOPS, "bandwidth": kf.A100_BANDWIDTH,
"max_steps": kf.MAX_STEPS}
def embed(html: str) -> str:
"""html with the data block rewritten from kernel_fusion.py."""
block = json.dumps(widget_data(), indent=1)
return DATA_BLOCK.sub(lambda m: m.group(1) + "\n" + block + "\n" + m.group(3), html, count=1)
if __name__ == "__main__":
current = WIDGET.read_text(encoding="utf-8")
updated = embed(current)
if "--check" in sys.argv:
sys.exit(0 if updated == current else 1)
WIDGET.write_text(updated, encoding="utf-8")
print("widget.html data block now matches kernel_fusion.py")Show code
"""Kernel fusion: bytes moved and time for a chain of elementwise steps, and a CPU stand-in you can run.
Model used throughout the lesson: two levels of memory, as in the roofline lesson (tiled-matmul-roofline). Main memory is large and
has a limited bandwidth; fast memory is small and free to use. We count the elements that cross between them. An elementwise step
makes each output element from the one input element in the same place, so it does 1 FLOP of math per element and needs a full read
and a full write of the tensor. A bias is one number per column, tiny next to the tensor, so the code uses one number and counts it as free.
Run `python3 kernel_fusion.py` for the numbers quoted in the lesson, and `python3 kernel_fusion.py --time` to time numpy on your own machine.
"""
from __future__ import annotations
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
import numpy as np
# --- the chip: copied from the roofline lesson (test_kernel_fusion.py checks the copy against ../../tiled-matmul-roofline/code/tiled_roofline.py)
# NVIDIA A100 Tensor Core GPU data sheet (revision "Jun21"), 80GB SXM column: 312 TFLOPS dense BFLOAT16/FP16 on the tensor cores, 2,039 GB/s
# (the 40GB cards list 1,555 GB/s). GB is 10**9 bytes. The tensor cores run only matrix multiplications.
# The steps here (add, multiply, max) run on the ordinary units. The NVIDIA Ampere Architecture In-Depth post gives 108 SMs, 64 FP32 cores
# per SM and a 1.41 GHz boost clock, and Table 1 gives 19.5 TFLOPS for FP32 (108 x 64 x 2 x 1.41 GHz = 19.49): the 2 counts one fused
# multiply-add (FMA) as two calculations. A plain add, multiply or max is one calculation per instruction, so these steps peak at half of
# it, 9.75 TFLOPS. PyTorch does FP16 pointwise math in FP32 (OpMathType.h: "For FP16 or BFloat16 inputs, ops should perform internal math
# in FP32"; torch/_inductor/config.py: codegen_upcast_to_fp32 = True), so the FP32 rate is the one that applies. Table 1 also gives
# 78 TFLOPS for FP16 arithmetic; half of that, 39 TFLOPS, is what a kernel doing its steps in FP16 would get (Go deeper uses it once).
A100_PEAK_FLOPS = 312e12
A100_BANDWIDTH = 2039e9
A100_FP32_FLOPS = 19.5e12
A100_FP16_FLOPS = 78e12
A100_STEP_FLOPS = A100_FP32_FLOPS / 2
FP16_BYTES = 2
SIDE = 4096 # the tensor is SIDE x SIDE numbers, stored in 2 bytes each
ELEMS = SIDE * SIDE
MAX_STEPS = 8 # the widget's slider
# --- the model: bytes, intensity, time --------------------------------------------------
def pass_bytes(elems: int = ELEMS, elem_bytes: int = FP16_BYTES) -> int:
"""One full trip over the tensor, in one direction."""
return elems * elem_bytes
def chain_bytes(steps: int, fused: bool, elems: int = ELEMS, elem_bytes: int = FP16_BYTES) -> int:
"""Traffic of `steps` elementwise steps. Unfused, every step reads and writes the tensor: 2 * steps passes. Fused: 2 passes."""
return (2 if fused else 2 * steps) * pass_bytes(elems, elem_bytes)
def chain_intensity(steps: int, fused: bool, elem_bytes: int = FP16_BYTES) -> float:
"""FLOP per byte: `steps` FLOPs per element over the bytes each element moves."""
return steps / (chain_bytes(steps, fused, 1, elem_bytes))
def ridge(peak_flops: float = A100_PEAK_FLOPS, bandwidth: float = A100_BANDWIDTH) -> float:
return peak_flops / bandwidth
def kernel_time(flops: float, nbytes: float, peak_flops: float = A100_PEAK_FLOPS, bandwidth: float = A100_BANDWIDTH) -> float:
"""Seconds: math and traffic overlap, so a kernel takes the larger of its two floors."""
return max(flops / peak_flops, nbytes / bandwidth)
def chain_time(steps: int, fused: bool, peak_flops: float = A100_STEP_FLOPS, elems: int = ELEMS) -> float:
"""Seconds for the chain, with the steps charged at A100_STEP_FLOPS. Unfused it is `steps` kernels one after another; fused it is
one kernel doing all the math."""
if fused:
return kernel_time(steps * elems, chain_bytes(steps, True, elems), peak_flops)
return steps * kernel_time(elems, chain_bytes(1, False, elems), peak_flops)
def steps_to_reach_ridge(flops_per_step: int = 1, elem_bytes: int = FP16_BYTES, peak_flops: float = A100_STEP_FLOPS) -> int:
"""Fewest chained steps for which the fused kernel stops waiting on memory: steps * flops_per_step / (2 * elem_bytes) >= ridge.
The default is the rate of the add, multiply and max steps; pass A100_FP16_FLOPS / 2 for steps done in FP16 arithmetic."""
need = ridge(peak_flops) * 2 * elem_bytes / flops_per_step
return int(need) + (need != int(need))
def matmul_flops(side: int = SIDE) -> int:
return 2 * side ** 3
def matmul_min_bytes(side: int = SIDE, elem_bytes: int = FP16_BYTES) -> int:
"""Read A once, read B once, write C once (the best case, from the roofline lesson)."""
return 3 * side * side * elem_bytes
def matmul_intensity(side: int = SIDE) -> float:
"""FLOP per byte of the multiply in its best case; it equals side / 3 for 2-byte numbers."""
return matmul_flops(side) / matmul_min_bytes(side)
def matmul_time(side: int = SIDE) -> float:
return kernel_time(matmul_flops(side), matmul_min_bytes(side))
def matmul_then_chain_bytes(steps: int, fused: bool) -> int:
"""Traffic of the multiply plus the chain: the chain's passes are the only part fusion removes."""
return matmul_min_bytes() + (0 if fused else chain_bytes(steps, False))
def matmul_then_chain_time(steps: int, fused: bool) -> float:
"""A big matrix multiply followed by the chain on its result. Fused, the steps run on each tile of C before its one write
(the epilogue), so the multiply's own write is the only write and the chain adds no passes. The model takes the steps' arithmetic in
the epilogue to overlap the multiply's own calculating, so it adds no time."""
return matmul_time() + (0.0 if fused else chain_time(steps, False))
# --- executors that count traffic ---------------------------------------------------------
@dataclass
class Traffic:
loads: int = 0 # elements read from main memory
stores: int = 0 # elements written to main memory
def nbytes(self, elem_bytes: int) -> int:
return (self.loads + self.stores) * elem_bytes
OPS = {
"add": lambda a, v: np.add(a, v, out=a),
"sub": lambda a, v: np.subtract(a, v, out=a),
"mul": lambda a, v: np.multiply(a, v, out=a),
"relu": lambda a, v: np.maximum(a, 0, out=a),
}
Step = tuple[str, float]
def run_unfused(x: np.ndarray, steps: list[Step], t: Traffic) -> None:
"""Each step sweeps the whole array: read all of it, write all of it, before the next step starts. Works in place."""
for op, v in steps:
t.loads += x.size
OPS[op](x, v)
t.stores += x.size
def run_fused(x: np.ndarray, steps: list[Step], t: Traffic, chunk: int) -> None:
"""Take one chunk, run every step on it while it stays in fast memory, write it back, take the next. Works in place."""
for i in range(0, x.size, chunk):
blk = x[i:i + chunk]
t.loads += blk.size
for op, v in steps:
OPS[op](blk, v)
t.stores += blk.size
def reference(x: np.ndarray, steps: list[Step]) -> np.ndarray:
"""The same chain with no counting and no chunks, on a copy."""
y = x.copy()
for op, v in steps:
OPS[op](y, v)
return y
# --- timing on the CPU (numpy) ------------------------------------------------------------
# The CPU has no HBM, but it has the same two-level shape: main memory (slow) and the cache next to the core (fast). A chunk that fits
# in cache plays the part of the tile held in registers or shared memory on a GPU.
TIMING_STEPS: list[Step] = [("add", 0.5), ("mul", 1.25), ("sub", 0.125), ("add", 0.25), ("mul", 0.75), ("sub", 0.0625), ("add", 0.125), ("mul", 1.5)]
CPU_ELEMS = 2 ** 25 # float32: 128 MiB, far larger than any cache
CPU_CHUNK = 262144 # float32: 1 MiB
CPU_WORKERS = 4
def _slabs(x: np.ndarray, workers: int) -> list[np.ndarray]:
size = x.size // workers
return [x[i * size:(i + 1) * size] for i in range(workers)]
def time_cpu(steps: int, fused: bool, reps: int = 5, workers: int = CPU_WORKERS, chunk: int = CPU_CHUNK) -> float:
"""Best of `reps` seconds for the first `steps` of TIMING_STEPS on 2**25 float32, split across `workers` threads."""
chain = TIMING_STEPS[:steps]
base = np.random.default_rng(0).random(CPU_ELEMS, dtype=np.float32)
best = float("inf")
with ThreadPoolExecutor(workers) as pool:
for _ in range(reps):
x = base.copy()
slabs = _slabs(x, workers)
start = time.perf_counter()
if fused:
list(pool.map(lambda s: run_fused(s, chain, Traffic(), chunk), slabs))
else:
list(pool.map(lambda s: run_unfused(s, chain, Traffic()), slabs))
best = min(best, time.perf_counter() - start)
return best
def main() -> None:
k = 3
print(f"table: {SIDE} x {SIDE} = {ELEMS:,} numbers of {FP16_BYTES} bytes; one pass = {pass_bytes():,} bytes")
print(f"A100 ridge (FLOP/byte): {ridge(A100_STEP_FLOPS):.1f} for the add, ReLU and scale steps, {ridge():.1f} for the tensor-core multiply")
for fused in (False, True):
name = "fused" if fused else "unfused"
print(f"{k} steps {name}: {2 if fused else 2 * k} passes, {chain_bytes(k, fused):,} bytes, "
f"{chain_time(k, fused) * 1e6:.1f} us, intensity {chain_intensity(k, fused):.3f} FLOP/byte")
print(f"byte ratio {chain_bytes(k, False) / chain_bytes(k, True):.1f}x, time ratio {chain_time(k, False) / chain_time(k, True):.1f}x")
print(f"one-FLOP steps needed for the fused kernel to reach the ridge: {steps_to_reach_ridge()}")
print(f"matmul {SIDE}^3: {matmul_flops() / 1e9:.1f} GFLOP, calculation floor {matmul_flops() / A100_PEAK_FLOPS * 1e6:.1f} us, "
f"memory floor {matmul_min_bytes() / A100_BANDWIDTH * 1e6:.1f} us, time {matmul_time() * 1e6:.1f} us, "
f"intensity {matmul_intensity():,.1f} FLOP/byte")
u, f = matmul_then_chain_time(k, False), matmul_then_chain_time(k, True)
print(f"matmul then {k} steps: unfused {u * 1e6:.1f} us, fused into the epilogue {f * 1e6:.1f} us, "
f"{u / f:.2f}x, {(u - f) / u * 100:.1f}% saved")
def main_time() -> None:
print(f"numpy, float32, 2**25 numbers, {CPU_WORKERS} threads, chunk {CPU_CHUNK:,}; best of 5 runs, in place")
for steps in (3, 8):
a, b = time_cpu(steps, False), time_cpu(steps, True)
print(f"{steps} steps: step by step {a * 1e3:.1f} ms, chunk by chunk {b * 1e3:.1f} ms, {a / b:.2f}x faster "
f"(byte count predicts {steps:.0f}x)")
if __name__ == "__main__":
main_time() if "--time" in sys.argv else main()Show code
"""Guards for kernel_fusion.py: the chip it copies, the byte counts, the executors, the ridge, the matrix-multiply case, and the numbers the lesson prints."""
import re
from pathlib import Path
import numpy as np
import pytest
import kernel_fusion as kf
ROOFLINE = Path(__file__).resolve().parents[2] / "tiled-matmul-roofline" / "code" / "tiled_roofline.py"
LESSON = Path(__file__).resolve().parents[1] / "lesson.md"
CHAIN: list[kf.Step] = [("add", 0.5), ("relu", 0.0), ("mul", 1.25)] # bias, activation, scale
def test_chip_constants_equal_the_roofline_lessons(tmp_path):
"""Guards a copy that drifted: the lesson quotes the roofline lesson's A100 numbers, so both files must hold the same ones."""
source = ROOFLINE.read_text(encoding="utf-8")
for name in ("A100_PEAK_FLOPS", "A100_BANDWIDTH", "FP16_BYTES"):
theirs = re.search(rf"^{name} = (\S+)$", source, re.M)
assert theirs, f"{name} not found in the roofline lesson: update this test"
assert float(theirs.group(1)) == getattr(kf, name), name
def test_three_steps_move_6_passes_unfused_and_2_fused():
"""Guards the lesson's headline count: 201,326,592 bytes against 67,108,864, a ratio of exactly 3."""
assert kf.pass_bytes() == 33_554_432
assert kf.chain_bytes(3, fused=False) == 6 * 33_554_432 == 201_326_592
assert kf.chain_bytes(3, fused=True) == 2 * 33_554_432 == 67_108_864
@pytest.mark.parametrize("steps", range(1, kf.MAX_STEPS + 1))
def test_while_memory_bound_the_time_ratio_equals_the_byte_ratio(steps):
"""Guards the claim 'time follows bytes': for 1 to 8 steps the chain is memory-bound both ways, so time saved equals bytes saved."""
ratio_time = kf.chain_time(steps, False) / kf.chain_time(steps, True)
ratio_bytes = kf.chain_bytes(steps, False) / kf.chain_bytes(steps, True)
assert ratio_bytes == steps
assert ratio_time == pytest.approx(steps, rel=1e-12)
def test_a_single_step_gains_nothing_from_fusion():
"""Guards a fused count that charges for fusing: one step is already one read and one write."""
assert kf.chain_bytes(1, True) == kf.chain_bytes(1, False)
assert kf.chain_time(1, True) == kf.chain_time(1, False)
def test_intensity_rises_by_the_number_of_steps_but_stays_below_the_ridge():
"""Guards the claim that 3 fused steps are still memory-bound (0.75 FLOP/byte against a ridge of 4.8 for the steps and 153 for the multiply),
and the step rate: half of the FMA-counted 19.5 TFLOPS, which is 108 SMs x 64 cores x 2 x 1.41 GHz. Charging the steps at 19.5 moves the ridge to 9.6."""
assert kf.chain_intensity(3, False) == 0.25
assert kf.chain_intensity(3, True) == 0.75
assert kf.ridge() == pytest.approx(153.0, abs=0.05)
assert kf.ridge(kf.A100_STEP_FLOPS) == pytest.approx(4.78, abs=0.005)
assert kf.A100_STEP_FLOPS == 9.75e12
assert 108 * 64 * 2 * 1.41e9 == pytest.approx(kf.A100_FP32_FLOPS, rel=0.002)
@pytest.mark.parametrize("peak, first_busy", [(kf.A100_STEP_FLOPS, 20), (kf.A100_FP16_FLOPS / 2, 77)])
def test_the_step_where_the_fused_kernel_stops_waiting_on_memory(peak, first_busy):
"""Guards the crossover against the FMA-counted 19.5 TFLOPS, which doubles the step rate and raises the crossover from 20 to 39; the
second case is steps done in FP16 arithmetic (78 TFLOPS, halved the same way). Steps before `first_busy` still take the traffic time,
and `first_busy` is limited by math."""
traffic_time = kf.chain_bytes(first_busy - 1, True) / kf.A100_BANDWIDTH
assert kf.steps_to_reach_ridge(peak_flops=peak) == first_busy
assert kf.chain_time(first_busy - 1, True, peak) == pytest.approx(traffic_time, rel=1e-12)
assert kf.chain_time(first_busy, True, peak) > kf.chain_bytes(first_busy, True) / kf.A100_BANDWIDTH * (1 + 1e-6)
@pytest.mark.parametrize("fused", [False, True])
def test_the_three_step_times_do_not_depend_on_which_calculation_rate_is_right(fused):
"""Guards the headline against the calculation rate: 3 steps take the same time at the step rate, at the FMA-counted and FP16 rates,
at the tensor-core rate and at a rate 4 times below the step rate, because they wait on memory in all of them."""
want = kf.chain_time(3, fused)
for rate in (kf.A100_STEP_FLOPS, kf.A100_FP32_FLOPS, kf.A100_FP16_FLOPS, kf.A100_PEAK_FLOPS, kf.A100_STEP_FLOPS / 4):
assert kf.chain_time(3, fused, rate) == want
def test_the_big_matrix_multiply_is_compute_bound_and_fusion_only_removes_the_chains_passes():
"""Guards the 'where fusion pays little' claim: the multiply takes its calculation floor, fused or not, and the chain is the only part that shrinks."""
assert kf.matmul_flops() / kf.A100_PEAK_FLOPS > kf.matmul_min_bytes() / kf.A100_BANDWIDTH
assert kf.matmul_time() == kf.matmul_flops() / kf.A100_PEAK_FLOPS
assert kf.matmul_intensity() == pytest.approx(kf.SIDE / 3) and kf.matmul_intensity() > kf.ridge()
fused, unfused = kf.matmul_then_chain_time(3, True), kf.matmul_then_chain_time(3, False)
assert fused == kf.matmul_time() # the steps' arithmetic is taken to overlap the multiply's calculating
assert unfused - fused == pytest.approx(kf.chain_time(3, False), rel=1e-9)
assert 1 - fused / unfused < 0.2 # about 18%, nowhere near the 67% the chain alone saves
assert 1 - kf.chain_time(3, True) / kf.chain_time(3, False) == pytest.approx(2 / 3)
@pytest.mark.parametrize("size,chunk", [(1000, 7), (1000, 1000), (1000, 1001), (1000, 1), (1024, 256), (999, 100)])
def test_counted_traffic_matches_the_closed_form_and_the_outputs_agree(size, chunk):
"""Guards a remainder chunk that is dropped or counted twice: the counters must equal the closed form for any chunk size,
and the fused and unfused runs must produce the very same numbers as the plain chain. This checks the counting model against
its formula; it is not a measurement of a GPU."""
x = np.random.default_rng(size).standard_normal(size).astype(np.float32)
a, b = x.copy(), x.copy()
tu, tf = kf.Traffic(), kf.Traffic()
kf.run_unfused(a, CHAIN, tu)
kf.run_fused(b, CHAIN, tf, chunk)
want = kf.reference(x, CHAIN)
assert np.array_equal(a, want) and np.array_equal(b, want)
assert (tu.loads, tu.stores) == (size * len(CHAIN), size * len(CHAIN))
assert (tf.loads, tf.stores) == (size, size)
assert tu.nbytes(2) == kf.chain_bytes(len(CHAIN), False, size)
assert tf.nbytes(2) == kf.chain_bytes(len(CHAIN), True, size)
def test_the_hand_worked_example_of_the_lesson():
"""Guards the table in Go deeper: six numbers, three steps, chunks of two. Unfused 36 numbers cross, fused 12."""
steps = [("add", 1.0), ("mul", 2.0), ("sub", 3.0)]
x = np.array([1, 2, 3, 4, 5, 6], dtype=np.float32)
a, b = x.copy(), x.copy()
tu, tf = kf.Traffic(), kf.Traffic()
kf.run_unfused(a, steps, tu)
kf.run_fused(b, steps, tf, 2)
assert a.tolist() == b.tolist() == [1, 3, 5, 7, 9, 11]
assert tu.loads + tu.stores == 36 and tf.loads + tf.stores == 12
def test_timing_split_covers_the_array_exactly():
"""Guards the CPU timing setup: a worker count that does not divide the array would leave a tail untouched and shorten the timed work."""
assert kf.CPU_ELEMS % kf.CPU_WORKERS == 0
slabs = kf._slabs(np.arange(kf.CPU_ELEMS, dtype=np.float32), kf.CPU_WORKERS)
assert sum(s.size for s in slabs) == kf.CPU_ELEMS and slabs[0][0] == 0 and slabs[-1][-1] == kf.CPU_ELEMS - 1
def test_the_lesson_pastes_the_real_output_and_quotes_its_numbers(capsys):
"""Guards the lesson text against the code: every line main() prints is pasted verbatim into the lesson, and each figure the prose
quotes, formatted here from the model and not typed, appears in the lesson."""
kf.main()
text = LESSON.read_text(encoding="utf-8")
for line in capsys.readouterr().out.splitlines():
assert line in text, line
us = lambda seconds: f"{seconds * 1e6:.1f} \u00b5s"
after, fused_after = kf.matmul_then_chain_time(3, False), kf.matmul_then_chain_time(3, True)
quoted = [
f"{kf.pass_bytes():,}", f"{kf.chain_bytes(3, False):,}", f"{kf.chain_bytes(3, True):,}", f"{kf.pass_bytes() / 1e6:.1f} MB",
us(kf.chain_time(3, False)), us(kf.chain_time(3, True)), us(kf.chain_time(6, False)), us(kf.chain_time(6, True)),
f"{kf.chain_intensity(3, False):.2f}", f"{kf.chain_intensity(3, True):.2f}",
f"{kf.ridge():.1f}", f"{kf.ridge(kf.A100_STEP_FLOPS):.1f}", f"{kf.A100_STEP_FLOPS / 1e12:g} trillion", f"{kf.A100_FP32_FLOPS / 1e12:g} trillion",
f"{kf.steps_to_reach_ridge()} steps", f"about {kf.steps_to_reach_ridge(peak_flops=kf.A100_FP16_FLOPS / 2)} steps",
f"{kf.matmul_flops() / 1e9:.1f} billion", us(kf.matmul_time()), us(kf.matmul_min_bytes() / kf.A100_BANDWIDTH),
f"{kf.matmul_intensity():,.1f}", us(after), f"{after / fused_after:.2f}", f"{(after - fused_after) / after * 100:.1f}%",
]
for figure in quoted:
assert figure in text, figureShow code
"""Guards for ../widget.html: its data block, its size, and that its JavaScript computes what kernel_fusion.py does."""
import json
import re
import subprocess
import kernel_fusion as kf
from embed_widget import WIDGET, embed
HTML = WIDGET.read_text(encoding="utf-8")
# Reads the number code out of the widget between its marker comments, runs it, and compares with the values Python wrote into the fixture.
PARITY = r"""
import fs from 'node:fs';
const [fixture, widget] = process.argv.slice(2);
const fx = JSON.parse(fs.readFileSync(fixture, 'utf8'));
const html = fs.readFileSync(widget, 'utf8');
const DATA = JSON.parse(html.match(/<script type="application\/json" id="fus-data">([\s\S]*?)<\/script>/)[1]);
const js = html.slice(html.indexOf('/* ---------- the numbers'), html.indexOf('/* ---------- the page'));
const api = new Function('DATA', "'use strict';" + js + '; return {chainBytes, chainTime, matmulTime, totalBytes, totalTime};')(DATA);
const bad = [];
const close = (a, b) => Math.abs(a - b) <= 1e-12 * Math.abs(b);
fx.cases.forEach((c) => {
if (api.totalBytes(c.steps, c.fused, c.mm) !== c.bytes) bad.push(['bytes', c]);
if (!close(api.totalTime(c.steps, c.fused, c.mm), c.time)) bad.push(['time', c, api.totalTime(c.steps, c.fused, c.mm)]);
});
if (!close(api.matmulTime(), fx.matmul)) bad.push(['matmul', api.matmulTime(), fx.matmul]);
console.log(JSON.stringify({ cases: fx.cases.length, bad: bad.slice(0, 5) }));
process.exit(bad.length ? 1 : 0);
"""
def test_widget_data_block_matches_kernel_fusion():
"""Guards an edit to the constants that was not copied into the widget (run embed_widget.py)."""
assert embed(HTML) == HTML
def test_every_element_the_script_looks_up_exists():
"""Guards a widget that never starts: a lookup of an id the page does not contain throws in the browser."""
page = HTML[:HTML.index("<script")]
ids = set(re.findall(r"\$\('([\w-]+)'\)", HTML[HTML.index("<script>"):])) | {"fus-t0", "fus-t1", "fus-s0", "fus-s1", "fus-mmbar0", "fus-mmbar1", "fus-b0", "fus-b1"}
assert all(f'id="{i}"' in page for i in ids), sorted(i for i in ids if f'id="{i}"' not in page)
assert 'id="fus-data"' in HTML and 'class="fus-root"' in page
def test_widget_is_small_and_asks_for_nothing_online():
"""Guards the widget growing past the 300-line limit, or reaching the network (a fetch, an external script or a font) and breaking offline use."""
assert len(HTML.encode("utf-8")) < 40 * 1024 and HTML.count("\n") < 300
for banned in ("http://", "https://", "fetch(", "XMLHttpRequest", "WebSocket", "sendBeacon", "import("):
assert banned not in HTML, banned
assert " src=" not in HTML and "@import" not in HTML
def test_widget_numbers_match_the_python_code(tmp_path):
"""Guards the widget's JavaScript drifting from kernel_fusion.py: its bytes and predicted times for every slider position,
with and without the multiply, must be the lesson's."""
cases = [{"steps": k, "fused": f, "mm": mm,
"bytes": kf.matmul_then_chain_bytes(k, f) if mm else kf.chain_bytes(k, f),
"time": kf.matmul_then_chain_time(k, f) if mm else kf.chain_time(k, f)}
for k in range(1, kf.MAX_STEPS + 1) for f in (False, True) for mm in (False, True)]
(tmp_path / "fixture.json").write_text(json.dumps({"matmul": kf.matmul_time(), "cases": cases}), encoding="utf-8")
(tmp_path / "parity.mjs").write_text(PARITY, encoding="utf-8")
run = subprocess.run(["node", str(tmp_path / "parity.mjs"), str(tmp_path / "fixture.json"), str(WIDGET)],
capture_output=True, text=True, timeout=120)
assert run.returncode == 0, run.stdout + run.stderr
assert json.loads(run.stdout)["cases"] == kf.MAX_STEPS * 2 * 2 == 32
assert kf.matmul_then_chain_bytes(3, False) - kf.matmul_then_chain_bytes(3, True) == kf.chain_bytes(3, False)