Contents
Last month, my teammate Swastic and I took on a task from CloudRift, the team behind Emmy. Emmy is a compiler that takes PyTorch code and turns it into GPU kernels, the small programs a GPU runs. Normally it does that by writing CUDA C++ and handing it to NVIDIA’s compiler, nvcc. The task was to skip that step and write PTX, the GPU’s assembly language, directly.
We ended up with a compiler whose kernels run about as fast as nvcc’s, and one of them runs faster. But the most interesting part wasn’t the speed. It was finding out which optimizations actually did anything, because a few of the classic ones made no difference at all. In this blog, I’ll explain how the compiler works from the ground up, follow a few kernels through it, and show what we measured.
A quick picture of how a GPU runs code
If you’ve written CUDA before, you can skip this part.
A GPU runs the same small program on thousands of threads at once. Threads are grouped into blocks (up to 1024 threads each), and inside a block, every 32 threads form a warp, which moves through the program together, one instruction at a time.
There are three kinds of memory that matter here:
- Global memory is big (gigabytes) but slow. Every input and output lives here.
- Shared memory is small (tens of kilobytes) but fast, and it’s shared by the threads of one block. Threads use it to work together.
- Registers are the fastest of all, but each thread only sees its own.
Every thread knows its own position: which block it’s in and its number inside that block. From those two numbers it works out which part of the data it should handle. That’s how one program, run by thousands of threads, covers a whole array.
What was the task?
Here’s what Emmy normally does:
PyTorch code --> Kernel IR --> CUDA C++ --> nvcc --> GPU binary
The Kernel IR is Emmy’s own description of a kernel. IR stands for intermediate representation: a structured, in-between form that’s easy for a compiler to read. It says which threads exist and what each one loads, computes and stores. Our job was to cut out the CUDA C++ step and go from the IR straight to PTX.
Why bother? Speed of compiling. According to CloudRift, going from PTX to a GPU binary is about 19× faster than running the whole nvcc pipeline. Emmy’s autotuner compiles thousands of versions of each kernel to find the fastest one, so that time adds up.
There were a few rules. The submission had to be a program you run as python compile.py kernel.ir.json > out.ptx. We couldn’t use Emmy’s own code generator or nvcc. And it was graded on hidden kernels from five categories: simple elementwise math, sums (reductions), fused kernels like softmax, matrix multiplies and attention. So it had to work on kernels we had never seen.
What is PTX, and what does ptxas do?
PTX is NVIDIA’s assembly language, but a virtual one. You can use as many registers as you like, and the same PTX works on many generations of GPUs. A tool called ptxas turns it into SASS, the real machine code for one specific GPU.
CUDA C++ --(nvcc)------------> PTX --(ptxas)--> machine code
Emmy IR --(our compiler)----> PTX --(ptxas)--> machine code
Keep one thing in mind, because it comes back later: ptxas is not a simple translator. It chooses the real registers, reorders instructions and does quite a lot of optimizing on its own.
What does the compiler get as input?
Here’s the IR for the simplest problem, adding two arrays:
Tile[a0] (N=64)
in0__u0 = load x0[((a0 * 2) + 0)]
in1__u0 = load x1[((a0 * 2) + 0)]
f32 v0__u0 = add(in0__u0, in1__u0)
in0__u1 = load x0[((a0 * 2) + 1)]
in1__u1 = load x1[((a0 * 2) + 1)]
f32 v0__u1 = add(in0__u1, in1__u1)
add[((a0 * 2) + 0)] = (v0__u0, v0__u1)
A Tile is a piece of parallel work. a0 goes from 0 to 63, and each thread gets a different value. So this says: 64 threads, and thread a0 adds elements 2·a0 and 2·a0 + 1 of the two arrays. Emmy has already decided how to split the work. A small meta.json file next to the IR tells us the rest, like the order of the kernel’s arguments and how many threads get launched.
How does the compiler work?
It reads the IR once, from top to bottom. Every kind of statement (Load, Assign, Loop, and so on) has its own function that writes the PTX for it.
Every name in the IR becomes either a register or a known constant. Constants stay constants, so (a0 * 2) + 0 becomes a single multiply and the + 0 just disappears. Every new value gets its own fresh register, and we leave it to ptxas to fit them into the real ones.
Example 1: adding two arrays
Let’s follow the IR from above into PTX. First, here’s what each thread has to do:
- Work out its number. With several blocks, a thread’s overall number is
block number × threads per block + its number inside the block. - Check that it has work. The launch has 256 threads, but there are only 64 pieces of work. Threads 64 to 255 must do nothing, or they would read and write memory that isn’t theirs. So every kernel starts with a check: if your number is too big, jump to the end.
- Find its data. Memory is just numbered bytes. A float takes 4 bytes, so element
iof an array sits atstart of the array + i × 4. - Load, add, store.
And here’s the PTX it becomes:
mad.lo.s32 %r5, %r4, %r6, %r1; // step 1: block * threads per block + thread
setp.ge.s32 %p1, %r5, 64; // step 2: is my number 64 or more?
@%p1 bra $L_exit; // then leave
mul.lo.s32 %r7, %r5, 2; // a0 * 2
mul.wide.s32 %rd4, %r7, 4; // step 3: element -> byte offset (x 4 bytes)
add.s64 %rd5, %rd1, %rd4; // start of array x0 + offset
ld.global.v2.f32 {%f1, %f2}, [%rd5]; // step 4: load two floats at once
...
add.f32 %f5, %f1, %f3;
add.f32 %f6, %f2, %f4;
st.global.v2.f32 [%rd7], {%f5, %f6}; // store two floats at once
One small trick: each thread reads two floats that sit next to each other, so the compiler loads both with one 8-byte instruction instead of two 4-byte ones. The GPU only allows that when the address is a multiple of 8, and the compiler can prove it here. The first element, a0 * 2, is always even, and an even element number times 4 bytes is always a multiple of 8. The arrays themselves start at a multiple of 256 bytes, because that’s how GPU memory gets handed out, so the full address is a multiple of 8 too.
Example 2: summing an array
Adding two arrays is easy because every thread works alone. Summing an array is harder: 1024 numbers have to end up as one, so the threads have to work together. Emmy does it with 128 threads in four steps:
- Each thread sums its own share. Thread 0 adds elements 0, 128, 256, … and thread 1 adds elements 1, 129, 257, … Each thread adds 8 numbers, so now there are 128 partial sums.
- Each warp combines its 32 sums. Threads in a warp can read each other’s registers directly with a shuffle instruction. Each thread adds the value from the thread 16 places away, then 8, then 4, 2 and 1. After those five steps, the warp’s total is in its first thread. There are 4 warps, so now there are 4 sums.
- Warps share through shared memory. The first thread of each warp writes its sum into shared memory. Then every thread waits at a barrier until all four are written.
- Combine the last four. The four sums are added, two at a time, and every thread reads the final total.
Here’s how that looks in PTX:
ld.global.f32 %f2, [%rd4]; // step 1: the thread's 8 loads, one after another,
add.f32 %f1, %f1, %f2; // each 128 elements (512 bytes) further on
ld.global.f32 %f3, [%rd4+512];
add.f32 %f1, %f1, %f3;
...
shfl.sync.bfly.b32 %f10, %f1, 16, 31, 4294967295; // step 2: get the value from 16 threads away
add.f32 %f11, %f1, %f10; // ... then 8, 4, 2, 1
...
st.shared.f32 [%r15], %f1; // step 3: write this warp's sum to shared memory
bar.sync 0; // wait for all warps
...
ld.shared.f32 %f1, [%r1]; // step 4: everyone reads the final total
Notice that step 1 has no loop. The IR has one, but every thread runs it exactly 8 times, so the compiler writes the 8 copies out one after another. That’s called unrolling, and it comes back later.
Example 3: matrix multiply
Multiplying two 512 × 512 matrices means each number in the input gets used many times. Reading it from slow global memory every time would be wasteful. So each block first copies a small square piece of each matrix (a tile) into fast shared memory, and then all its threads work from there. The copy uses cp.async, which copies in the background so the threads can keep computing while the next tile arrives.
Then each thread runs a loop of 64 steps, multiplying and adding values from the two tiles. Emmy asks for that loop to be unrolled, so the compiler writes out all 64 steps.
Each thread computes a 2 × 2 square of the output, so it keeps four running sums. In each of the 64 steps it reads two numbers from A’s tile (rows r and r + 1, column k) and two from B’s tile (row k, columns c and c + 1), then does four multiply-adds. Every value it loads gets used twice.
Here’s the useful trick. Every one of those addresses is a starting point plus a fixed number of bytes. The next number along a row is 4 bytes further, and the next row of a tile is 256 bytes further, because a row holds 64 floats. After unrolling, k is a plain number in each copy, so the compiler keeps each address in the form “register plus a constant” (this is called affine addressing). It computes the two starting points once, and every load after that just carries its constant inside the instruction:
ld.shared.v2.f32 {%f5, %f6}, [%r85]; // step 0: B[k, c] and B[k, c+1], one load
ld.shared.f32 %f7, [%r95]; // A[r, k]
fma.rn.f32 %f1, %f5, %f7, %f1; // sum(r, c) += A[r, k] * B[k, c]
fma.rn.f32 %f2, %f6, %f7, %f2; // sum(r, c+1) += A[r, k] * B[k, c+1]
ld.shared.f32 %f10, [%r95+256]; // A[r+1, k]: the next row, 256 bytes on
fma.rn.f32 %f3, %f5, %f10, %f3; // sum(r+1, c)
fma.rn.f32 %f4, %f6, %f10, %f4; // sum(r+1, c+1)
ld.shared.v2.f32 {%f13, %f14}, [%r85+256]; // step 1: B moves down a row, +256
ld.shared.f32 %f15, [%r95+4]; // A moves along its row, +4
...
All 192 loads of the 64 steps use just those two registers, and the constant costs nothing because the load instruction has room for it. Without this, every load would first need its own address arithmetic, a few integer instructions each, and together they’d outnumber the 256 multiply-adds that do the actual work.
What made it fast, and what didn’t?
The compiler has optimization levels, so we could switch off one optimization at a time, time the kernel, and look at the machine code ptxas produced. Here’s what we found:
| What we changed | Kernel | Result |
|---|---|---|
| affine addressing | matrix multiply | 68 → 21 µs |
| asking for 16 values at once | big array sum | 23 → 10 µs |
| unrolling attention’s inner loops | attention | 218 → 64 µs |
| moving loads out of loops | attention, matrix multiply | no change |
| fusing multiply and add | matrix multiply | no change |
The second row needs a word of explanation. Reading from global memory takes hundreds of clock cycles. If a thread asks for one number and waits for it before asking for the next, it spends nearly all its time waiting. If it asks for 16 numbers in a row and only then starts using them, the waits overlap. In the big sum, where each thread reads 512 numbers, that alone made the kernel more than twice as fast.
The attention kernel compares each query with every key, and four rows of the query need the same key values. Once the inner loops were unrolled, every address became a known offset, the shared key values were loaded once instead of four times, and many loads could be in flight together. nvcc keeps those loops as loops, and that’s why this kernel ends up faster than nvcc’s.
The last two rows surprised me. They’re the classic optimizations you’d find in any compiler textbook, and our PTX did look tidier with them. But the machine code came out the same either way, because ptxas already does both. We only kept the multiply-add fusion because it makes the PTX file smaller, and the grader rejects anything over 2 MB.
There was one more case like that. Merging pairs of loads made the matrix multiply go from 21 to 15 µs in an early version, matching nvcc. Later we simplified the index math, ptxas started merging those loads by itself, and now the machine code is identical with or without ours.
Why we made exp slower on purpose
PTX has no instruction for exp. Our first version used the GPU’s fast but slightly rough approximation. Swastic replaced it with an accurate one. It splits the input into a whole power of 2 and a small leftover, works out the small part with a short polynomial, and scales the result back up. He did the same for log.
That made kernels that use exp 20–40% slower. On my laptop’s RTX 3060, the attention kernel went from 1.59× faster than nvcc to 1.15× faster. We kept it anyway. nvcc builds Emmy’s code with the accurate exp, so with the rough version, part of our lead would have come from doing sloppier math. That’s not a fair race.
How did we test it?
We copied CloudRift’s grader so it could run on our own GPU, with the same inputs and the same allowed error. That way we could test as often as we liked.
Since the real grading used hidden kernels, we also made 51 extra problems with CloudRift’s own generator, like GELU, layer norm, batched matrix multiplies and attention with up to 512 keys. Everything passed, the 15 open problems and the 51 extra ones, on the grader’s RTX 5090 and on my RTX 3060.
A few more things that helped
- Checks against PyTorch itself. Swastic added tests that run real PyTorch code through Emmy and our compiler, then compare with PyTorch computing in high precision. These catch mistakes that are already in the IR, which a comparison against Emmy’s own CUDA can’t see.
- A tracer. It prints a kernel’s PTX with each IR statement written as a comment above the code it became. It was the most useful debugging tool we had.
- Safety nets. If the compiler hits an internal error at one optimization level, it quietly tries again at a simpler one. It does the same if unrolling makes the PTX bigger than 2 MB.
How fast is it?
Here are some numbers from the grader’s RTX 5090, compared with nvcc building Emmy’s CUDA for the same kernel. These were timed before the exp change.
| Kernel | ours | nvcc | |
|---|---|---|---|
| vector add | 3.09 µs | 3.10 µs | 1.01× |
| softmax | 3.04 µs | 3.07 µs | 1.01× |
| matrix multiply 512 | 15.0 µs | 15.0 µs | 1.00× |
| attention | 51.8 µs | 64.2 µs | 1.24× |
| big array sum | 10.1 µs | 8.96 µs | 0.89× |
| attention (128) | 37.5 µs | 29.3 µs | 0.78× |
Most kernels land within a few percent of nvcc, and across all 15 problems it averages out to about the same speed. The clear losses are the big sums and the second attention kernel.
What’s missing
All the math happens in 32-bit floats. 16-bit inputs are converted on the way in and rounded once on the way out. Tensor cores, the GPU’s special matrix-multiply units, work for one instruction shape, which Swastic added. Newer features like TMA aren’t supported, since none of the problems needed them. Next on my list are the slow sums and that second attention kernel.
What I took away
- Speed comes from memory, not math. What matters is how addresses are computed, how many loads are waiting at once, and what gets reused.
- Writing PTX by hand. I had tried my hand at assembly before, so PTX felt familiar: registers, loads and stores, compares and branches. What was new was writing one program for thousands of threads at once, and choosing which kind of memory each value lives in.
- Unrolling. It does more than save the loop’s own instructions. It lets each thread keep many loads waiting at once, and it turns every address into a starting point plus a constant.
- Overlapping memory and compute. In the matrix multiply,
cp.asynccopies the next tiles into shared memory in the background while the threads work on the current one, with room for three tiles at a time.
Credits
Thanks to CloudRift for building Emmy and running the hackathon.
The code is on GitHub, and so are the problems we worked on if you want to try writing one yourself.