Pidoku

Persistent Kernels and Megakernels

Module 25 Lesson 25.j 1h 15m Difficulty 5/5

Prerequisites 5.d, 5.f, 13.k, 25.b, 25.e


Before you start: words you need#

WordPlain meaning
Persistent kernelA kernel launched with about one CTA per SM (or per cluster) that loops over work items until none are left, instead of one CTA per work item.
Tile schedulerThe code inside a persistent kernel that decides which work item each CTA takes next.
MegakernelA persistent kernel that runs a whole sequence of different operations — a layer, or the entire model forward pass — in one launch.
Kernel boundaryThe end of one kernel and start of the next. Implies a grid-wide barrier (everything of kernel 1 finishes first), a launch gap and an HBM round trip for intermediate results.
StragglerThe last CTA of a kernel to finish. At every kernel boundary, all SMs wait for it.
Event counterAn integer in global memory that a task increments when it finishes; dependent tasks wait until it reaches a target. A fine-grained replacement for the kernel boundary.
PDLProgrammatic dependent launch: lets the next kernel start its preamble before the previous one has completely finished (25.a, 25.e).

1. What is it?#

The ordinary CUDA model is “launch a grid with one CTA per tile; the hardware schedules CTAs onto SMs; the kernel ends when all are done”. Two departures from it now matter for inference:

  1. Persistent kernels keep CTAs resident and loop over tiles. Every fast Hopper and Blackwell GEMM and attention kernel works this way (25.e): it amortises set-up (barrier initialisation, TMEM allocation, descriptor prefetch), overlaps one tile’s epilogue with the next tile’s mainloop, and controls tile order for L2 reuse.
  2. Megakernels extend persistence across operations: the whole decoder layer, or the whole forward pass, is one kernel whose SMs execute a schedule of tasks (matrix-vector products, attention, norms, all-reduces), synchronising through counters instead of kernel boundaries.

The best-known examples are Hazy Research’s Llama-1B megakernel (“Look Ma, No Bubbles!”, May 2025), the Mirage Persistent Kernel (MPK) compiler (OSDI 2026), and per-layer megakernels such as DeepGEMM’s Mega MoE (25.h).

Facts checked on 13 November 2026.


2. Why does it exist?#

Low-batch decode is a long chain of short, memory-bound kernels. A 1B-parameter model at batch 1 runs about 100 kernels per token, each a few microseconds long. At that scale, three costs that are negligible for big kernels become a large fraction of the step:

  • Launch gaps. Hazy Research measured about 2.1 µs per launch on a stream and about 1.3 µs inside a CUDA graph (5.f, 13.k). Graphs remove CPU cost, not the GPU-side gap.
  • Tail effects. Each kernel ends with SMs idle while the straggler finishes; then the next kernel’s prologue starts from cold.
  • Memory-pipeline bubbles. Kernel k + 1 cannot start loading its weights until kernel k ends, even though the weights do not depend on kernel k’s output. For a memory-bound model, idle HBM is lost time.

The Hazy Research megakernel reported Llama-3.2-1B forward passes under 1 ms on H100 and under 680 µs on B200 at batch 1, about 2.5× (H100) and 3.5× (B200) faster than vLLM and over 1.5× faster than SGLang, using 78 % of H100 memory bandwidth where the engines reached at most 50 % (authors' figures, May 2025, against engine versions of that time). MPK’s README claims 1.2–6.7× lower latency across its benchmarks. These are research results on small models at batch 1, but they show how much time is spent between kernels.


3. Simple analogy#

A relay race where every runner must wait at the line until all runners of the previous leg have finished, and then a whistle blows (the launch gap). With 132 runners per leg, the slowest one sets the pace, and nobody can even tie their shoes for the next leg early.

A megakernel turns it into a kitchen with tickets: each cook starts preparing the ingredients for their next dish as soon as their current one is plated (prefetching weights), and only waits for the specific sauce (input) the dish needs, signalled by a counter on the wall. No whistle, no waiting for the slowest cook in the room.


4. Tiny example: boundaries versus counters#

A simulation of one decode pass of a Llama-1B-sized model: 112 operations (16 layers × 7 fused ops) on 132 SMs. Each SM’s share of an operation streams weights (6.6 µs ideal, ±20 % per-SM variation) and then does a short tail that needs the previous operation’s output.

Go
// megakernel.go — one decode forward pass as ~100 dependent ops on 132 SMs:
// one kernel per op (grid-wide barrier + launch gap) versus a megakernel in which each SM
// starts loading its next weights early and waits only on a counter for its inputs.
package main

import (
	"fmt"
	"math/rand"
)

const (
	sms     = 132
	ops     = 16 * 7 // 16 layers x 7 fused ops (a Llama-1B-sized model)
	loadUs  = 6.6    // ideal time to stream one op's weights with all SMs (≈22 MB at 3.35 TB/s)
	tailUs  = 0.5    // per-task work that needs the previous op's output (norm, reduce, store)
	jitter  = 0.2    // ±20 % spread in per-SM load time (DRAM channels, L2 slices, clocks)
	graphUs = 1.3    // launch gap between kernels inside a CUDA graph (measured by Hazy Research)
)

func main() {
	rng := rand.New(rand.NewSource(7))
	task := func() float64 { return loadUs * (1 + jitter*(2*rng.Float64()-1)) }

	// One kernel per op: nothing of op k starts before every SM finished op k-1, plus a launch gap.
	perOp := 0.0
	for k := 0; k < ops; k++ {
		slowest := 0.0
		for s := 0; s < sms; s++ {
			slowest = max(slowest, task()+tailUs)
		}
		perOp += slowest + graphUs
	}

	// Megakernel: SM s may load op k's weights as soon as it finished its own op k-1 task;
	// only the tail waits for the counter "all of op k-1 done".
	free := make([]float64, sms) // when each SM finished its previous task
	prevDone := 0.0              // when the counter for op k-1 reached its target
	for k := 0; k < ops; k++ {
		done := 0.0
		for s := 0; s < sms; s++ {
			loaded := free[s] + task()
			free[s] = max(loaded, prevDone) + tailUs
			done = max(done, free[s])
		}
		prevDone = done
	}
	ideal := float64(ops) * (loadUs + tailUs)
	fmt.Printf("ideal (no stragglers, no gaps): %6.0f µs\n", ideal)
	fmt.Printf("one kernel per op:              %6.0f µs\n", perOp)
	fmt.Printf("megakernel with counters:       %6.0f µs  (%.2fx faster)\n", prevDone, perOp/prevDone)
}
ideal (no stragglers, no gaps):    795 µs
one kernel per op:                1086 µs
megakernel with counters:          824 µs  (1.32x faster)

The per-op version loses about 290 µs: 146 µs of launch gaps and the rest to waiting for the slowest SM at every boundary. The megakernel hides most straggler time because a fast SM is already streaming its next weights while the slow one finishes. The model ignores other real costs (instruction fetch, synchronisation overhead, the extra work of a generic interpreter), so treat 1.3× as the shape of the effect, not a forecast.


5. Technical explanation#

Persistent kernels, the general pattern#

grid = min(num_SMs [x CTAs per SM], num_work_items)       # or one cluster per SM group
cta_loop:
    item = scheduler.next(cta_id)          # static: cta_id + i*grid; dynamic: atomic counter or CLC
    if item is none: break
    do(item)                               # mainloop + epilogue, pipelined with the next item

Schedulers, from simplest to most adaptive:

  • Static round-robin: deterministic, no atomics; unbalanced if items differ in cost or some SMs are busy with another kernel (for example a concurrent communication kernel, 25.i).
  • Atomic work queue: each CTA does atomicAdd(&next, 1); balanced; nondeterministic order.
  • Cluster launch control (Blackwell): CTAs are launched normally, but a running CTA can cancel a not-yet-started one and take its work (clusterlaunchcontrol.try_cancel). It gets the load balance of a persistent kernel while still letting the hardware share SMs with other kernels. CUTLASS calls this the CLC dynamic persistent scheduler.
  • Stream-K / split-K for balancing within a single GEMM (25.e).

Costs of persistence. A persistent kernel occupies every SM for its whole lifetime, so it cannot overlap with other kernels unless it is told to use fewer SMs (DeepGEMM’s set_num_sms, FlashInfer’s and DeepEP’s SM counts). It also hides the GPU’s own scheduling, so bugs in its scheduler appear as hangs or unbalanced tails.

From persistent kernels to megakernels#

A megakernel adds three things:

  1. A task graph. The model’s operations are decomposed into tasks sized for one SM (a slice of a matrix-vector product, one head’s attention, one chunk of an all-reduce) with explicit dependencies.
  2. An in-kernel scheduler or interpreter. Hazy Research compiled a per-SM instruction list ahead of time in Python; an on-GPU interpreter executes it, with seven instruction types (fused RMSNorm/QKV/RoPE, attention, attention reduction, O-projection + residual, fused RMSNorm/up-gate/SiLU, down-projection + residual, final norm + LM head). MPK instead has worker CTAs and scheduler warps: schedulers track events and push ready tasks to workers’ queues at run time (mi.PersistentKernel(num_workers=96, num_local_schedulers=48, ...) in its README).
  3. Fine-grained synchronisation. Counters in global memory replace kernel boundaries. A task increments a counter when its output is stored; a dependent task spins until the counter hits its target. Splitting a counter per chunk (Hazy split the down-projection into four) lets consumers start on the first chunk before the last is done.

And one resource trick: shared-memory paging. The Hazy H100 kernel divides 213 KB of shared memory into 13 pages of 16 KiB; an instruction requests pages and releases them as soon as it can, and the interpreter hands released pages to the next instruction so its weight loads start early. That is the “fast SM starts loading early” behaviour of the simulation above.

What megakernels make hard#

  • Dynamic shapes. Batch size, sequence lengths, which experts are active: each changes the task graph. Research megakernels target fixed small batches; MPK’s tracking issue for MoE models (opened June 2025) was still open in November 2026.
  • Generality versus speed. An interpreter that can run any instruction pays for dispatch and register pressure (all instruction types share one register budget).
  • Integration. Engines own scheduling, KV cache management and sampling (16–18). A megakernel must take over the whole decode step, or be one fused piece inside it.
  • Debugging and profiling. One kernel in the profiler. MPK and Hazy both built in-kernel timeline profilers for that reason.
  • Multi-GPU. Communication must also become tasks (MPK supports multi-GPU; Hazy’s ThunderKittens has NVLink primitives), using the device-side layers of 25.i.

The middle ground engines actually use (late 2026)#

  • CUDA graphs for the CPU side (5.f, 13.k).
  • PDL to overlap each kernel’s prologue with the previous kernel’s tail (DeepGEMM set_pdl, CuTe DSL fp16_gemm_6.py).
  • Aggressive fusion (13.j): fused norm + quantise, fused all-reduce + norm (25.i), fused MoE pipelines and layer-level megakernels such as Mega MoE (25.h).
  • Persistent GEMM and attention kernels with dynamic schedulers.

Whole-model megakernels remain research or specialised deployments (fixed model, small batch, latency-critical) as of November 2026.


6. Under the hood: a counter-synchronised task#

// one worker CTA executing task t = (op = down_proj, rows r0..r1) of layer L
wait_until(counter[L].mlp_act[chunk_of(r0)] >= target)   // ld.acquire.gpu in a loop, with nanosleep
// weights for this task were already requested into free smem pages before the wait
compute matvec(rows r0..r1) using act from global/L2, accumulate residual
store out[r0..r1]
__threadfence()   (or st.release.gpu)                    // make the output visible before signalling
atomicAdd_release(&counter[L].down_done, 1)              // red.release.gpu.global.add

The memory-ordering pair is the correctness core: release on the producer’s increment, acquire on the consumer’s load. Without it, a consumer can see the counter before it sees the data. This is the same publish/subscribe discipline as the mbarrier phases of 25.a, at global-memory scope.


7. Performance implications#

  • Gains scale with the number of short kernels. Small models, batch 1–8, many layers: large wins. Large batches or large models make each kernel long, and boundaries become a small fraction.
  • The win is mostly bandwidth utilisation. Keeping HBM busy across operation boundaries is what takes a memory-bound decode from ~50 % to ~80 % of peak bandwidth in the Hazy result.
  • Persistent kernels need SM budgets when other work must run concurrently (communication, a second micro-batch).
  • PDL captures part of the benefit cheaply: prologue overlap and earlier weight loads (the next kernel can issue L2 prefetches before griddepcontrol.wait), without a megakernel.

8. Production implications#

  • Measure inter-kernel gaps first. In Nsight Systems, sum the idle time between kernels in a decode step under CUDA graphs. If it is under 5 %, megakernel-style work has little to win.
  • Prefer incremental fusion. Layer-level fused kernels (attention block, MLP or MoE block) capture most of the gain with far less integration risk than a whole-model megakernel.
  • Latency products are the use case. Voice, real-time agents and speculative-decoding drafters (where a small model runs at batch 1 on every step) are where megakernels pay off.
  • Determinism and debuggability change: dynamic schedulers reorder work; build tracing into the kernel, and keep a non-megakernel path for debugging and correctness comparison (28.b).

9. Common mistakes#

  1. Launching more persistent CTAs than SMs (or than fit with the kernel’s shared memory), so some CTAs never become resident and a spin-wait deadlocks.
  2. Spin-waiting without memory ordering (plain loads and stores for counters).
  3. Assuming CUDA graphs remove all launch overhead. They remove CPU overhead; GPU-side gaps of about a microsecond per kernel remain.
  4. Persistent kernels that starve concurrent kernels, such as an all-reduce on another stream.
  5. Static schedules for variable work (ragged attention, MoE), leading to long tails.
  6. Comparing a batch-1 megakernel with an engine tuned for throughput and concluding the engine is slow in general.

10. Hands-on exercise#

  1. In the Go simulation, set jitter to 0 and graphUs to 0. What remains of the megakernel’s advantage, and why? Then set ops to 7 × 80 and loadUs to 40 (a 70B-class model on 8 GPUs) and compare.
  2. Profile a batch-1 decode step of a 1B model in vLLM with CUDA graphs. Count kernels, total kernel time and total gap time.
  3. Clone the Mirage repository (mpk branch) and run its Qwen3-8B demo with and without --use-mirage on one GPU. Compare tokens per second and look at its profiler output.
  4. Write a toy persistent kernel (CUDA or Triton) that processes a list of variable-cost items with an atomic queue; compare its tail with a one-CTA-per-item launch.

11. Interview questions#

  1. What is a persistent kernel, and why are all fast Hopper/Blackwell GEMMs persistent?
  2. Compare static, atomic-queue and cluster-launch-control scheduling.
  3. Where does the time go between kernels in low-batch decode, even with CUDA graphs?
  4. How does a megakernel replace kernel boundaries, and what memory-ordering rules make that correct?
  5. Why do megakernels help memory-bound decode in particular?
  6. What makes megakernels hard to adopt in a general serving engine?
  7. When would you choose PDL plus fusion over a megakernel?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in