---
title: "Why running GPU steps together makes a model faster"
description: "Each small GPU step carries the whole table out of memory and back. Fuse three steps into one and, in this lesson's model, the job takes a third of the time."
topic: "AI systems"
chapter: "inside-the-chip"
order: 34
minutes: { plain: 5, deep: 20 }
prerequisites: ["Matrix multiplication", "Reading Python and NumPy"]
seo_title: "What is kernel fusion in deep learning?"
date: 2026-10-27
---

# Why running GPU steps together makes a model faster

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](https://spicyshark.co/learn/why-running-gpu-steps-together-is-faster/widget.html) 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](https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf). It predicts; it does not measure. As in [the roofline lesson](https://spicyshark.co/learn/tiled-matmul-roofline/), 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.

![Two panels. Top: three steps run one at a time make six trips between main memory and the chip, a read and a write for each step. Bottom: the same three steps fused make two trips, one read and one write, with the steps run on the chip in between.](https://spicyshark.co/learn/why-running-gpu-steps-together-is-faster/figs/trips.svg)

*Figure 1. Three steps alone make six trips between memory and the chip; fused, two.*

1. **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.
2. **Run each step alone.** A step reads the whole table and writes it all back: two trips.
3. **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](https://developer.nvidia.com/blog/nvidia-ampere-architecture-in-depth/) can serve some repeat trips of a 33.6 MB table, so real gains are smaller.
4. **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](https://github.com/pytorch/pytorch/blob/e68ed499d7c4e1e2e8cdbf867f9ec0e8b9bf9db0/aten/src/ATen/OpMathType.h#L15-L23). 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.
5. **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.
6. **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:44`<br>`return elems * elem_bytes` | One trip is every number in the table times its size in bytes. |
| 2. Run each step alone | `kernel_fusion.py:134`<br>`t.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:49`<br>`return (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:63`<br>`return 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:145`<br>`OPS[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:108`<br>`return 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:

```bash
cd lessons/why-running-gpu-steps-together-is-faster/code && python3 kernel_fusion.py
```

Phone readers: slide the box sideways to see every column.

```text
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.

## Your turn

Predict, then run, from the `code/` folder:

```bash
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?

<details><summary>Expected output</summary>

```text
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.

</details>

## 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](https://spicyshark.co/learn/tiled-matmul-roofline/) 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.

## 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](https://ocw.mit.edu/courses/18-06sc-linear-algebra-fall-2011/pages/ax-b-and-the-four-subspaces/multiplication-and-inverse-matrices/).
> - Reading Python and NumPy: [NumPy: the absolute basics for beginners](https://numpy.org/doc/stable/user/absolute_beginners.html).

### 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.

```python
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](https://spicyshark.co/learn/tiled-matmul-roofline/) 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.

![A row of six pieces of a table in main memory, the third highlighted. An arrow labeled read once carries that piece down to a box of fast memory where the steps add, relu and scale run one after another. An arrow labeled write once carries it back. Then the next piece is taken.](https://spicyshark.co/learn/why-running-gpu-steps-together-is-faster/figs/chunks.svg)

*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.

![Speed in trillions of calculations per second against calculations per byte, both on log scales. The memory slope rises to a ridge at 153 and then runs flat at 312. A dashed lower roof at 9.75, with its ridge at 4.8, marks the ordinary add, ReLU and scale steps. A, three steps one at a time, sits at 0.25 per byte. B, the same steps fused, sits at 0.75, still left of the ridge at 4.8. C, a 4096 by 4096 matrix multiplication, sits at 1,365 on the flat roof.](https://spicyshark.co/learn/why-running-gpu-steps-together-is-faster/figs/roofline-slide.svg)

*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](https://developer.nvidia.com/blog/nvidia-ampere-architecture-in-depth/) 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`](https://github.com/pytorch/pytorch/blob/e68ed499d7c4e1e2e8cdbf867f9ec0e8b9bf9db0/aten/src/ATen/OpMathType.h#L15-L23) says so, and TorchInductor's [`codegen_upcast_to_fp32`](https://github.com/pytorch/pytorch/blob/e68ed499d7c4e1e2e8cdbf867f9ec0e8b9bf9db0/torch/_inductor/config.py#L2508) 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:

```python
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](https://spicyshark.co/learn/tiled-matmul-roofline/) 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.

![Horizontal bars in microseconds on one A100, model values. Three steps alone: 98.7 one at a time, 32.9 fused, in orange. After a 4096 by 4096 matrix multiplication: 539.2 one at a time, made of 440.5 green multiplication and 98.7 orange steps; 440.5 fused into the multiplication, all green.](https://spicyshark.co/learn/why-running-gpu-steps-together-is-faster/figs/matmul-bars.svg)

*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 `reference` and 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.

```bash
cd lessons/why-running-gpu-steps-together-is-faster/code && python3 kernel_fusion.py --time
```

```text
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:

```bash
python3 -B -m pytest -q -p no:cacheprovider code/
```

```text
..............................                                           [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](https://spicyshark.co/learn/online-softmax/) 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-overhead` mode for `torch.compile` uses 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 fused `x.cos().cos()` takes nearly the time of one `cos`, 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?

<details><summary>Answer</summary>
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.
</details>

**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%?

<details><summary>Answer</summary>
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.
</details>

**3.** A teammate says CUDA graphs fuse kernels, so there is no need to write fused ones. Is that right?

<details><summary>Answer</summary>
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.
</details>

**4.** On the A100 model a fused chain of one-calculation steps stops waiting on memory at 20 steps. Where does 20 come from?

<details><summary>Answer</summary>
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.
</details>

**5.** In training, the ReLU's output is needed again later. What does that do to fusion's saving?

<details><summary>Answer</summary>
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.
</details>

## Further reading

**Gentle**

- Horace He, [Making Deep Learning Go Brrrr From First Principles](https://horace.io/brrr_intro.html)
- PyTorch, [Introduction to torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html)
- NVIDIA, [Getting Started with CUDA Graphs](https://developer.nvidia.com/blog/cuda-graphs/)
- [NVIDIA A100 Tensor Core GPU data sheet](https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf)

**Deep**

- Triton, [Fused Softmax](https://triton-lang.org/main/getting-started/tutorials/02-fused-softmax.html), 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](https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747)
- PyTorch, [torch.compile API documentation](https://docs.pytorch.org/docs/stable/generated/torch.compile.html)
- 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](https://arxiv.org/abs/2205.14135)
