Phase 02/Writing and measuring kernels/CUDA programming
PHASE 02 · Writing and measuring kernels

CUDA programming

0%
8 h6 subtopics3 lessons · 2 required
In plain English

CUDA is the language for giving instructions to the canteen of junior cooks from the first topic (the GPU's thousands of simple workers). A CUDA program has two halves. The host half runs on your normal computer and acts like a site manager, reserving space on the GPU, shipping data over, and shouting "go" with a chosen number of teams and workers. The device half, the kernel, is the short instruction sheet every worker follows. Because the manager shouts "go" and immediately walks away, you also need ways to know when the workers have finished (synchronisation) and ways for workers on the same team to wait for each other before sharing results. This topic gets you writing, compiling and debugging that two-halves program on a free cloud GPU.

Why it matters

vLLM, SGLang and TensorRT-LLM all ship custom CUDA kernels, and PyTorch itself is a thin layer over them. You need to write a kernel end to end once to read theirs with confidence and to understand what asynchronous launches and streams mean for latency measurements.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Write, compile and run a complete CUDA C++ program with nvcc.
  • Allocate device memory, copy data both ways and check errors from every API call.
  • Launch kernels with the triple-chevron syntax and explain that launches are asynchronous.
  • Use __syncthreads, cudaDeviceSynchronize and streams correctly.
  • Bind a custom kernel into PyTorch with load_inline and compare against a native op.

Key concepts

Host and device
The CPU side (host) and GPU side (device) of a program; __global__ marks a function the host launches on the device.
Kernel launch
kernel<<<gridDim, blockDim, sharedBytes, stream>>>(args); enqueues work and returns immediately.
cudaMalloc / cudaMemcpy
Allocate device memory and copy between host and device; copies on the default stream block the host.
cudaDeviceSynchronize
Host waits until all previously launched device work has finished; needed before timing or reading results.
__syncthreads
Block-level barrier; all threads in the block wait and shared memory writes become visible.
Stream
An ordered queue of device work; separate streams can overlap copies and kernels.
CUDA event
A marker recorded into a stream, used for accurate device-side timing.
Atomic operation
Read-modify-write that is safe when many threads hit the same address, for example atomicAdd.

Subtopics

  1. 1. Anatomy of a CUDA program

    Host code, __global__ kernel, __device__ helpers, nvcc compilation, -arch flags, and the generated PTX/SASS.

  2. 2. Memory management and error checking

    cudaMalloc, cudaMemcpy, cudaFree, unified memory with cudaMallocManaged, and a CUDA_CHECK macro around every call.

  3. 3. Kernel launches and asynchrony

    Launch configuration, dynamic shared memory, why the host returns immediately, and the resulting timing pitfalls.

  4. 4. Synchronisation

    __syncthreads, cudaDeviceSynchronize, cudaStreamSynchronize, events, and atomics for cross-block reductions.

  5. 5. Reductions and scans

    Tree reduction in shared memory, warp shuffle intrinsics, and the two-pass pattern for cross-block sums.

  6. 6. Calling CUDA from PyTorch

    torch.utils.cpp_extension.load_inline, accessing tensor data pointers, and checking numerical agreement with torch ops.

Resources

documentation
course

Hands-on lessons

L1

Your first nvcc program on Colab - SAXPY with error checking and event timing

Colab T4 · freenotebook90 minrequired

Goal · A complete saxpy.cu that compiles with nvcc, checks every API call, times the kernel with CUDA events and reports achieved bandwidth.

  1. 1On a Colab T4, run !nvcc --version and !nvidia-smi to confirm the toolchain.
  2. 2Use %%writefile saxpy.cu to write host code that allocates x and y of 1<<26 floats, fills them, copies to the device.
  3. 3Write the __global__ saxpy kernel with a grid-stride loop; launch with 256 threads per block.
  4. 4Wrap every cuda* call in a CUDA_CHECK macro that prints cudaGetErrorString and exits; also call cudaGetLastError after the launch.
  5. 5Record cudaEvent_t before and after the launch, cudaEventSynchronize, compute elapsed ms and GB/s (3 x n x 4 bytes).
  6. 6Copy y back and verify every element equals a*x+y within 1e-6; print max error.
  7. 7Compile with !nvcc -arch=sm_75 -O3 saxpy.cu -o saxpy and run; then deliberately pass a block size of 2048 and observe the launch error message.
Deliverable
saxpy.cu plus the printed bandwidth and max-error lines.
Check
Max error is 0; achieved bandwidth is at least 180 GB/s on a T4; the 2048-thread launch is caught and reported by CUDA_CHECK rather than silently producing garbage.
Fallback
Kaggle T4, or compile with nvcc on any rented single GPU; the code is identical.
L2

Block reduction with shared memory and atomics

Colab T4 · freenotebook90 minrequired

Goal · A sum-reduction kernel that uses a shared-memory tree within each block and atomicAdd across blocks, matching the CPU sum.

  1. 1Write reduce.cu where each block loads its slice into a __shared__ float array.
  2. 2Implement the tree reduction with a for loop halving the stride and __syncthreads() between steps.
  3. 3Thread 0 of each block atomicAdd's the block result into a single device float.
  4. 4Verify against a double-precision CPU sum over 1<<24 random floats; report absolute and relative error.
  5. 5Remove the __syncthreads() and rerun several times to show the result becomes wrong and unstable.
  6. 6Replace the final tree levels with __shfl_down_sync warp shuffles and compare timings with CUDA events.
Deliverable
reduce.cu with timings for the tree version and the shuffle version.
Check
Relative error below 1e-5 with synchronisation; at least one incorrect result in five runs without it; the shuffle version is not slower than the tree version.
Fallback
Kaggle T4; or implement the same tree reduction in the fake_cuda.py simulator from p2-cuda-thread-hierarchy-l1 to check the logic.
L3

Bind a CUDA kernel into PyTorch with load_inline

Colab T4 · freenotebook75 minoptional

Goal · A custom fused "x * sigmoid(x)" (SiLU) CUDA kernel callable from PyTorch that matches torch.nn.functional.silu and is timed against it.

  1. 1Write the kernel and a C++ wrapper that takes a torch::Tensor, checks it is CUDA and contiguous, and launches over numel().
  2. 2Load it with torch.utils.cpp_extension.load_inline(name, cpp_sources, cuda_sources, functions).
  3. 3Compare the output with F.silu on a 1e7-element float32 tensor using torch.allclose.
  4. 4Time both with torch.cuda.Event over 100 iterations after warm-up; report microseconds and GB/s.
  5. 5Add a float16 path and show the bandwidth roughly doubles because fewer bytes move.
Deliverable
Notebook with the kernel source, allclose result and timing table.
Check
torch.allclose passes with atol=1e-6 for float32; your kernel is within 1.5x of the PyTorch op's time.
Fallback
Run on Kaggle; or read the equivalent kernel in PyTorch's ATen source and annotate it instead.

Build your own

Build your own CUDA softmax and layernorm kernels

CUDA C++Colab T4 · free~7 h

Row softmax and layer normalisation written in CUDA, bound into PyTorch with load_inline, verified against F.softmax and F.layer_norm on GPT-2 shapes and timed against them, ending with a fused residual-add-plus-layernorm.

The real thing: github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/cuda/SoftMax.cu ↗

How you know a stage passes

Write tests/test_kernels.py first. Each test compiles the extension with torch.utils.cpp_extension.load_inline, runs it on random tensors with GPT-2 row widths (768, 1024, 3072 and 50257 for the vocabulary), asserts torch.allclose against the torch reference at the stated tolerance, and times both with torch.cuda.Event (median of 50 after 10 warm-ups). Run `pytest -q` on a Colab T4; a stage is done when its test passes and the earlier ones still pass.

Stages, in order. Each one leaves you with something that runs.0/7
  1. 01bind one elementwise kernel
    A tanh-approximation GELU kernel with a C++ wrapper that checks the tensor is CUDA, contiguous and float32, loaded via load_inline and callable as mykernels.gelu(x).
    test · torch.allclose with F.gelu(x, approximate='tanh') at atol 1e-6 on 1e7 floats; passing a CPU tensor raises a RuntimeError from your check.
  2. 02naive row softmax
    One thread per row doing three passes (max, exp-sum, normalise) in fp32; correct for any row length.
    test · allclose at atol 1e-6 against F.softmax(dim=-1) for 4096 rows x 1024; the time ratio to torch is printed (expect it to be much slower).
  3. 03one block per row with shared-memory and shuffle reductions
    A 256-thread block per row computes the row max and sum with a shared-memory tree finished by warp shuffles, using the online max-and-sum update so the row is read twice, not three times.
    test · allclose at atol 1e-6; at least 20x faster than s2 on 4096 x 1024 and within 2x of F.softmax.
  4. 04warp per row and the vocabulary softmax
    A dispatcher picks a warp-per-row kernel for rows up to 1024 and a block-per-row grid-stride kernel for long rows such as 50257; both handle lengths that are not multiples of 32.
    test · allclose for row lengths 64, 768, 1000 and 50257; achieved bandwidth (read plus write bytes / time) for 64 rows x 50257 is at least 60 percent of your measured copy bandwidth.
  5. 05layer normalisation
    One block per row computes mean and variance in fp32 (Welford or two-pass), applies gamma and beta, and matches torch's eps handling.
    test · allclose at atol 1e-5 against F.layer_norm for 8192 x 768 and 8192 x 3072; within 1.5x of torch's layer_norm time.
  6. 06fused residual add plus layernorm with fp16 I/O
    A kernel that returns both h = x + residual and LN(h) in one pass, with float16 inputs and outputs and fp32 arithmetic inside.
    test · allclose at atol 1e-5 in fp32 and 1e-2 in fp16; the fused kernel is at least 1.3x faster than torch's separate add followed by layer_norm at 8192 x 768.
  7. 07package and benchmark
    A mykernels package built with torch.utils.cpp_extension.load from csrc/ files, plus bench.py writing bench.md with kernel, shape, your microseconds, torch microseconds and GB/s.
    test · `pytest -q` passes every test; `python bench.py` writes bench.md and every kernel is within 2x of its torch counterpart.

Knowledge check

QWhy does timing a kernel with Python's time.perf_counter around the launch give a tiny, wrong number?

The launch is asynchronous and returns immediately; you must synchronise (cudaDeviceSynchronize or an event) before stopping the timer.

QWhat is the maximum number of threads per block, and what happens if you exceed it?

1024 on all current GPUs; the launch fails with cudaErrorInvalidConfiguration, which you only see if you check cudaGetLastError.

QWhy is __syncthreads() needed between loading a tile into shared memory and reading it?

Threads run at different speeds; without the barrier a thread may read a shared-memory slot another thread has not yet written.

QWhen is atomicAdd a reasonable choice and when is it not?

It is fine for a few thousand adds to one address (one per block); it serialises badly if every thread of a large grid hits the same address.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • All six subtopics marked completed.
  • saxpy.cu and reduce.cu saved with checks passing and bandwidth numbers recorded.
  • Can write a correct kernel launch, error check and event timing from memory.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →