Fused sampling, and one benchmark harness for PyTorch, torch.compile, Triton and CUDA
Finish the kernel pack with a fused sampling kernel that turns logits into tokens in one pass using the Gumbel-max trick, with per-request seeds and no probabilities written to memory. Then run every kernel in the pack through one harness that checks each backend (eager PyTorch, torch.compile, Triton and hand-written CUDA) against eager, times them the same way, and reports bandwidth, FLOP rate and speed-up, so you can decide when a custom kernel earns its place.
By Sandip Maity, Applied AI Engineer
Key takeaways
- Sampling with probabilities softmax(logits / T) equals taking the argmax of logits / T plus Gumbel noise, so one pass with in-kernel random numbers replaces softmax, a cumulative sum and a search.
- Counter-based random numbers keyed by a per-request seed make each request's samples reproducible, whatever else is in the batch.
- A benchmark harness should check correctness before it times anything, use the same timer and inputs for every backend, and report achieved bandwidth or FLOP rate, not only milliseconds.
- Compare against torch.compile and the vendor kernel, not only eager PyTorch. A custom kernel earns its place where the compiler cannot fuse or the format is unusual.
- Report the GPU, versions and shapes with every number; kernel results do not carry over between GPUs.
Goal: write a fused sampling kernel, then put every kernel in this pack through one honest benchmark, and learn to read the result.
You need: the earlier lessons in this track, and a GPU for the timings (the free Colab T4 from getting a GPU is enough). The code is gpu_kernels/sampling.py, gpu_kernels/bench.py and gpu_kernels/cuda_kernels.cu in the companion repository.
Honest limits. We ran the harness in check-only mode on a CPU with Triton's interpreter; the output below is from that run. We have not run its timings on a GPU for this page, so it shows no speed numbers: those are yours to measure, and they will differ by GPU, driver and versions. The two CUDA kernels' device code compiles with nvcc 12.8 for a T4 (sm_75), but neither the kernels nor their PyTorch wrapper have run on a GPU here.
#Fused sampling with the Gumbel-max trick
The usual way to sample one token from logits at temperature : compute , then draw from (torch.multinomial, which builds a cumulative sum and searches it). For a batch of 64 requests and a vocabulary of 128,256 tokens in float32, the logits are 32.8 MB, and that path reads and writes vocabulary-sized tensors several times.
The Gumbel-max trick does it in one read. Draw independent uniform numbers in and set , standard Gumbel noise. Then
So the kernel only has to add noise and track a running maximum: one pass over the logits, nothing written but the chosen token. Temperature 0 means greedy: no noise, plain argmax.
gpu_kernels/sampling.py · MIT licensed, on GitHub
"""Fused temperature sampling in Triton with the Gumbel-max trick.
Sampling token i with probability softmax(logits / T)_i is the same as taking
argmax_i(logits_i / T + g_i), where each g_i = -log(-log(u_i)) and u_i is uniform in (0, 1).
So one pass over the logits, with random numbers made inside the kernel, replaces
softmax + cumulative sum + search, and never writes probabilities to memory.
One program per row (request). It walks the vocabulary in blocks and keeps a running
maximum and its index. Temperature 0 means greedy (no noise). Each row has its own seed,
so a request's samples are reproducible whatever else is in the batch.
Runs on a GPU, or on a CPU with TRITON_INTERPRET=1 set before importing triton.
"""
import torch
import triton
import triton.language as tl
@triton.jit
def _gumbel_sample_kernel(logits_ptr, temp_ptr, seed_ptr, out_ptr, stride, V,
BLOCK: tl.constexpr):
row = tl.program_id(0)
temp = tl.load(temp_ptr + row)
seed = tl.load(seed_ptr + row)
greedy = temp == 0.0
inv_t = tl.where(greedy, 1.0, 1.0 / tl.where(greedy, 1.0, temp))
best_val = -float("inf")
best_idx = 0
for v0 in range(0, V, BLOCK):
cols = v0 + tl.arange(0, BLOCK)
mask = cols < V
x = tl.load(logits_ptr + row * stride + cols, mask=mask, other=-float("inf")).to(tl.float32)
u = tl.rand(seed, cols) # counter-based: same seed, same numbers
u = tl.minimum(tl.maximum(u, 1e-10), 1.0 - 1e-7) # keep log(-log(u)) finite
g = -tl.log(-tl.log(u))
score = tl.where(greedy, x, x * inv_t + g)
score = tl.where(mask, score, -float("inf"))
blk_val = tl.max(score, axis=0)
blk_idx = tl.argmax(score, axis=0) + v0
take = blk_val > best_val
best_idx = tl.where(take, blk_idx, best_idx)
best_val = tl.where(take, blk_val, best_val)
tl.store(out_ptr + row, best_idx)
def sample(logits, temperature, seeds, block=1024):
"""logits: [B, V]; temperature: [B] float32 (0 = greedy); seeds: [B] int32. Returns [B] int64."""
B, V = logits.shape
logits = logits.contiguous()
out = torch.empty(B, dtype=torch.int64, device=logits.device)
_gumbel_sample_kernel[(B,)](logits, temperature, seeds, out, logits.stride(0), V, BLOCK=block)
return out
def sample_reference(logits, temperature, generator=None):
"""The usual unfused way: softmax, then a multinomial draw (greedy where T == 0)."""
out = torch.empty(logits.shape[0], dtype=torch.int64, device=logits.device)
greedy = temperature == 0
out[greedy] = logits[greedy].argmax(dim=-1)
if (~greedy).any():
probs = torch.softmax(logits[~greedy].float() / temperature[~greedy, None], dim=-1)
out[~greedy] = torch.multinomial(probs, 1, generator=generator).squeeze(1)
return outPale bar: softmax probability. Solid bar: share of your draws (0 so far). Draw to see the noisy scores.
Each draw adds independent Gumbel noise −log(−log u) to logits ÷ T and picks the largest. Over many draws the counts match softmax(logits ÷ T). Temperature 0 means greedy: no noise. Random numbers come from your browser.
The rest is Pro
Keep reading this full lab
Pro unlocks this full lab, every advanced lesson, the hands-on labs and completion certificates.
One year
$25
365 days, no auto-renewal
Lifetime Best value
$75
pay once, keep it forever
7-day refund, no questions asked. One payment, no auto-renewal.Compare plansHave a licence key?
Not ready? Keep learning free
Not ready? Take the free 5-day email course
One short email a day for five days, each built on a free lesson, then the occasional new lesson or offer. Unsubscribe in one click.
Still to come in this lab
- One harness for four backends
- What you can now do
- Common mistakes
- Exercise
- Going deeper
You will be able to answer
- Why does adding Gumbel noise and taking the argmax give a sample from the softmax?
- Why give each request its own seed instead of one seed for the batch?
- Your Triton kernel is 3x faster than eager PyTorch but the same speed as torch.compile. What should you conclude?