December 2026
After lots of fun tackling Anthropic's performance engineering take-home, I wanted to see what kind of speed-up we could achieve with kernel fusion on a model I knew well.

So I went back to the transformer LM we previously built from scratch and profiled it on a single RTX 4090 to see what opportunities existed.
I ended up writing a Triton attention kernel that gave us a 2.2x speedup on prefill inference, cutting processing time from 121.5 ms to 55.3 ms, and enabling training at longer sequence lengths.

Where was the GPU spending its time?
I started with our 129-million-parameter Transformer on a single RunPod RTX 4090 and timed it at several sequence lengths while holding the batch size at four.
I used two kinds of runs:
- CUDA synchronization - to measure how long a step took for each length, I warmed up the model and timed it with CUDA synchronization so the clock included the GPU finishing its work.
- NVidia Nsight trace - to understand what happened inside a step, I recorded a separate run with Nsight, which shows the kernels the GPU executed and how long each one ran.
Which kernels dominate wall-clock time?
The first thing I looked at was how much of the forward pass went into matrix multiplication.
forward | cuda (NVIDIA GeForce RTX 4090) | FP32
5 warm-up steps, 10 measured steps
Mean: 19.007 ms | sample std: 3.263 ms
Throughput: 53,875 tokens/sforward | cuda (NVIDIA GeForce RTX 4090) | FP32
5 warm-up steps, 10 measured steps
Mean: 80.770 ms | sample std: 1.155 ms
Throughput: 50,712 tokens/sAt 256 tokens, matmuls accounted for 73% of forward GPU time.

At 1,024 tokens, this fell to 46%, and operations like masked_fill_kernel and exp_kernel_cuda occupied a visible part of the timeline -- but these names reveal little about which lines of code actually made it expensive.

Spying on GPU kernels with Nsight
When recording the trace, I used NVTX to mark regions of model code with names I recognized, including the individual stages inside attention.
with nvtx.range("attention_softmax"):
attention_weights = basics.softmax(scores, dim=-1)
with nvtx.range("attention_values_matmul"):
return attention_weights @ VI could then match each GPU kernel to the call that launched it and sum the durations under the same label across all twelve layers -- while doing this one comparison stood out:

At 256 tokens, the GPU spent half a millisecond in softmax and half a millisecond in its two matrix multiplications combined.

At 1,024 tokens, softmax took 21 milliseconds while the two matmuls together only took 7.
Why was softmax taking so long?
What was surprising about the result is how little arithmetic softmax does relative to the operations on either side of it.
The first matrix multiplication compares queries with keys to produce a score for each pair of tokens.
Softmax turns each row of scores into weights, and the second multiplication uses those weights to combine the values.

Most of the arithmetic happens in the two matmuls, yet the GPU spent 3x as long on the step in-between them.
A closer look at our kernels
The trace showed our softmax running as several kernels -- one found the max of each row, another took exponentials, and later kernels summed and normalized results.
Each stage wrote intermediate values to GPU memory for the next one to read.

Before trying to fuse those operations, I wanted to know how much data we were passing back and forth.
Finding the bottleneck: memory
PyTorch's memory snapshots let me follow the largest individual allocations back to the lines that requested them.

At 512 tokens, the largest buffers in the training run came from the vocabulary logits and loss.
At 1,024 tokens, attention overtook them -- with four sequences, twelve heads, and a 1024x1024 matrix of four-byte scores per head: one attention buffer occupied 192 MiB.

That was the size of one intermediate, and several stages worked their way across tensors of that shape -- doubling the context length would quadruple the size of each one.
Could mixed-precision fix our problem?
Wondering if smaller tensors could solve our problem, I tried BF16 autocast, which lets PyTorch choose precision operation by operation.
At 1,024 tokens it brought peak training memory down from 10.90 GiB to 8.52 GiB -- but even though scores entered softmax in BF16, exponentiation and normalization still produced 192 MiB FP32 tensors.
Tokens per sequence | FP32 peak training memory | BF16 autocast peak |
512 | 5.02 GiB | 4.16 GiB |
1,024 | 10.90 GiB | 8.52 GiB |
Memory traffic might explain the slowdown
This brings us back to the 21 millisecond trace -- each softmax kernel read the previous kernel's output and wrote an intermediate for the next one.
With tensors this large, I suspected the GPU was spending a substantial part of that time moving scores through memory.

If we fused score calculation, softmax, and value aggregation into one kernel, we could use the scores where they were computed and avoid those round trips to global memory.
But how to do that when a full score matrix takes 4 MiB, far too large to keep in fast on-chip memory?
Bypassing memory constraints
Consider just one head processing one sequence.
At 1,024 tokens, it computes 1,024 x 1,024 scores. At four bytes per FP32 score, that's 4 MiB for one head.

The fast working storage available to a group of GPU threads consists of registers and shared memory. On the RTX 4090, a thread block can use at most 99 KiB of shared memory alongside its registers.
Even a single head's score matrix is too large to keep in that local working space.
FlashAttention to the rescue
In comes FlashAttention -- an improved attention algorithm which leverages a tiling approach we can borrow.

Typically we compute the full score matrix, scoring every query against every key before applying softmax and combining the values.
FlashAttention changes the order by working one tile at a time.
A tile is a rectangle of the score matrix. In our kernel, a single tile's rows represent 64 queries and columns represent 64 keys, so each tile contains 4,096 query-key scores.

At 1,024 tokens, that means working with 16 KiB of FP32 scores per tile, 256 times smaller than the head's full 4 MiB score matrix.
While those scores are still on chip, the kernel uses them to update a partial output (a running weighted sum), then discards to reuse the space for the next tile (the next 64 keys for the same queries).

There's one catch -- a query's final weight for any one key depends on every other key in the row.
So how can we use the first tile's scores when their final softmax weights depend on keys we haven't seen yet?
Softmax yoga
For each query, the numerator is the sum of each value multiplied by the exponential of its score.
The denominator is the sum of those same exponentials.

Each tile can contribute to both sums immediately, and the kernel can wait until the last tile to divide.
One wrinkle: softmax subtracts the largest score before taking exponentials for numerical stability.
Suppose the largest score in the first tile was 4, but the next tile contains a 6. Every earlier contribution used exp(score - 4) and now needs to use exp(score - 6).
But since the correction is the same for every earlier score, the kernel can merely multiply both running sums by exp(4 - 6) and continue, never having to retrieve the old scores.
With this we should be able to finally start our implementation.
Double-checking our math
Before writing our kernel, I wanted to check the part of the math I was most likely to get wrong: when a later tile introduced a larger score, did I rescale the earlier tiles' contributions correctly?
To do this I wrote the tile loop in ordinary PyTorch and compared its output with attention computed from the full score matrix.
With these in agreement, we can finally begin our fused Triton kernel.
Scaffolding our kernel
The high-level flow for injecting our kernel starts with the Transformer.
Every block already called self.attn(...) so I used that as the point for swapping implementations.
x = x + self.attn(self.ln1(x), token_positions)When running our benchmark script with --attention-backed triton, the code will replace each block's attn module with a wrapper that reuses the existing weights in each attention layer.
Our wrapper is a PyTorch module that will project the input into queries, keys, values, and apply RoPE just as before -- but then calls FlashAttentionTriton.apply which allocates the output tensor and launches flash_fwd_kernel (our Triton kernel written in the same Python file with the @triton.jit decorator) on the GPU.

The kernel will write its answer into that output tensor, and the wrapper will merge the heads and pass the result through the block's original output projection.
This gives the kernel a narrow job -- it receives queries, keys, and values that were already on the GPU, and just has to produce one attention output per query.
The first decision we have to make in Triton is how to divide that work.
Time to write some Triton
I gave each Triton program 64 query rows from one attention head, and made it responsible for finishing those rows.
At 1,024 tokens that gave the GPU 16 independent programs per head: each program loaded its queries once, then worked across the keys and values 64 at a time.
Here's the full Triton kernel:
It looks more complicated than it is, it's mainly setting up pointers, loading 64 queries, then looping over tiles of keys/values while tracking the running maximum so it can divide at the end.
Here's where the fusion happens in the kernel:
new_max = tl.maximum(row_max, tl.max(scores, axis=1))
probabilities = tl.exp(scores - new_max[:, None])
correction = tl.exp(row_max - new_max)
denominator = correction * denominator + tl.sum(probabilities, axis=1)
numerator = numerator * correction[:, None]
numerator = tl.dot(probabilities.to(v_tile.dtype), v_tile, acc=numerator)
row_max = new_maxAt this point in the loop, scores holds one tile of query-key scores, with future positions already masked. Each row has a running maximum, a denominator, and a numerator that accumulates its weighted values.
The last tl.dot is where scores start contributing to the attention output, for each query we want a weighted average of the value vectors.
The variable probabilities holds the weights for the current tile -- they're still unnormalized because we haven't seen all the keys yet, but we can use them to build two parts of the average:
tl.dot(probabilities, v_tile, acc=numerator)^ this multiplies each value vector by its weight and adds the result to the running numerator, while the denominator tracks the sum of those weights.
A concrete example
For a simple example, imagine a tile of two weights 1 and 0.5 and two values 4 and 10.
This tile contributes:
1 x 4 + 0.5 x 10 = 9 # Numerator
1 + 0.5 = 1.5 # DenominatorOnce we've added these contributions, we can discard the tile's scores and move on -- if a later tile changes the running maximum, we rescale both totals together.
Getting outputs
After the last tile, we divide the running numerator by the running denominator to get one output vector per query.
For each query, we (crucially) also save the log of the softmax normalizer.
During training, the backward pass can recompute a query-key score and recover its attention probability with:
exp(score - saved_log_normalizer)Meaning as long as we save the log normalizer we can safely discard the full row of probabilities.
Checking the causal mask
To test the causal mask, which ensures tokens only attend to itself and earlier tokens during next-token prediction in training (so we can't cheat), I set all queries and keys to zero so every pair got the same score, then numbered the values 0, 1, 2, etc.
Since softmax would give equal weight to every value the mask let through, each token should return the average of the values it can see, i.e. the first three outputs should be:

The same rule should hold as the kernel crosses from one tile to the next, and changing future keys/values should leave earlier outputs unchanged.
(Although is_causal will pretty much always be set as True in our language model, we kept the flag in our kernel for testing purposes)
—
With this, we have a forward pass that can be used for inference, while still preserving the values we need to recover attention probabilities for training's backward pass.
Did we drift numerically?
Before timing the new attention kernel, I wanted to know whether we inadvertently changed predictions.
I made two copies of the transformer with identical weights, gave them the same batch of four 512-token sequences, then ran three training steps side-by-side.

One copy used the original attention in ordinary, uncompiled PyTorch -- our reference.
I checked the model at three points:
- compared the logits after each forward pass
- compared the gradients after each backward pass
- compared the weights after AdamW updates
To calculate drift after three optimizer updates, I compared each named weight tensor (e.g. ffn.w1.weight) with its counterpart in the reference model, subtracting them entry by entry and taking the L2 norm of the difference (which combines all those differences into one magnitude).

Then I divided by the L2 norm of the reference weights at that same step to express the gap as a percentage -- of the 111 comparisons, the largest gap in our compiled Triton model was 0.1321%, in a weight matrix in the first layer's feed-forward network.
Compared with the eager original | Max logits gap | Max gradient gap | Max weight gap after 3 updates |
Compiled original | 0.64% | 1.57% | 0.1338% |
Compiled custom | 0.65% | 2.28% | 0.1321% |
I also ran the test with the original attention on both sides, compiling one copy and leaving the other in ordinary PyTorch (since compilation can also cause drift) -- which also yielded 0.1338% as the largest difference in the 111 comparisons, coincidentally also in the first layer's feed-forward network.
What did fusion buy us on its own?
At 8,192 tokens, the original attention forward pass took 2.62ms.
Our Triton kernel did the same work in 0.24ms, more than 10x faster, while peak forward allocation fell from 652 MiB to 5 MiB.

This was the result we'd hoped to see -- finding the intermediate to eliminate, figure out how the kernel could avoid storing it, with a measurable difference in memory and time.
The stronger comparison was against torch.compile -- PyTorch's compiler had already brought the original forward pass down to 0.68ms, and the custom kernel was still 2.8x faster.

These were isolated causal attention runs on one RTX 4090, with a batch size of one, head width 64 and BF16 inputs.
On that same workload, PyTorch's built-in scaled dot-product attention (SDPA) reached 0.12ms, which gives a sense of how much performance headroom remained.
On the other hand, the backward pass separately showed where our implementation needed work, with our backward pass taking 6.59 ms compared to the 1.89 ms compiled original, which helps explain why the 2,048-token training step took 15% longer even as peak memory fell by more than half.
Implementation | Forward | Backward | Forward + backward |
Original | 2.62 ms | 5.14 ms | 7.66 ms |
Compiled original | 0.68 ms | 1.89 ms | 2.53 ms |
Custom Triton forward | 0.24 ms | 6.59 ms | 6.81 ms |
PyTorch SDPA | 0.12 ms | 0.55 ms | 0.66 ms |
Did the whole Transformer get faster?
At 4,096 tokens, swapping the attention implementation gave us a 2.20x speedup -- cutting processing time from 121.5 ms to 55.3 ms.

Here's the comparison at 2,048 tokens, with four sequences per batch, BF16 autocast, and all three models compiled:
Attention implementation | Prefill time per batch | Full training step | Peak training memory |
Original | 39.5 ms | 153.3 ms | 14.99 GiB |
Custom Triton forward | 22.4 ms | 176.7 ms | 6.77 GiB |
PyTorch SDPA | 20.1 ms | 76.4 ms | 6.08 GiB |
Two things stood out to me -- first, our kernel sped up prefill inference by 1.77x, cutting the processing time from 39.5 ms to 22.4 ms, within 2.3 ms of SDPA.
The gain also grew with the problem we'd designed the kernel to solve -- at 512 tokens it saves just 0.31ms, while at 4,096 tokens it more than halved the time for the batch.
Second, the memory saving changed what I could train on this GPU:

At 2,048 tokens, the custom implementation freed up 8.23 GiB of peak training memory.
At 4,096 tokens, the original model ran out of memory while ours completed a training step.
That step took 555 ms compared to SDPA's 159 ms, so I'd still choose SDPA to train this model today, but getting a previously-impossible run to fit on the same 4090 was a big win.
What I'd optimize next
With our prefill reduction from 121.5 ms to 55.3 ms, the next thing I'd tackle follows from the part we left unfinished: the backward pass.
Our forward kernel discarded each tile after using it, but the backward implementation rebuilt dense matrices to calculate gradients.

I'd keep the forward path fixed and tile the backward pass so it can accumulate gradients as it goes -- our goal being 176.7 ms per step on the same 2,048 token training benchmark with an eye towards SDPA's 76.4 ms as a reach goal.