One line of PyTorch GELU launches 9 kernels and passes over memory 22 times. On the lecture's H100 that took 7.67 ms of GPU time. One fused kernel passes twice and took 0.70 ms: 11 times fewer bytes, 10.9 times faster.
Pick one of the five ways to write GELU and watch its kernels run. Then switch from the profiler to the stopwatch. Then we build each way from zero: an honest benchmark, the profiler, a CUDA kernel, a Triton kernel, torch.compile and a fused softmax.
You need the two clocks and arithmetic intensity from Lecture 5, and a little Python. We build the rest from zero.
Lecture 6 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto; this lecture by Tatsunori Hashimoto). Previous: Lecture 5, GPUs. Next: Lecture 7, Parallelism I.
Times are the lecture's own run on an NVIDIA H100 80GB HBM3, from the trace in stanford-cs336/spring2025-lectures: profiler kernel times and the mean of 3 timed calls, on a 16,384 × 16,384 float32 tensor (1.07 GB). The two kinds of number come from separate calls in the same run.
Chapter 0
Count the kernels and the trips to memory behind one line of PyTorch
You write GELU as one line of PyTorch math, in the tanh form the lecture uses. On a 16,384 by 16,384 tensor of float32 numbers, the lecture's H100 took 8.1 ms per call. PyTorch's own gelu took 1.1 ms. The math is the same.
The profiler explains the gap. PyTorch runs eagerly: each operator in the line launches its own kernel, a function that runs on the GPU. The line has 9 operators (six multiplies, two adds and a tanh), so 9 kernels run. Each one reads its inputs from HBM, the GPU's main memory, and writes its result back.
Lecture 5 showed that an elementwise kernel waits on memory, not on math. So count bytes. Call the tensors the kernels read R, the tensors they write W, the elements in a tensor n, and the bytes per element b. The traffic is:
Q equals R plus W, times n, times b.
Count every tensor each kernel reads, and every tensor it writes. R plus W is the number of passes over memory. Multiply by the size of one tensor, n times b.
Manual GELU: R = 13 and W = 9, so 22 passes. One pass is 268,435,456 × 4 bytes = 1.07 GB, so Q = 23.6 GB. A fused kernel reads x once and writes y once: 2 passes, 2.15 GB. That is 11 times less traffic.
Each box is one kernel, in the order Python runs them, with the tensors it reads from HBM and writes back. Press Next kernel, or fuse the line into one.
Kernel order and read counts come from running the lecture's manual_gelu under PyTorch's dispatcher. Kernel times are the lecture's profiler rows on the H100: 0.70 ms for a kernel that reads one tensor, 1.04 ms for one that reads two.
The profiler agrees with the count. The 9 kernels took 7.67 ms of GPU time, 3.1 TB/s. PyTorch's fused kernel took 0.70 ms, also at 3.1 TB/s: 10.9 times faster, the same ratio as the traffic. Both ran at 91 to 92% of the H100's 3.35 TB/s. Fusion did not make the memory faster. It moved fewer bytes.
This lecture gets you that one kernel three ways: write CUDA, write Triton, or let torch.compile write it. First, measure honestly.
Symptom: a block of elementwise math (an activation, a norm, a bias add) takes far more GPU time than its FLOPs suggest.
Measure: count the kernels in a profile, and the passes over memory: Q = (R + W) × n × b.
Fix: one fused kernel: PyTorch's built-in op, torch.compile, or your own Triton kernel.
y = a * b + c eagerly on three tensors of the same size. How many passes over memory does it make?Chapter 1
Make a stopwatch tell the truth: synchronize, warm up, then repeat
A benchmark measures wall-clock time: start a timer, run the code, stop the timer. The lecture's rule: spec sheets and papers do not know your library version, your GPU or your workload, so measure your own code. A GPU makes the stopwatch easy to fool.
The CPU and the GPU run at the same time. When Python calls a CUDA operation, the CPU puts a kernel in the GPU's queue and returns at once. It does not wait for the result. So a time.time() after the call measures how long it took to queue the work, not to do it.
torch.cuda.synchronize() makes the CPU wait until the GPU's queue is empty. The lecture's benchmark calls it after the warm-up and after every trial. The warm-up is one untimed call, because the first call can compile code or fill caches. Then it times 3 trials and reports their mean.
python def benchmark(run, num_warmups=1, num_trials=3): # the lecture's version for _ in range(num_warmups): run() # first calls can compile or fill caches torch.cuda.synchronize() # wait for the warm-up to finish times = [] for trial in range(num_trials): start = time.time() run() # only queues the kernels torch.cuda.synchronize() # wait until the GPU is done times.append((time.time() - start) * 1000) return sum(times) / len(times) # milliseconds
Top lane: the CPU queues each call and starts and stops the clock. Bottom lane: the GPU runs the kernels. Switch the synchronize and the warm-up off and on.
Illustrative timeline: the kernel takes the lecture's 0.70 ms; queuing a call takes 0.02 ms and the first call costs an extra 1.5 ms. Both of those are made-up round numbers.
With the device's numbers, a missing synchronize reads 0.02 ms for a kernel that takes 0.70 ms: 35 times too fast. A missing warm-up puts the one-time cost into the first trial, and the mean of three goes from 0.72 ms to 1.22 ms.
Check the stopwatch on something you know first. The lecture times time.sleep(0.05) and gets 50.61 ms, the 50 ms it asked for plus a little.
Symptom: your new kernel looks 30 times faster than PyTorch's.
Measure: check that the clock stops after torch.cuda.synchronize(), and that the first call is not timed.
Fix: synchronize before you read the clock, warm up first, and report several trials.
torch.cuda.synchronize() and read 0.02 ms. What did you measure?Chapter 2
Grow one knob at a time, and read what the time depends on from the shape of the curve
One timing says little. A sweep says what the time depends on. The lecture benchmarks a small MLP (a linear layer then a GELU, repeated), forward and backward, on its H100. The base run has width 256, 4 layers, batch 256 and 2 steps: 6.29 ms.
Then it grows one knob at a time, up to 5 times. Steps and layers make the time grow in a straight line: each extra layer adds 0.89 ms over the 2 steps. Batch and width do nothing: 5 times the batch takes 5.96 ms.
Each dot is one of the lecture's measurements. Pick a knob, then drag the scale to read a point.
All times are the lecture's: mean of 3 timed runs on an H100, float32. MLP base: width 256, 4 layers, batch 256, 2 steps of forward and backward. Matmuls are square n by n.
Count the work to see why. One layer at width 256 and batch 256 does 6 × 256 × 2562 = 1.0 × 108 FLOPs per step, forward and backward. At 50 TFLOP/s that is 2 µs. The measured cost is 443 µs per layer per step.
So over 99% of the time is not math. It is a fixed cost paid for each operation: Python, PyTorch's dispatcher, autograd and the kernel launch. The GPU finishes each tiny kernel and waits for the next.
The matmul sweep shows both regimes. Sizes 1,024 and 2,048 take the same 0.84 to 0.87 ms, though the second does 8 times the FLOPs. From 8,192 to 16,384 the time grows 7.5 times, close to the 8 that 2n3 predicts. Only there does the GPU reach 54 TFLOP/s in float32, about 80% of the H100's 67.
Symptom: doubling the batch does not change the step time.
Measure: sweep the batch and the width. A flat curve means fixed costs set the time.
Fix: give each kernel more work (bigger batches), fuse operations, or launch the whole step as one CUDA graph (Chapter 7).
Chapter 3
Split the time by kernel, read what each name tells you, and check each kernel against the bandwidth
A benchmark gives one number. A profiler says where it went. PyTorch's torch.profiler records every operator, every kernel it launched, and their time on the CPU and on the GPU. The lecture sorts the table by GPU time.
python with torch.profiler.profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof: run() torch.cuda.synchronize() print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=10))
Kernel names show the implementation. A 2,048 by 2,048 float32 matmul ran cutlass_80_simt_sgemm_256x128_8x4_nn_align1: CUTLASS, NVIDIA's linear algebra library, with 256 by 128 tiles. At 128 by 128, PyTorch picked a different kernel, with 32 by 32 tiles. The library chooses the kernel by shape.
Is a kernel good? For an elementwise kernel, compare its bytes with its time. Take the traffic Q from Chapter 0 and the GPU time t from the profiler. Their ratio is the effective bandwidth:
B-eff equals Q over t.
Count the kernel's bytes Q. Divide by its GPU time t. Compare the result with the datasheet bandwidth.
The lecture adds two 2,048 by 2,048 float32 matrices: 2 reads and 1 write, so Q = 3 × 4,194,304 × 4 = 50.3 MB. The profiler gives t = 17.1 µs. Beff = 2.94 TB/s, 88% of the H100's 3.35 TB/s. The kernel is about as fast as the memory allows.
Filled bars are GPU time per kernel. The outlined bar is CPU time spent launching. Pick a workload.
Rows are the lecture's torch.profiler output on the H100, grouped as the table groups them; short names are ours, full names are in the read-out.
The same tables show the cost of launching. That add spent 19 µs of CPU time in cudaLaunchKernel, more than the 17 µs the GPU spent adding. The 128 by 128 matmul spent 226 µs launching and 5 µs computing. That is the fixed cost behind the flat curves of Chapter 2.
Symptom: an elementwise kernel reaches 40% of the bandwidth.
Measure: Beff = Q / t from the profiler.
Fix: look for wasted bytes or wasted work: uncoalesced loads (Lecture 5, Chapter 6), one element per thread, or 64-bit math (Chapter 4).
Chapter 4
Write GELU in CUDA, and map each thread to the element it owns
CUDA is NVIDIA's extension of C and C++ for GPUs. The lecture's simplified picture: you write f(i) for one index i, and the GPU runs it for every i. The code you write runs in one thread.
Threads come in blocks, and the blocks of one launch form a grid. A block runs on one SM, where its threads can share memory and wait for each other. Each thread reads three built-in numbers: its block's index blockIdx.x, the threads per block blockDim.x, and its own index in the block threadIdx.x. Call them b, D and t. The element i that the thread owns is:
i equals b times D, plus t.
blockIdx.x: 0 up to the number of blocks minus 1.blockDim.x: 1,024 in the lecture.threadIdx.x: 0 to D minus 1.Skip b whole blocks of D threads each. Then step t more. That position is the thread's element i.
With D = 1,024, thread 5 of block 2 owns i = 2 × 1,024 + 5 = 2,053. The lecture's tensor has 268,435,456 elements, so its launch needs 262,144 blocks.
cuda __global__ void gelu_kernel(float* in, float* out, int num_elements) { int i = blockIdx.x * blockDim.x + threadIdx.x; // the element this thread owns if (i < num_elements) { // the last block can run past the end out[i] = 0.5 * in[i] * (1.0 + tanh(0.79788456 * (in[i] + 0.044715 * in[i] * in[i] * in[i]))); } } // launch: cdiv(n, 1024) blocks of 1024 threads, where cdiv(a, b) = (a + b - 1) / b gelu_kernel<<<num_blocks, block_size>>>(x.data_ptr<float>(), y.data_ptr<float>(), num_elements);
The launcher rounds the block count up, so the last block can hold threads past the end. The if (i < num_elements) guard stops them.
Each cell is one element; its colour band shows its block. The yellow line is the end of the tensor. Drag its size and pick the block size. Tap a cell to see its index sum, then switch the guard off.
A toy grid: real launches use D = 1,024 and hundreds of thousands of blocks. Past the end, an unguarded thread reads and writes memory that belongs to something else.
The lecture's CUDA GELU took 1.66 ms of GPU time. That beats the manual 7.67 ms but not PyTorch's 0.70 ms: 1.29 TB/s, 39% of the bandwidth. Two differences stand out in the source. In C, a literal such as 0.5 is a double, so each thread does its math in 64-bit floats; 0.5f would keep it in 32-bit. And each thread loads one float, while PyTorch's kernel, vectorized_elementwise_kernel<4, …>, loads several at once. The lecture did not time either change.
Symptom: wrong values, or a crash, only when n is not a multiple of the block size.
Measure: run with CUDA_LAUNCH_BLOCKING=1, as the lecture does, so the error points at the kernel that caused it.
Fix: guard every thread with if (i < n).
Chapter 5
Write one program for a block of elements, and let the compiler choose the threads
Triton is a language for GPU kernels, written in Python, which OpenAI released in 2021. Its idea, from the lecture: think about thread blocks, not threads. A Triton program handles a whole block of elements as one vector, and the compiler turns it into threads.
| Job | CUDA | Triton |
|---|---|---|
| Memory coalescing (loads from DRAM) | manual | automatic |
| Shared memory management | manual | automatic |
| Scheduling within SMs | manual | automatic |
| Scheduling across SMs | manual | manual |
Three calls do most of the work. tl.program_id(0) gives the program's index, pid. offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) names its elements. tl.load and tl.store move them, and mask = offsets < n switches off the lanes past the end. BLOCK_SIZE must be a power of two, because tl.arange requires it.
Who are the threads, then? The lecture prints the PTX, NVIDIA's GPU assembly, that Triton made for its GELU. It asks for 128 threads per block (.reqntid 128): 4 warps, Triton's default. Call the block size S and the warps per program w. The elements per thread e are:
e equals S over thirty-two times w.
num_warps: 4 by default.Multiply the warps w by 32 to get the threads in a program. Share the program's S elements among them.
S = 1,024 and w = 4: e = 1,024 / 128 = 8. The PTX confirms it. Thread 5 loads elements 20 to 23 with one 128-bit load, and elements 532 to 535 with a second.
The lecture calls this thread coarsening: each thread does more elements, so the GPU spends fewer instructions per element. CUDA gives you one thread per element unless you write the loop yourself.
Top: n = 1,300 elements cut into programs; the mask switches off the grey lanes. Bottom: one program's elements, with one thread's share lit. Pick the block size and the warps, then drag the thread.
For BLOCK_SIZE 1,024 and 4 warps, the layout is the one in the lecture's PTX: runs of 4 floats per load. For the other settings we keep that pattern; the compiler may choose another one.
Symptom: a Triton kernel does not compile with BLOCK_SIZE = 1,000.
Measure: tl.arange needs a power of two.
Fix: round up with triton.next_power_of_2, and mask the extra lanes.
Chapter 6
Load once, keep every step in registers, store once, and watch for overflow
GELU, the Gaussian error linear unit, multiplies x by the chance that a standard normal number falls below x. That needs the error function, so many models use the GELU paper's tanh approximation (Hendrycks and Gimpel, 2016). The lecture uses it, as PyTorch's gelu(x, approximate="tanh") does. Call the input x and the inner argument a:
GELU of x is about one half x, times one plus tanh of a; and a is the square root of two over pi, times x plus 0.044715 x cubed.
Cube x, scale it by 0.044715 and add x. Multiply by 0.7979 to get a. Take tanh of a, add 1, and multiply by half of x.
x = 1: a = 0.7979 × 1.044715 = 0.8336, tanh(a) = 0.6824, so GELU ≈ 0.5 × 1.6824 = 0.8412. The exact GELU is 0.8413. Over all x, the gap is at most 0.00047, at x = 2.70.
Triton's math functions include exp but not tanh, so the lecture writes tanh with exp. Start from tanh(a) = (ea − e−a) / (ea + e−a), and multiply the top and the bottom by ea:
tanh of a equals e to the 2a minus 1, over e to the 2a plus 1.
tl.exp(2 * a), used twice.Compute e to the 2a once. Subtract 1 from it for the top, add 1 to it for the bottom, and divide.
a = 0.8336: e2a = 5.297, so tanh(a) = 4.297 / 6.297 = 0.6824, the value above.
python @triton.jit def triton_gelu_kernel(x_ptr, y_ptr, num_elements, BLOCK_SIZE: tl.constexpr): pid = tl.program_id(axis=0) offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < num_elements x = tl.load(x_ptr + offsets, mask=mask) # one read from HBM a = 0.79788456 * (x + 0.044715 * x * x * x) # every line from here to the store exp = tl.exp(2 * a) # stays in registers tanh = (exp - 1) / (exp + 1) y = 0.5 * x * (1 + tanh) tl.store(y_ptr + offsets, y, mask=mask) # one write to HBM # launch: one program per 1,024 elements triton_gelu_kernel[(triton.cdiv(n, 1024),)](x, y, n, BLOCK_SIZE=1024)
Nothing returns to HBM until the store: 2 passes. In the lecture's profile, triton_gelu_kernel took 0.705 ms, within 1% of PyTorch's 0.702 ms. In the PTX, tl.exp becomes ex2.approx, a fast base-2 exponential.
Left: the GELU curve and your x. Right: each register's float32 value. Drag x past 10, then switch to the safe form of tanh.
The page rounds each step to float32, as a GPU register would. The GPU's fast exp and division may move the edge a little; the NaN itself follows from IEEE float32.
The identity has a trap in float32. Its largest number is 3.4 × 1038, whose natural log is 88.7. Once 2a passes 88.7, e2a becomes infinity, which happens at x ≈ 10.06. Then the top and the bottom are both infinite, and infinity over infinity is NaN. The lecture tests with random normal inputs, which almost never reach 10.
Symptom: NaN in the activations after a custom GELU, only for large inputs.
Measure: test x = ±20, not only random normals. In NumPy float32, the lecture's form gives NaN from x ≈ 10.06.
Fix: write tanh(a) = 1 − 2 / (e2a + 1). When e2a is infinite it gives 1; when e2a is 0 it gives −1.
a, exp and tanh live?Chapter 7
Hand plain PyTorch to the compiler, read the kernel it writes, and pay its first-call cost
The fifth way to write GELU is no kernel code at all. torch.compile(manual_gelu) captures the Python function and passes it to its default backend, Inductor, which writes Triton kernels for GPUs. The profile of the compiled GELU shows one kernel: triton_poi_fused_add_mul_tanh_0.
The name reads as a sentence. poi is short for pointwise, and fused_add_mul_tanh lists the operators it merged. The compiled softmax got triton_red_fused_div_exp_max_sub_sum_0: a reduction kernel with all five softmax steps inside. Their GPU times were 0.707 ms and 0.731 ms.
Compiling costs time once, on the first call. Call the compile time tc, the eager time per call te, and the compiled time per call tk. Compiling pays off after N* calls:
N-star equals t-c over t-e minus t-k.
Each call saves t-e minus t-k. Divide the one-time cost t-c by that saving. After N-star calls, the compile has paid for itself.
The lecture's stopwatch: te = 8.10 ms and tk = 1.47 ms, so each call saves 6.63 ms. With a made-up tc = 10 s, N* = 10 / 0.00663 = 1,508 calls. A training run makes far more calls than that.
Two lines of total time as calls add up. Drag the compile time. Then add a new input shape halfway through, which compiles again.
Per-call times are the lecture's stopwatch for manual and compiled GELU. Compile times are made up: they depend on the model, the machine and the cache.
A new input shape can trigger a recompile. By default PyTorch notices that a size changed and compiles a more general kernel on that recompile. And mode="reduce-overhead" replays the work with CUDA graphs, a recorded sequence of kernels launched with one call. That is the fix for the launch-bound MLP of Chapter 2. PyTorch's docs warn that it can use more memory.
Symptom: a compiled model is slow for its first steps, or slow again when the batch shape changes.
Measure: log recompiles with TORCH_LOGS=recompiles, and leave the first call out of benchmarks.
Fix: warm up, and keep shapes stable or mark them dynamic.
Chapter 8
Fuse a reduction: give each row its own program and keep the row on chip
GELU treats each element alone. Softmax does not: each output needs its whole row, for the row's largest value and for its sum. The lecture follows Triton's fused-softmax tutorial.
Call a row's scores xj, the row's largest score m, and the outputs yj. Each output is:
y-j equals e to the x-j minus m, over the sum over k of e to the x-k minus m.
Find the row's max m. Subtract it from every score x-k and take e to that power. Divide each result by their sum.
The lecture's row 0, 0, 100: m = 100, so the terms are e−100, e−100 and 1, and y ≈ (3.7 × 10−44, 3.7 × 10−44, 1). Without the shift, e100 = 2.7 × 1043 overflows float32 and the last output is NaN. In exact math the shift changes nothing: it divides the top and the bottom by em.
Top: the scores, their exponentials and the outputs, in float32. Bottom: the kernels and passes over memory. Pick a row, then switch the shift and the fusion.
The first two rows are the lecture's example; the third is ours. Kernel times are the lecture's profiler rows for a 16,384 × 16,384 float32 matrix on the H100.
Eager softmax runs 5 kernels: max, subtract, exp, sum and divide. For an M by N matrix, the Triton tutorial counts 5MN + 2M element reads and 3MN + 2M writes. A fused kernel reads MN and writes MN, so the ratio is (8MN + 4M) / 2MN, about 4. The lecture's code comment says 5MN + M reads; its own line-by-line counts add to 5MN + 2M.
The Triton kernel runs one program per row: row_idx = tl.program_id(0), with BLOCK_SIZE = next_power_of_2(N). It loads with other=float("-inf"), so masked lanes never win the max and add e−∞ = 0 to the sum. In the profile, the 5 eager kernels took 3.26 ms and the Triton kernel 0.705 ms: 4.6 times less. PyTorch's softmax took 1.14 ms here, and the compiled one 0.731 ms.
Symptom: rows longer than a block can hold: the kernel spills registers, slows down, or does not compile.
Measure: BLOCK_SIZE × 4 bytes per program: 64 KB of registers across 128 threads at N = 16,384.
Fix: loop over the row in tiles with a running max and sum: the online softmax of Lecture 5, Chapter 8.
tl.exp?Chapter 9
Run a chain of kernels on a CPU and GPU timeline, fuse it, and change the size until the bottleneck flips
Every chapter in one tool. The CPU queues kernels one after another. The GPU starts a kernel after its launch and after the kernel before it. Each kernel's GPU time is its passes over memory at 3.1 TB/s, the rate the lecture's kernels reached. Pick a chain, a way to write it, and a tensor size.
Top lane: CPU launches. Bottom lane: GPU kernels; gaps are idle time. Pick the chain and how to write it, then drag the size and the launch cost.
A model, not a measurement: each kernel moves its passes at 3.1 TB/s with a 2 µs minimum; the launch cost is made up (the lecture's profiler logged 15 to 19 µs for single launches). Built-in ops: x + bias, F.gelu, + r, F.softmax.
Things to try. Manual GELU on 228 floats: 9 kernels, 7.7 ms, and the GPU is busy almost the whole time. Drag the size down to 214. Now the CPU's launches set the pace, and the GPU sits idle most of the time. Fusing helps at both ends: fewer bytes when the tensor is large, fewer launches when it is small. Then switch on the CUDA graph to see the small case recover.
Check yourself before you drag. At 10 µs per launch, a kernel hides its launch only if it runs longer than 10 µs. A two-pass kernel moves 8 bytes per element, so it needs n > 10 µs × 3.1 TB/s / 8 ≈ 3.8 million elements, about 222.
Chapter 10
Keep the numbers, the pass counter in code, and the checks that find a slow kernel
Measure first: synchronize, warm up, repeat, then sweep one knob. Profile to see the kernels, and divide each kernel's bytes by its time. Elementwise chains are memory-bound, so fusing them into one kernel cuts time by the cut in passes. You can get that kernel four ways, and on the lecture's H100 three of them tied.
| Idea | Rule or number | Why it matters |
|---|---|---|
| Traffic | Q = (R + W) × n × b | manual GELU: 22 passes, 23.6 GB; fused: 2 passes |
| Honest timing | warm up, synchronize, 3 trials | without synchronize you time the queue, not the kernel |
| Scaling | grow one knob at a time | flat in batch and width: fixed costs, 443 µs per layer-step |
| Effective bandwidth | Beff = Q / t | the add of 2,048²: 2.94 TB/s, 88% of 3.35 |
| CUDA index | i = b × D + t, guard i < n | cdiv(n, D) blocks; the last one runs past the end |
| Triton program | offsets = pid × S + arange(S), mask | S must be a power of two |
| Coarsening | e = S / (32 × w) | 1,024 elements on 4 warps: 8 per thread |
| tanh from exp | 1 − 2 / (e2a + 1) | the lecture's form gives NaN from x ≈ 10.06 in float32 |
| Compile | N* = tc / (te − tk) | saves 6.63 ms per call on GELU |
| Fused softmax | one program per row, other = −∞ | 3.26 ms to 0.705 ms; 4 times fewer passes |
| Way to write GELU | Kernels | GPU time | Stopwatch |
|---|---|---|---|
| Manual PyTorch math | 9 | 7.67 ms | 8.10 ms |
PyTorch F.gelu | 1 | 0.702 ms | 1.11 ms |
| CUDA, one thread per element | 1 | 1.664 ms | 1.82 ms |
| Triton | 1 | 0.705 ms | 1.73 ms |
torch.compile | 1 | 0.707 ms | 1.47 ms |
The pass counter in code. We ran it on a CPU: it counts the operators PyTorch dispatches, which on a GPU are the kernels. It prints 9 kernels, 13 reads and 9 writes.
python import torch from torch.utils._python_dispatch import TorchDispatchMode class CountPasses(TorchDispatchMode): def __init__(self): super().__init__(); self.kernels = self.reads = 0 def __torch_dispatch__(self, func, types, args=(), kwargs=None): self.kernels += 1 # one operator, one kernel, one write self.reads += sum(isinstance(a, torch.Tensor) for a in args) return func(*args, **(kwargs or {})) def manual_gelu(x): return 0.5 * x * (1 + torch.tanh(0.79788456 * (x + 0.044715 * x * x * x))) with CountPasses() as c: manual_gelu(torch.randn(1024)) passes = c.reads + c.kernels print(c.kernels, c.reads, passes) # 9 13 22 print(passes * 16384**2 * 4 / 7.669e-3 / 1e12) # 3.08 TB/s, the lecture's 7.669 ms
torch.compile, mixed precision and profiling in practice.lecture_06.py, gelu.cu, and the trace with the H100 timings).Now teach it: press Present or Teach. Count the passes of the manual GELU aloud, explain why the stopwatch needs a synchronize, and map a thread to its element. Then go back to the race and predict, before you switch, which way's stopwatch time is furthest from its GPU time.