Decode Megakernels in 2026
Where the time goes in one GLM-5.3 decode step, and how SGLang, vLLM, TensorRT-LLM and research groups win that time back
If you have read anything about serving large language models, you have probably heard that decoding for a single user is memory-bound. The GPU has to read every weight it needs once per step, but it only multiplies those weights by a handful of tokens. So, a step should take about as long as reading its bytes at full memory bandwidth.
Let's check that on a real setup. I served GLM-5.3, a 78-layer Mixture-of-Experts model, from its NVFP4 (4-bit) checkpoint on one machine with eight B300 GPUs. Tensor parallelism split the model over all eight, and speculative decoding drafted 3 tokens per step. In that setup, each GPU reads about 13 GB of weights per decode step. At the B300's peak memory bandwidth of 7.67 TB/s (the peak implied by its memory bus width and clock; NVIDIA quotes 8 TB/s), that takes 1.71 milliseconds. Stock SGLang, meaning SGLang without any megakernel, takes 7.32 milliseconds per step.
To close that gap, SGLang, vLLM and TensorRT-LLM have all started to ship model-specific "megakernels" for small-batch decoding over the past few weeks. SGLang keeps them in a separate repository, sgl-nvidia-mega; vLLM has merged "specialized decode" paths for Kimi K3 and DeepSeek-V4.1-Flash, with more in open pull requests; and TensorRT-LLM has per-model targets (implementations of one model's decode step for a given setup) in its new modeling_v2 package. Before any of them, research groups showed that a whole model can run as a single kernel. The name is used loosely: some megakernels are one kernel for a whole model, while others, including the one we will take apart, are several large kernels per layer. With sgl-nvidia-mega's GLM-5.3 megakernel, the step above takes 4.76 milliseconds, from the same checkpoint and with the same arithmetic up to rounding (section 8), so the server produces 1.54 times as many tokens per second.
What do these megakernels do, and where do the 5.6 milliseconds above the memory floor go? In this article, I first take apart the GLM-5.3 megakernel and measure where its 2.6 milliseconds of saving come from, one stage of a layer at a time. Then, with that picture in mind, we will go through the others: GLM-5.3 in vLLM, in a second sgl-nvidia-mega megakernel and in TensorRT-LLM; DeepSeek-V4.1-Flash, Kimi K3, GLM-5.3-Flash and Qwen3.5; and the research megakernels that came first. At the end, I look at Flapping Airplanes' new megakernel framework, which runs training, inference and a game in one kernel, and guess at how it might work.
Everything I say about how they work comes from their source code and pull requests, which I link along the way. The measurements are my own, from the machine above, on a development build that adds a few unpublished changes to sgl-nvidia-mega's GLM-5.3 megakernel. Its code is public in pull requests #19 and #24, and what I describe about how it works is in that public code. For the other projects, I quote the numbers they report.
I'll limit the scope to decoding with one to four users, which is what most of these megakernels target, and mention larger batches only in passing. I won't cover prefill or expert parallelism (except for a short note on DeepGEMM's Mega MoE), and I won't go into the details of how the kernels are written or how they plug into each engine.
1. One Decode Step of GLM-5.3
1.1 What a Step Does
GLM-5.3 is a Mixture-of-Experts (MoE) model with 78 decoder layers. Each layer has an attention module and an MoE module with 256 routed experts, of which the router picks 8 per token, plus one shared expert that every token goes through. (The first 3 layers use a dense feed-forward network, or MLP, instead of the MoE.) The attention is Multi-Head Latent Attention (MLA), as in DeepSeek-V3, and like DeepSeek-V3.2's, it is sparse: a small module called the indexer picks the 2,048 most relevant earlier tokens, and the attention only looks at their entries in the KV cache (the stored keys and values of earlier tokens). Figure 1 below shows every operation of one layer for one token, with the shapes from the checkpoint.
The names in Figure 1 are the ones that the code uses, and I'll use them too. q_a and kv_a compress the hidden state, q_b expands the compressed query into heads, and W_UK and W_UV are the two halves of MLA's up-projection, which are folded into the query and the output so that the attention can work directly on the compressed 576-value cache entries.
With speculative decoding, a small draft model (here the checkpoint's multi-token prediction or MTP layer, a single extra layer) guesses the next 3 tokens, and the target model then checks all of them at once. A step starts with the target model running once over 4 tokens (the current token and the 3 guesses) and deciding how many guesses to keep. SGLang calls this the target verify. Then the draft model runs over the accepted tokens to catch up, which also gives it its first guess for the next step, and then runs twice more for the second and third guesses. In my runs, an SGLang setting (SGLANG_SIMULATE_ACC_LEN) fixes the average number of tokens per step at 2.99, so that stock SGLang and the megakernel produce the same number of tokens per step and only the time of a step differs. Figure 2 below shows the order of the passes.
With tensor parallelism over 8 GPUs, each GPU holds one eighth of most weight matrices. Each GPU computes a partial result, and twice per layer, after the attention and after the MoE, the 8 partial results have to be added up across the GPUs before any GPU can continue (the dark boxes in Figure 1). This collective sum is called an all-reduce. I cover it in detail in How GPUs Talk to Each Other During LLM Inference, but you don't need that article to follow this one.
In a profile of one GPU, the 78 layers take 6.48 of the 7.34 milliseconds of a stock step, and 4.03 of 4.69 with the megakernel. (Profiled times differ slightly from the served times above.) The layers are therefore almost the whole step, and they are also where 93 percent of the saving is. Everything else gets about a fifth faster too: the draft passes; the multiplications by the output layer over the vocabulary, called the LM head; sampling; and bookkeeping. We will come back to it in section 7. Since the layers share one structure (apart from the first three, which are dense, and the 21 layers, those three included, that run their own indexer), we can look at a single layer for most of this article.
1.2 What a Step Should Cost
Before we look at the time, let's count the bytes, since they set a lower bound. For each GPU and each step, I added up the bytes of the weights that the step reads, using the shapes and data types in the checkpoint.
A layer's attention weights are stored in BF16, and they come to about 69 MB per GPU. Most of that is split across the GPUs, but one piece isn't: the first projection of the attention, which turns the 6,144-wide hidden state into the 2,048-wide query and 576-wide key inputs, is replicated, so every GPU reads all 32 MB of it in every layer. The routed experts are stored in NVFP4, 4 bits per weight plus one 8-bit scale per 16 weights, so one expert takes 21.2 MB, or 2.65 MB per GPU. With 4 tokens, each of which picks 8 experts, a layer uses about 24 distinct experts on average (I measured that on real text; consecutive tokens often pick the same experts), so the MoE reads about 76 MB per GPU per layer, shared expert and router included.
The 78 layers, the three draft passes and the four multiplications by the LM head (over a 154,880-token vocabulary) add up to 13.1 GB per GPU per step. At 7.67 TB/s, reading that takes 1.71 milliseconds, and stock SGLang takes more than four times as long.
1.3 Where the Stock Time Goes
I expected the stock profile to show idle time, since a step that takes four times as long as its memory traffic needs suggests a GPU that waits for the CPU to launch work. SGLang, however, records each part of the step as a CUDA graph and replays the graphs, so the launches are cheap, and in the median step the GPU is idle for only 50 microseconds of the 7.34 milliseconds.
The GPU is busy more than 99 percent of the time. What is it busy with? Let's zoom in on one layer of the target verify. Figure 3 below shows every kernel that stock SGLang runs for one layer (one without its own indexer), drawn to scale, with the megakernel's kernels for the same layer underneath.
A note on how the boxes are measured: kernels overlap in both paths (section 2.1), so a kernel's own duration overstates its cost. In Figure 3, I charge each kernel only the time between the latest end of any kernel launched before it and its own end, so that the boxes add up to the time of the layer. Kernels that run entirely in the shadow of others get a width of zero. In stock SGLang, these are three of the shared expert's four kernels (which run on a second stream), the quantization of the MoE input to NVFP4, and one of the two RMSNorms (root-mean-square normalizations).
The first thing to notice in Figure 3 is how many boxes there are and how small each one is. Stock SGLang runs 22 kernels for this layer, and the median layer takes 77.7 microseconds. Reading the weights of one layer (and the attention's KV cache entries) at full bandwidth takes 19.5 microseconds, so 58 of those 77.7 microseconds go to something other than reading weights. Each kernel is a general-purpose one built to be fast on large inputs: a matrix multiplication (GEMM) from cuBLAS, an attention kernel from TensorRT-LLM, a norm from FlashInfer. My reading of the profile is that with 4 tokens, each of them finishes its work quickly, and most of its time goes into getting started, loading its first data and winding down, which the next kernel then has to wait for.
The second thing to notice is that the layer falls into four stages, which I have bracketed in Figure 3:
- The attention input: the projections, norms and position encoding that turn the hidden state into the query and the new entry of the KV cache.
- The indexer (on 21 of the 78 layers) and the sparse attention itself.
- The attention output: the projection back to the hidden size, the all-reduce, the residual add and the norm, and the router that picks the experts.
- The MoE: the routed and shared experts, the step that combines their outputs, and the second all-reduce.
The megakernel runs the same four stages with 8 kernels instead of 22, in 46.9 microseconds, and spends 27 microseconds beyond the time it takes to read the weights. Sections 3 to 6 go through the stages one at a time, but first, let's go over two ideas that recur across them.
2. Two Recurring Ideas
2.1 Starting Early
Normally, a kernel on a CUDA stream starts only after the previous kernel on that stream has finished. Since the Hopper generation (H100), there is a way around this called programmatic dependent launch (PDL). A kernel launched with it may start while the previous kernel is still running, as soon as that kernel signals that its dependents may launch, with the PTX instruction griddepcontrol.launch_dependents. (The megakernel's kernels mostly issue it at their start.) The new kernel then has to execute griddepcontrol.wait before it reads anything that the previous kernel writes, and that wait returns once the previous kernel has finished and its writes are visible.
On its own, PDL only hides the launch latency. What matters is what a kernel does between its start and its wait. A kernel in a decode step reads two kinds of data: the activations, which the previous kernel produces, and its weights, which never change. The weights can be read before the wait. So, the megakernel's kernels start by loading their weights (into shared memory, into registers, or only into the L2 cache) while the previous kernel is still finishing, and only then wait for their input, as illustrated in Figure 4 below. Some go one step further and ask the L2 cache to fetch the weights of a kernel that comes later in the layer.
We can see this in the profile. The megakernel's first attention kernel runs for 11.2 microseconds in the median layer, but it only adds 4.4 microseconds to the layer. It starts while the kernel before it is still running (the fold at the end of the previous layer, section 6.3, which does an all-reduce and spends much of its time waiting for the other GPUs), and it reads its weights in the meantime.
The engine megakernels in section 10 that I read follow this rule, and vLLM's notes for GLM-5.3-Flash state it as an invariant (TMA is the GPU's bulk-copy engine):
Load weights before the PDL wait. Kernels issue their weight TMA or register loads before
griddepcontrol.wait; activations only after. A new kernel that waits first loses most of its gain at 1-8 tokens.
Starting early isn't new, though: many of stock SGLang's kernels use PDL too. The 22 kernels of a stock layer run for 126 microseconds in total, but the layer only takes 77, so they overlap quite a bit (part of that is the shared expert on its second stream). The megakernel's 8 kernels run for 73 microseconds, and the layer takes 47. In both cases, the kernels' run time is about 1.6 times the layer's time, so the megakernel doesn't overlap its kernels more than stock SGLang does. What it changes is how many kernels there are and what each of them does while it waits.
2.2 The All-Reduce in a Mailbox
The second idea is about the two all-reduces per layer. Stock SGLang already uses a fast all-reduce for small messages: a one-shot kernel from FlashInfer. Each GPU reads its partial result from memory and writes it into a buffer on every GPU, with one multicast store that NVLink delivers to all eight. Then it waits until the other 7 partials have arrived in its own buffer, adds the 8 of them up, adds the residual and applies the norm, all in the same kernel. That is already a lean design, and it adds about 6 microseconds to the layer each time it runs.
The megakernel does the same exchange but moves it into the kernels on either side of the all-reduce, so that no kernel does only the all-reduce. Each GPU has a mailbox in memory that all 8 GPUs can write to. The kernel that produces a partial result writes it into all 8 mailboxes as it goes, in 64-bit records that each hold three BF16 values and a 16-bit tag. (For the MoE, that kernel is the one that combines the experts' outputs, as section 6.3 shows.) The tag is the number of the current all-reduce (an epoch), so that a GPU can tell a fresh record from one left over from an earlier layer. The next kernel, the one that needs the sum, reads its own mailbox, waits until every record carries the current tag, and adds the 8 partials in a fixed order, GPU 0 first, as shown in Figure 5 below. Most of the saving comes from the other work that this next kernel does, as sections 5 and 6 show.
The fixed order matters, and FlashInfer's kernel keeps one as well. Floating-point addition isn't associative, so if two GPUs added the partials in different orders, they could end up with slightly different hidden states, then route a token to different experts, and drift apart.
The other projects in section 10 have their own versions of this mailbox: Lamport buffers (a record counts once it no longer holds a sentinel value) in TensorRT-LLM and in vLLM's DeepSeek-V4.1-Flash path, and flag-in-data mailboxes in vLLM's GLM-5.3 path, which are the same idea as the tags here.
The mailbox has two more details worth knowing. First, every wait for another GPU has a deadline. If a GPU doesn't see its records in time, the kernel logs an error and traps, which stops the server instead of leaving it hanging. Second, a mailbox slot is only reused after every GPU has acknowledged that it has read the slot's previous contents.
The mailbox doesn't remove the cost of the exchange itself. In my traces, the fold spends 2 to 2.5 of its roughly 7 microseconds polling for the other GPUs' records, which covers the slowest GPU finishing its part and the records crossing NVLink. We will come back to the exchange at the end, since it is the largest piece of what is left.
With these two ideas in place, let's go through the four stages of a layer.
3. Stage 1: The Attention Input
3.1 What Stock SGLang Runs
The attention of GLM-5.3 starts by compressing the hidden state. One projection, which SGLang runs as a single fused GEMM, turns the 6,144 values of each token into a 2,048-wide query input and a 576-wide key input (512 latent values plus 64 for the position encoding). Both get an RMSNorm. The second projection, q_b, then expands the query input into the 8 attention heads that this GPU owns. Since MLA computes the attention against the compressed 512-wide latent cache instead of full keys, each head's query is also multiplied by an absorbed key matrix (W_UK) to bring it into that latent space. Finally, the rotary position embedding (RoPE) is applied, the query is quantized to FP8 to match the FP8 KV cache, and the new tokens' latents and position keys are written into the cache.
In stock SGLang, that is 7 kernels: the fused GEMM, two RMSNorms, the q_b GEMM, the absorption as a batched GEMM, one kernel for RoPE and quantization, and one that writes the cache entry. Together, they add 17.6 microseconds to each layer.
3.2 What the Megakernel Runs
The megakernel does the same work in 2 kernels, as shown in Figure 6 below.
The first kernel is a GEMM built for a handful of tokens. Each streaming multiprocessor (SM) gets a contiguous block of the output values and the whole 6,144-wide input, so that no two SMs ever have to add up their results, and the weights are packed so that each SM reads one unbroken piece of memory. On the 21 layers with their own indexer, the same launch also computes the indexer's key projection and per-head weights, which stock SGLang runs as a separate GEMM.
The first kernel also takes over part of the RMSNorm before it. The kernel that ends the previous layer (the fold; see section 6.3) hands over the hidden state multiplied by the norm's weights, but not yet divided by its root mean square. It also hands over the sums of squares that the division needs, and the GEMM applies the division to its 32-bit results before it rounds them to BF16. Since a token's scale factor can be pulled out of a matrix multiplication, this computes the same quantity, and the fold doesn't have to finish the norm itself. The rounding happens at a different point from stock SGLang, though, so the results here can differ from SGLang's in the last bits.
The second kernel, which the megakernel calls the MLA prologue, does everything else: both RMSNorms, the q_b projection, the W_UK absorption, RoPE, the FP8 quantization, and the writes into the KV cache (and, on indexer layers, it also finishes the indexer's key and writes it into the indexer's own cache). It runs as 9 thread-block clusters (groups of SMs that can read each other's shared memory) of 8 SMs each. Each of the first 8 clusters handles one attention head, and each of its SMs computes a slice of that head's query. The SMs of a cluster exchange their slices through each other's shared memory instead of through global memory. The ninth cluster writes the cache entries.
3.3 What It Waits For
Both kernels load their weights before their PDL wait. For the first, that is the replicated 32 MB projection, which takes 4.2 microseconds to read at 7.67 TB/s. The W_UV kernel of the previous layer (we will meet it in section 5) already asks the L2 cache for the first 8 MB of it, and the kernel streams in the rest while the fold before it is still waiting. As we saw in section 2.1, it adds only 4.4 microseconds to the layer. The prologue reads much less (about 10 MB) and adds 5.2 microseconds, so memory isn't its limit; it is probably limited by its chain of dependent steps.
The stage goes from 17.6 to 9.6 microseconds per layer.
4. Stage 2: The Indexer and the Sparse Attention
4.1 Choosing 2,048 Tokens
GLM-5.3 uses DeepSeek Sparse Attention (DSA). Before the attention runs, the indexer (section 1.1) scores every earlier token with low-precision FP8 dot products and keeps the 2,048 with the highest scores. The attention then only reads those 2,048 entries of the KV cache, however long the context is. In GLM-5.3, only 21 of the 78 layers have their own indexer (layers 0, 1 and 2, then every fourth layer from 6 to 74), and the layers in between reuse the selection of the most recent indexer layer, as illustrated in Figure 7 below.
The indexer is the part of the layer that the megakernel changes least. In stock SGLang, it takes 7 kernels:
- a GEMM for the indexer's query projection, split over the input dimension, plus a kernel that adds up the pieces;
- a GEMM for its key projection;
- one kernel that finishes the query (RoPE, a Hadamard rotation and FP8 quantization);
- one that finishes the key and writes it into the indexer's own cache;
- the scoring, a DeepGEMM kernel;
- and the top-2,048 selection, an SGLang kernel.
The megakernel computes the key projection in the same launch as the attention's first GEMM and finishes the key in the prologue, as we saw in section 3, and it replaces the query projection and its finishing kernel with one kernel of its own. The scoring and selection kernels are unchanged, and they take about as long as before.
On the 21 layers with their own indexer, the indexer goes from 21.6 to 16.4 microseconds per layer, and almost all of that saving comes from the projections. The selection kernel alone adds about 8.5 microseconds to the layer, more than any other kernel except the MoE engine of section 6, which makes it the next candidate for a replacement.
4.2 The Attention Over the Selected Tokens
The attention itself changes much more. With 4 tokens and 8 heads per GPU, the kernel computes, for each of the 4 queries, 8 dot products of 576 values against each of the 2,048 tokens that the query selected, runs a softmax over the scores, and adds up the 2,048 latent vectors weighted by the softmax. That is little arithmetic but a lot of separate tokens to fetch, since each token's cache entry sits somewhere else in memory.
Stock SGLang runs this with a sparse decode kernel from TensorRT-LLM's attention library, which adds 11.7 microseconds to each layer. The megakernel's attention kernel splits each query's 2,048 tokens over a cluster of 16 SMs, 128 tokens each, as illustrated in Figure 8 below.
Each SM fetches its 128 cache entries with bulk copies (one per entry), computes the scores with FP8 tensor-core instructions, and keeps a partial result: the largest score it saw, the sum of the exponentials, and the weighted sum of its 128 latent vectors. A partial result like that can be merged with another one by rescaling both to the larger maximum, which is the same online-softmax merge that FlashAttention uses across blocks. Every SM owns 32 of the 512 output values (for all 8 heads), and it pushes the other SMs' values of its partial result, together with its largest score and sum, directly into their shared memory. Each SM then merges the 16 partials for its 32 values in a fixed order. The merge therefore never goes through global memory, and the result for one token doesn't depend on how many other tokens the step has.
With 4 queries, 64 SMs each do a little work and finish together. The stage (without the indexer) goes from 11.7 to 6.4 microseconds per layer. Since the attention only reads 2,048 cache entries of 576 bytes per query, at most 4.7 MB per layer for all 4 queries, it isn't limited by memory bandwidth. It is probably limited by the latency of the scattered loads and by the merge.
5. Stage 3: The Attention Output, the All-Reduce and the Router
5.1 What Stock SGLang Runs
After the attention, each GPU holds a 512-wide latent result for each of its 8 heads. Stock SGLang turns it back into a 256-wide value per head with a batched GEMM (the other half of the absorbed MLA projections, W_UV) and projects the 8 × 256 values to the 6,144-wide hidden size with the output projection (o_proj). Then it runs the all-reduce with the residual add and the next RMSNorm. Then the router, a small GEMM with 256 outputs, scores the experts for each token.
That is 4 kernels, and together they add 17.7 microseconds to each layer. The output projection is the only part with a sizable weight: 25 MB per GPU, since o_proj is split across the 8 GPUs along its input dimension. That split is why the all-reduce is needed: each GPU's o_proj produces the full 6,144 values of each token, but only from its own 8 heads.
5.2 What the Megakernel Runs
The megakernel runs this stage as three kernels, shown in Figure 9 below.
The first kernel computes the W_UV projection and also prepares the next kernel: before its PDL wait, it tells the L2 cache to fetch most of the next kernel's o_proj weights, so that they are already on chip by the time they are needed.
The second kernel computes this GPU's partial o_proj result on 128 SMs, each of which owns 48 of the 6,144 output values and keeps its slice of the weights in registers, loaded before the PDL wait. As each SM finishes its 48 values, it writes them into the mailboxes of all 8 GPUs, as described in section 2.2. The third kernel waits for the 8 partials, adds them up in rank order, adds the residual, and applies the RMSNorm.
The interesting part is the router. The router's scores depend on the normed sum, so they seem to need the all-reduce first, as one more step in the chain. But the router is a linear map, and all that the norm does to a token's hidden state is multiply it by fixed weights and by one number, the reciprocal of its root mean square. So, the router's matrix product can move in front of the sum; only the scaling has to wait. Here is the idea with toy sizes in NumPy:
import numpy as np
rng = np.random.default_rng(0)
gpus, d_in, hidden, experts = 8, 16, 24, 6
a = rng.standard_normal((gpus, d_in)) # attention output, per GPU
w_o = rng.standard_normal((gpus, hidden, d_in)) # o_proj slice, per GPU
res = rng.standard_normal(hidden) # residual
gamma = rng.standard_normal(hidden) # RMSNorm weights
w_r = rng.standard_normal((experts, hidden)) # router weights
# stock: all-reduce, residual add, RMSNorm, then the router
h = sum(w_o[r] @ a[r] for r in range(gpus)) + res
rstd = 1 / np.sqrt(np.mean(h**2) + 1e-5)
stock = w_r @ (h * rstd * gamma)
# megakernel: each GPU sends its share of the scores with its partial
w_p = w_r * gamma # router times norm weights
w_ro = [w_p @ w_o[r] for r in range(gpus)] # fixed, built at load time
share = [w_ro[r] @ a[r] for r in range(gpus)]
mega = rstd * (sum(share) + w_p @ res) # rstd still needs the sum h
print(np.allclose(stock, mega)) # True
In GLM-5.3, each of the fixed matrices w_ro[r] is 256 × 2,048 (256 experts by this GPU's 8 heads × 256 values), and the megakernel builds them when the model loads. Each GPU computes its share of the router scores straight from its attention output, on 16 more SMs of the o_proj kernel, and writes it into the mailboxes along with its partial result. (The residual's part is split over the GPUs as well, each GPU taking 768 of the residual's 6,144 values.) The third kernel then adds up the 8 shares in rank order, multiplies by the token's scale factor, which it has just computed for the norm, and picks the 8 experts in one warp (32 threads) per token, with the same selection rule as SGLang's routing kernel. The scores themselves are added up in a different order than in stock SGLang, so they can differ in the last bits.
As a result, the routing is done by the time the all-reduce is. The router GEMM and the routing kernel both drop out of the chain.
5.3 What It Waits For
Much of this stage is the exchange between the GPUs. The W_UV kernel adds 2.1 microseconds to the layer, the o_proj kernel 4.5 (its weights are mostly in L2 already), and the third kernel 4.0, which goes into waiting for the other GPUs' partials, adding them up, and finishing the norm and the routing. The stage goes from 17.7 to 10.6 microseconds per layer, and that includes the routing, which takes stock SGLang another 1.7 microseconds in the next stage.
6. Stage 4: The MoE
6.1 What Stock SGLang Runs
The MoE is the largest stage in both paths. In stock SGLang, the routed experts run in TensorRT-LLM's NVFP4 MoE kernels, as packaged in FlashInfer:
- a routing kernel that sorts the tokens by expert;
- a kernel that quantizes the MoE's input to NVFP4;
- a grouped GEMM for the first projection of every expert (gate and up, with the SwiGLU activation, the expert's gated nonlinearity, fused in);
- a grouped GEMM for the second projection;
- and a kernel that combines each token's 8 expert outputs with their routing weights (the finalize).
The shared expert runs in BF16 on a second stream, as two cuBLAS GEMMs (one of them split over two kernels) and an activation kernel, partly in parallel with the routed experts. Then the all-reduce adds up the 8 GPUs' outputs.
With 4 tokens, the grouped GEMMs work on tiles of 128 output values by 8 tokens, and most of each tile is empty, since an expert sees only one or two of the 4 tokens. That doesn't matter much for speed, since the weights dominate. What matters is that the stage is a chain of 6 kernels that add to the layer's time, each of which has to start and drain; together they add 30.7 microseconds to each layer.
6.2 The Engine
The megakernel replaces all of this with two kernels: the engine, and the fold after it, which also does the all-reduce. The engine's job is to read about 24 experts' worth of weights (64 MB per GPU, plus 9 MB for the shared expert) as fast as the memory allows, and to do the little arithmetic that 4 tokens need along the way.
To spread that evenly over the SMs, the engine cuts every expert into 4 quarters. With tensor parallelism, each GPU holds 256 of an expert's 2,048 intermediate values, so a quarter covers 64 of them: the gate-and-up weights that produce them (128 outputs, 64 for the gate and 64 for the up projection) and the matching part of the down projection, about 0.66 MB in NVFP4. A quarter can be computed on its own, since the down projection of a quarter gives a partial output that only has to be added to the other quarters' at the end. With about 24 experts, that makes about 96 work units. The shared expert, which is stored in BF16 and is therefore about 3.6 times as large per quarter, adds 4 more. The engine runs on 33 clusters of 4 SMs, 132 of the B300's 148 SMs. A table that the CPU computes once assigns the units to the clusters for every possible number of distinct experts: the 4 shared quarters go to clusters 0 to 3, and the routed units are dealt out to the other 29 clusters, 3 or 4 units each, as shown in Figure 10 below.
Within a cluster, the 4 SMs split each unit 4 ways again. For the first projection, each SM takes a 1,536-wide slice of the 6,144-wide input, so the 4 SMs then have to add up their results. Each SM sends its partial sums to the other three through their shared memory, and all four add them up in the same order, so that they end up with the same sums. Then each SM applies SwiGLU, quantizes the result to NVFP4 for the second projection, and computes a quarter of the 6,144 output values.
The order of the work within a cluster is what keeps the memory busy, as shown in Figure 11 below. The weights stream through a ring of 4 shared-memory buffers of 36 KB each. The kernel's warps have fixed roles: one warp issues the weight copies and another the copies of the scale factors, one issues the tensor-core instructions, and four compute the activation and write out the results. Let's call the gate-and-up projection FC1 and the down projection FC2. The order is FC1 of units 0, 1 and 2, then FC2 of unit 0, FC1 of unit 3, FC2 of unit 1, and then the remaining FC2s, so that the second projection of a unit runs two units behind its first. That way, the copy warps stream in the next units' weights while the other warps compute the current unit's activation.
6.3 The Combine Inside the All-Reduce
The engine doesn't combine the 8 expert outputs of a token. It writes each unit's partial output, as 32-bit floats, into a scratch buffer and leaves combining them to the fold. The fold reads the partials, adds up each expert's 4 quarters, rounds to BF16, multiplies by the routing weight, and sums the 8 experts and the shared expert, with the same rounding steps as SGLang's finalize kernel. Then it writes the sum into the mailboxes and finishes the all-reduce, as in section 2.2. It also leaves the norm half done, as we saw in section 3.2.
6.4 What It Waits For
The MoE is the one stage where the megakernel approaches the peak memory bandwidth. My traces show the engine streaming weights at about 7 TB/s in the middle of its run. What it loses is at the edges: about 1.6 microseconds at the start to read the routing and deduplicate the experts, about 1.5 at the end to drain, and some more because some clusters get 4 units and others 3, so the 4-unit clusters finish last. The stage goes from 30.7 to 20.2 microseconds per layer, with the routing moved to the previous stage.
7. Around the Layers: The Draft and the Step
So far, we have looked at the 78 layers, but a step also runs the draft model 3 times, multiplies by the LM head 4 times, and does some bookkeeping between these passes: sampling, deciding which guesses to accept, and preparing the next pass's inputs. In stock SGLang, all of that takes 853 microseconds per step, idle time included.
The megakernel covers parts of the draft layer as well, with three draft-side changes. The draft layer starts by looking up the token's embedding and normalizing it together with the previous hidden state, which the megakernel does in one kernel. Then a projection (eh_proj) mixes the two into one hidden state. Stock SGLang runs that projection on every GPU, reading the full 151 MB weight, while the megakernel gives each GPU one eighth of its outputs and gathers the results through a mailbox. At the end, the draft picks its most likely next token from the vocabulary, which is split across the GPUs. Stock SGLang gathers every GPU's scores for the whole vocabulary and then takes the maximum, while in the megakernel each GPU finds the maximum of its own part and sends only that value and its token ID, so that every GPU can take the maximum of the 8 candidates.
The bookkeeping is recorded, together with everything else, into one CUDA graph per step, so that the CPU launches the whole step, from the target verify to the last draft pass, at once. A few smaller changes trim the bookkeeping, for example by broadcasting the result of the verify to the other GPUs once instead of three times.
With all of that, everything outside the layers goes from 853 to 662 microseconds per step, which is 7 percent of the saving in the profile. To see how much of the speedup comes from recording the step as one graph, I also served stock SGLang with only the step-graph switches turned on (section 9). With one user, that makes a step 7.26 milliseconds long instead of 7.32, so the graph accounts for 0.06 milliseconds of the megakernel's 2.56-millisecond saving. Recording the step as one graph has little to win on its own, since the stock GPU is hardly ever idle, and almost all of the megakernel's gain comes from its kernels.
8. Does It Compute the Same Thing?
Does the megakernel compute the same thing as stock SGLang? It is designed to, in two ways, and a third design choice makes sure that a hang doesn't go unnoticed.
First, every part of the step has a stock version, copied from SGLang's model code, and the megakernel's kernels replace these one at a time, so each can be tested against its stock counterpart. Second, the kernels round at the same points as the stock code wherever they can, and they sum partial results in a fixed order, so that the result for one token doesn't depend on the other tokens or on the GPU. In the few places where a kernel rounds at a different point, like the norm in section 3.2, or adds up in a different order, like the router scores in section 5.2, the last bits of some values can differ. Third, the deadlines from section 2.2 turn a hang into a stop.
Agreement up to the last bits doesn't guarantee the same text, though, since a tiny difference can flip a close choice between two tokens and send the generation down another path. So, I also measured the end result with the build used for the speed numbers, this time with the draft model's real acceptance instead of a pinned one. On GSM8K (grade-school math word problems; 200 questions, with 8 worked examples in the prompt), stock SGLang scores 0.895 and the megakernel 0.920. The standard error of a 200-question score is about 0.02, and stock SGLang scored 0.925 on the same questions the day before, so a difference of this size is within the noise. Both find a passkey hidden in a 16,000-token text 8 of 8 times.
For a finer check, I generated 256 tokens for each of 32 prompts, fed each prompt and its output back in as a prefill, and compared the token distributions of the decode path with those of the prefill path, which the megakernel doesn't touch. The average KL divergence of the decode path's distribution from the prefill path's is 0.0161 nats for stock SGLang and 0.0162 for the megakernel, and the most likely token is the same at 97.7 percent of the positions with both. A numerical error in the megakernel's decode path would show up as a larger divergence here, and the divergence is essentially the same. The real acceptance length, the average number of tokens a step produces, which numerical drift would lower, is 3.46 with stock SGLang and 3.44 with the megakernel, a difference of the size I see between runs.
9. Putting It Together
Let's put the four stages side by side, together with the time it takes to read each stage's weights. Figure 12 below shows both, with the MoE split into the experts and the combine plus all-reduce.
As Figure 12 shows, there isn't one big win. Every stage gets shorter, by between a fifth (the MoE's combine and all-reduce, 8.9 to 7.3 microseconds) and almost a half. In each stage that reads weights, stock SGLang takes two to five times as long as reading them would, and the megakernel closes much of that gap, but in no stage all of it.
How does that translate into speed for a user? I served stock SGLang and the megakernel with the same model flags and measured the time per step and the decode speed per user with 1, 2 and 4 users, each sending an 8,192-token prompt and generating 1,024 tokens. The megakernel's servers add the flag that turns it on and the step-graph switches from section 7, and I also ran stock SGLang with only those switches. I launched each server twice (in the order stock, megakernel, megakernel, stock, and then the switches-only server twice) and averaged the two launches. Figure 13 below shows the result.
With one user, the megakernel decodes at 627 tokens per second against 408 for stock SGLang, 1.54 times as fast. With 2 users, the megakernel is 1.40 times as fast, and with 4 users 1.13 times.
The gain shrinks, and not only as a ratio: the megakernel saves 2.56 milliseconds per step with 1 user, 2.43 with 2, and 1.26 with 4. With 4 users, a step has 16 tokens from 4 unrelated texts, which pick more distinct experts per layer than the roughly 24 of one user, and the megakernel runs different variants of several kernels for more than 8 tokens. I haven't profiled the 4-user step yet, so I can't say which of these costs the most.
The megakernel also has a memory cost. Several of its kernels read their weights in a layout of their own, which the megakernel builds as copies next to SGLang's weights when the model loads (SGLang's own weights stay, since prefill and all other steps still use them). In my runs, these copies take 20.3 GiB per GPU (15.8 GiB of them for the MoE's down projections), and the KV cache shrinks from 3,654,144 to 2,999,424 tokens, 18 percent fewer. With one to four users and 8,192-token prompts, the smaller cache doesn't matter, but it limits how many long contexts a server can keep at the same time.
10. The Megakernel Landscape
Now that we know what one megakernel does and where its time goes, let's look at the others. Over the past few weeks, engineers at NVIDIA and elsewhere have opened pull requests with megakernels for several large open models, in the three places from the introduction: sgl-nvidia-mega for SGLang, specialized decode paths inside vLLM, and per-model targets in TensorRT-LLM. All of them attack the gap that I measured for GLM-5.3, but they draw the lines between kernels in different places, as Figure 14 below shows. (I'll use users and requests interchangeably: each user here is one request.)
The counts range from stock SGLang's 22 to 29 kernels per layer to one kernel for the whole model. In the rest of this section, I'll go through the designs one project or model at a time. For each, I'll look at what it covers, what it does differently from the GLM-5.3 megakernel we took apart, and what it reports.
10.1 GLM-5.3 in vLLM
The closest relative of the megakernel from sections 3 to 6 is vLLM's specialized decode path for the same model (vLLM calls it latency-specialized), opened as two pull requests: #63386 for the 78 layers and #63387 for the MTP drafter. It serves the FP8 checkpoint on 8 B200 or B300 GPUs (the reported numbers are on B200), for exactly one request at a time, with the same 4 tokens per step (or one token padded to 4 when speculative decoding is off).
The main difference is how few kernels it needs. For each layer, every GPU launches two kernels: a worker kernel that computes the query and the new KV entry, the attention and the output projection, and a fused MoE kernel. On the 21 layers with their own indexer, three of the eight GPUs first run a selector kernel. Each of the three scores a third of the earlier tokens, and the three exchange histograms of their scores to agree on which 2,048 tokens to keep. The indexer, which mostly stays stock in sgl-nvidia-mega, is split across GPUs here. The fused MoE combines the experts' outputs across the GPUs itself, and a variant called the seam does that combine by column slices and also prepares the next layer's norm input, much like the fold in section 6.3.
Another difference is memory. The vLLM path reads the weights in place, in vLLM's DeepGEMM layout (the switch also moves prefill's MoE to DeepGEMM), so it keeps no second copy. Its KV cache holds 5.4 percent fewer tokens (3.4 GiB less per GPU), against 18 percent fewer for the sgl-nvidia-mega megakernel in section 9, and its CUDA graphs take 1.96 GiB instead of 0.54. Its mailboxes live in a symmetric-memory arena (memory that every GPU in the group can address), and where the driver supports it, the weights and the arena are placed by locality, so that each of the GPU's two dies works on memory close to it.
The pull requests report a time per output token of 1.92 milliseconds instead of 3.56 at an 8K context (1.85 times as fast), and 1.64 milliseconds (2.17 times) with the specialized drafter and a post-forward CUDA graph as well. At about 3 tokens per step, the 1.64 milliseconds make a step of about 4.9 milliseconds, close to the 4.76 that I measured for sgl-nvidia-mega, although the GPUs, the weights and the baseline all differ.
10.2 GLM-5.3 FP8 in sgl-nvidia-mega
Another GLM megakernel for SGLang, #22 for the FP8 checkpoint, draws the lines between kernels much as vLLM does. One kernel, MegaMLA, covers the attention side from the input norm through the projections, RoPE, the cache update, the sparse attention and the output projection, up to and including the all-reduce. A second kernel, MegaMoE, covers the rest of the layer, from the post-attention norm through the router, the routed and shared experts, and the second all-reduce. Inside each kernel, the thread blocks are split into groups, one per token of the speculative step, and each group only waits for its own inputs, so a token whose inputs arrive late doesn't hold up the others. The layers with their own indexer keep SGLang's attention.
It reports 1.34 times as many tokens per second for one request on 8 GPUs and 1.17 times for two requests, and 1.21 and 1.04 times on 4 GPUs.
10.3 GLM-5.3 in TensorRT-LLM
TensorRT-LLM approaches the problem through modeling_v2, a package of per-model targets. A routing module (no relation to MoE routing) looks at the model, the GPU and the parallel layout and either picks a target that implements the decode step for that combination or falls back to the built-in model. #20267 added default targets for gpt-oss-120b and DeepSeek-R1, and #20524 adds one for GLM-5.3 in NVFP4 on GB300, mainly at TP8, which is nearly my setup (GB300 systems pair B300 GPUs with Grace CPUs).
Its own kernels cover the all-reduce after the attention together with the routing, the RoPE append to the KV cache, the sparse MLA decode, an indexer top-k that is merged across GPUs, the dense MLP, and the draft model's MoE. The target also hooks into the executor to stage each step's inputs and write the sampler's results. A sister target for Rubin GPUs at TP16 (#20517) is merged. Neither pull request compares its speed with the built-in model for one request. The Rubin one reports 858 tokens per second per user at a forced acceptance of 2.91 tokens per step, in a deployment that the built-in model couldn't run at all.
10.4 DeepSeek-V4.1-Flash
DeepSeek-V4.1-Flash has had the most megakernel pull requests so far: sgl-nvidia-mega's first pull request (#1) was for it, and so were vLLM's #61868 and #61869. Both projects run it on 4 GB300 GPUs with DSpark speculative decoding, which drafts 5 tokens per step, and the model has two features that GLM-5.3 doesn't. With mHC, a form of hyper-connections, it keeps several residual streams and mixes them at every sublayer boundary, and with Engram, some layers look up large hashed tables, which are partly kept in host memory.
Both projects build these features into a boundary kernel (the kernel at a sublayer boundary, which does the all-reduce) like the mailbox all-reduce in section 2.2. In the words of vLLM's notes, every sublayer boundary runs a "fused Lamport all-reduce + mHC", and "every MoE finalize [is] deferred to the next boundary's fused kernel", which is the fold of section 6.3 under another name. The attention's output GEMM (wo_b) writes its output straight into the boundary kernel's mailbox at small batches, like the o_proj kernel in section 5.2. The sgl-nvidia-mega version adds a second form of the exchange for larger batches (beyond the one to four users this article focuses on): from 49 to 384 tokens, each GPU sends a token's values only to the GPU that owns that token, which adds up the four partials in rank order and sends the sum back (a two-shot all-reduce instead of a one-shot one). On the draft side, vLLM runs DSpark's whole chain of draft tokens in one cooperative kernel per GPU, with the draft head split by vocabulary across the GPUs.
vLLM reports a decode step of 4,075 instead of 5,355 microseconds for one request, 1.31 times as fast as its stock path, and about 1.14 times at 32 requests. Pull request #1 in sgl-nvidia-mega reports 1,038 tokens per second per user for one request but no comparison with stock SGLang.
10.5 Kimi K3
Kimi K3 mixes MLA layers with linear-attention layers called Kimi Delta Attention (KDA), which keep a fixed-size state instead of a KV cache. sgl-nvidia-mega's Kimi K3 megakernel (#17, merged) serves the MXFP4 checkpoint (another 4-bit format) on 8 GB300 GPUs at 1 to 64 requests. vLLM's (#61867, merged) runs on 8 or 16 GB300 GPUs, with or without DSpark, and also supports decode context parallelism, which splits a long KV cache across the GPUs. The vLLM pull request's file list reads like a summary of this article: a KDA kernel, MLA query and value kernels, an MoE split into a front, the routed experts, a tail and the shared expert (plus a small-batch chain), an o_proj producer and consumer (the two halves of the exchange in section 5.2), and shared code for mailboxes, two-shot all-reduces and prefetching.
Without speculative decoding, both report roughly 1.9 to 2.5 times the speed. sgl-nvidia-mega reports 2.54 times for one request, measured as the time to generate 1,024 tokens, falling to 1.40 times at 64 requests. vLLM reports a decode step 1.89 times as fast for one request on 16 GPUs (3.90 instead of 7.38 milliseconds), and 1.71 times as many tokens per second with DSpark at an acceptance of 6 tokens per step.
10.6 GLM-5.3-Flash
Despite its name, GLM-5.3-Flash isn't simply a scaled-down GLM-5.3. vLLM calls its architecture Glm5Next. It combines KDA layers like Kimi K3's with DSA like GLM-5.3's and mHC like DeepSeek-V4.1's, and its vLLM megakernel (#63102) borrows accordingly: the KDA kernel and a split-K GEMM from Kimi K3, and the Lamport all-reduce from DeepSeek-V4.1. This reuse points to a toolkit that is shared across models.
Its notes also show a choice that a one-request megakernel doesn't face. It serves steps of 1 to 64 tokens, and its MoE switches between two kernels: clusters that each handle one expert's route for 1 to 4 tokens, and an expert-grouped persistent kernel for 8 to 64 (token counts that the table leaves out run stock). A policy table records the crossover for each stage, together with the measurement behind it. It reports an inter-token latency 1.76 times lower for one request on 4 GB300s without speculative decoding, 1.33 times with 3 MTP drafts, and 1.16 times at 64 requests.
10.7 Qwen3.5
Qwen3.5-397B-A17B is another hybrid, with Gated DeltaNet linear attention between its full-attention layers. Its sgl-nvidia-mega megakernel (#20) replaces the same kinds of pieces as the GLM-5.3 megakernel: the router together with the quantization of the MoE input in one launch, the whole MoE (the top-k, both projections, SwiGLU and the requantization in between) in another, the Gated DeltaNet chain, a fused attention prologue and epilogue, and the layer boundaries, with an NVLink multicast all-reduce that the preceding GEMM writes into directly.
The surprising part is what the kernels do on their own. At a 128K context, the megakernel alone makes decoding 8.5 percent faster (766 instead of 706 tokens per second per user). Most of the 1.83 times that it reports comes from a separate SGLang pull request (#45474) with, in its words, "the runtime changes that turn the plugin's GPU savings into speed". The pull request says why: without that runtime pull request, "the round becomes host-bound". That is the opposite of what I measured for GLM-5.3 in section 7, where recording the whole step as one CUDA graph saved only 0.06 milliseconds.
10.8 Outside the Inference Engines
The engines didn't invent the idea. In May 2025, Hazy Research at Stanford published a megakernel for Llama-3.2-1B that runs the entire forward pass as one kernel. Their reasoning matches section 1.3's: in a chain of small kernels, the GPU stops loading weights during each kernel's setup and teardown, and they measured that vLLM and SGLang used at most half of an H100's bandwidth for a single sequence.
Their megakernel works like an interpreter. Each SM runs a list of instructions (a fused norm, query-key-value projection and RoPE, the attention, the output projection, and so on) that is scheduled ahead of time on the host. Shared memory is split into pages that an instruction hands to the next one as soon as it's done with them, so the next weights start loading early, and counters in global memory replace kernel boundaries as the way to wait for inputs. It used 78 percent of the H100's bandwidth and ran more than 1.5 times as fast as SGLang. A follow-up in September 2025 applied the same interpreter design to a throughput-focused Llama-70B megakernel on 8 GPUs (any batch size, mixed prefill and decode), with remote loads and stores to the other GPUs issued from inside the kernel, and processed 65,536 ShareGPT prompts about 22 percent faster than SGLang end to end.
MPK (Mirage Persistent Kernel, December 2025) automates this. A compiler turns the model into a graph of tasks at the level of single SMs, and a runtime inside one persistent kernel schedules them across the GPU. Its paper reports up to 1.7 times lower latency than serving systems that launch one kernel per operator.
At the other end of the batch-size range, DeepGEMM's Mega MoE fuses the expert-parallel dispatch, both expert projections, the activation and the combine into one kernel, overlapping the NVLink transfers with the tensor-core work. It targets expert-parallel serving rather than one user, but it removes kernel boundaries for the same reason.
10.9 The Speedups Side by Side
Figure 15 below collects the speedups that the pull requests report for one request, together with my measurement for GLM-5.3.
The numbers range from 1.3 to 2.5 times. My guess is that four differences in how they were measured matter more than the model.
The first is how many tokens a step has. Kimi K3 without speculative decoding has one token per step, and it has the largest speedup in Figure 15, 2.5 times in sgl-nvidia-mega's pull request (vLLM's reports 1.9 times). vLLM's GLM-5.3 path reports 1.85 times with speculative decoding, and 2.17 times with its specialized drafter and post-forward CUDA graph as well (the bar in Figure 15).
The second is how fast the stock path was to begin with. vLLM reports the time per output token; multiplied by its 2.99 tokens per step, that gives about 10.6 milliseconds per step for its stock path at an 8K context and 4.9 for its specialized path (in FP8, on B200 GPUs). That specialized path is about as fast as the megakernel's 4.76 milliseconds, but vLLM's stock path is much slower than SGLang's 7.32 (on different GPUs and weights), so the same kind of fast path gives a larger ratio there.
The third is how much of the step is replaced and what else changes. The GLM-5.3 FP8 megakernel from section 10.2 replaces the attention and the MoE with two kernels per layer but leaves the indexer layers' attention stock, and it reports 1.34 times. For Qwen3.5, most of the 1.83 times comes from a separate pull request for SGLang's runtime (#45474), and the megakernel alone gives 8.5 percent (section 10.7).
The fourth is what is measured. The time of a decode step gives larger ratios than the time per token over a whole conversation, which also includes reading the prompt. On a trace of agentic coding sessions, sgl-nvidia-mega pull request #24 reports 1.40 times for the decode speed and 1.20 times end to end.
11. What Is Left
Back in Figure 12, the megakernel's layer takes 46.9 microseconds, and reading its weights at full bandwidth would take 19.5, so, as in section 1.3, about 27 microseconds of every layer go to something other than reading weights.
The two stages with the all-reduces hold the largest part of that. The attention output and the fold take 17.9 microseconds per layer, about 1.40 milliseconds per step, but their weights only need about 4 microseconds. The rest is the exchange itself: loading the partial results, waiting for the other GPUs' records (2 to 2.5 microseconds in the fold, section 2.2), adding them up and applying the norm. The MoE engine, on the other hand, is within about 3.4 microseconds of its floor, so even a perfect engine would save less than 6 percent of the step.
Hazy Research found something similar in their Llama-3.2-1B megakernel (section 10.8), which has no kernel boundaries left at all. In the B200 version of it, of a 600-microsecond forward pass, they counted 250 microseconds for storing activations, waiting until they were visible and loading them again, more than the 200 microseconds of compute and far more than the 30 microseconds spent waiting for weights. Once the weights stream at full speed, what is left is the latency of handing each result to the next step, on one GPU or across 8.
My guess is therefore that the next large gain will most likely come from the hand-offs, and, on 8 GPUs, above all from the exchanges between them: fewer of them per layer, or less time spent waiting in each one. vLLM's GLM-5.3 path in section 10.1, with two kernels per layer (three on the indexer layers), shows how far the hand-offs within one GPU can be cut; the two exchanges between GPUs remain.
12. Flapping Airplanes' Megakernel Framework
On October 21, 2026, a young lab called Flapping Airplanes announced a $1 billion Series A together with what it calls "the world's most complete megakernel framework", one that "can perform entire training runs, serve inference, play video games, and even do all three simultaneously in a single kernel". The lab was founded by Ben Spector, Asher Spector and Aidan Smith and launched in January 2026. Ben Spector is the lead author of ThunderKittens and a co-first author of both Hazy Research megakernel posts from section 10.8, and the name that the framework goes by in the demo, the Kittens Virtual Machine, points back to that work.
There is no code, paper or benchmark yet, but the announcement came with a 45-second video that shows more than the text does. In this section, I first go through what the video shows and then give my guess at how the parts that it doesn't show might work. Along the way, I'll use an independent open-source project, Flappy Kernel, which someone built in the two days after the announcement. It runs an LLM, a small trainer and a game in one launch of Mirage's persistent kernel (MPK, section 10.8) on one H100, and its notes measure several of the problems that I could otherwise only guess at.
12.1 What the Video Shows
The demo is called KVM DOOM. A single kernel launch on one B200 runs three programs at the same time, each on its own share of the GPU's 148 SMs, as shown in Figure 16 below. In the video's words, these are "three Python programs", and "the Kittens Virtual Machine runs all three at the same time".
The training program trains a small language model on 116 SMs. Its loss falls from about 12 to 2.1 over 4,000 steps, which take 46 seconds at about 360,000 tokens per second. The inference program runs on 24 SMs and keeps answering the question "What is a megakernel?" with the model that is being trained, at about 1,070 tokens per second. Its answers start as nonsense ("The term is a town in the town of the town...") and end, 46 seconds later, as "A megakernel is a single GPU program that is launched once that handles what would normally be a chain of separate kernel launches. Different worker groups can execute different operations within the same launch." The third program runs Doom on the remaining 8 SMs.
The video also shows a few lines of each program. The training program reads like the forward pass of an ordinary model, and the framework differentiates it:
gate = g.extend(w_gate(x=x))
up = g.extend(w_up(x=x))
gate_act = g.elementwise(mp.Silu(), x=gate)
fused = g.mul(gate_act, up)
out = g.extend(w_down(x=fused))
...
bwd, grads = g.backward(loss)
The inference program is a decode loop (g.range(count, style="no_backprop")) that runs a snapshot of the model's forward pass and picks the next token with g.sample_token, and the Doom program describes the player's movement as an element-wise function (@elementwise def PlayerCmd(...)). All three are Python code that builds a graph (g), and the virtual machine runs the graphs. That is the interpreter from section 10.8 with a compiler in front of it.
Finally, the video compares the demo with Megatron for the training and vLLM for the inference, "each timed individually" on the same 116 and 24 SMs. Megatron takes 70.1 seconds for the 4,000 steps instead of 46.1, vLLM produces 710 tokens per second instead of 1,076, and together they launch 514,562 kernels against KVM's one. So each of KVM's programs is about 1.5 times as fast as the usual tool running alone, even though it shares the GPU with two other programs.
The video leaves a lot out: the size of the model (small enough that 4,000 steps take 46 seconds), how Megatron and vLLM were limited to their SMs, and anything at the "trillion-parameter pretraining scale" that the announcement mentions.
12.2 Checking the Baselines
The comparison is the one part of the video that can be checked without KVM itself, so I rebuilt the baselines on one of our B300s, which has the same 148 SMs as a B200, and limited each to the video's SM counts with MPS (116 SMs for training and 24 for inference), checking that each process saw exactly that many SMs. The video doesn't name the model, but 4,000 steps in 46.1 seconds at about 355,000 tokens per second is 4,096 tokens per step, and a starting loss of about 12 is the natural logarithm of a vocabulary of about 150,000 tokens. So I used Qwen's 151,936-token vocabulary with tied embeddings, SwiGLU MLPs, RMSNorm and RoPE, in a family of sizes where width and depth grow together (a hidden size of h, h/64 layers, an MLP of 3h and heads of 64 values), from 42 million to 970 million parameters. For training, I used Megatron-Core 0.19.2 (in NVIDIA's 26.09 PyTorch container). For inference, I used a nightly build of SGLang as the main baseline, and vLLM 0.32.0 because it is the one in the video.
Megatron's defaults are a poor fit for a model this small, so I first turned on its own options one at a time, on a 4-layer model of 43 million parameters. Turning off the NaN check (a synchronization with the host every step) and dropout took a step from 19.3 to 17.8 milliseconds. The largest single change is Megatron's fused cross-entropy (--cross-entropy-loss-fusion): with a 151,936-token vocabulary, the default loss makes about 16 separate passes over the 4,096 × 151,936 logits in fp32, and fusing it brings the step to 13.6 milliseconds. Recording the whole step as one CUDA graph (--cuda-graph-impl full_iteration) takes it to 8.4, and turning off Megatron's rerun bookkeeping (--rerun-mode disabled) to 8.0, with the same loss to within 0.001 at every logged step. Nothing else I tried helped: the other attention backends, manual garbage collection, more data-loader workers, bf16 Adam states, or a patch that fuses the output layer with the loss (Apple's Cut Cross-Entropy, which can't be captured in the graph). Even so, the loss still takes about 60 percent of the GPU time of a step, so a better loss kernel would make Megatron faster still. A full 4,000-step run with this configuration takes 32.2 seconds, against KVM's 46.1.
For decoding, I timed one request with a 32-token prompt and 1,024 new tokens, picked greedily, and took the median of five runs. SGLang's defaults already capture CUDA graphs, use TensorRT-LLM's attention kernels (trtllm_mha) on Blackwell, and let the CPU schedule each step while the GPU is still running the one before. The two settings that I expected to matter for a single request, turning off the prefix cache and capturing graphs for a batch of one only, changed nothing (1,249 tokens per second against 1,248 for a 486-million-parameter model), so I kept the defaults. vLLM also schedules ahead by default and uses CUDA graphs, and limiting it to one sequence (max_num_seqs=1), the Triton attention backend and turning off prefix caching help a little: together they decode 1,659 tokens per second for the 43-million-parameter model, against 1,591 with the defaults (medians of three runs, which vary by up to 5 percent). With CUDA graphs turned off, vLLM drops to 692 tokens per second, close to the video's 710. SGLang decodes the same model at 1,861 tokens per second, and it is 10 to 22 percent faster than vLLM's best configuration at every size of the family.
So at this size, all three configured baselines are faster than KVM's numbers, Megatron by 1.4 times, vLLM by 1.5 and SGLang by 1.7. The question then becomes how big the model would have to be for KVM to come out ahead, and Figure 17 below answers it by running the configured baselines at each size of the family.
Megatron's step reaches KVM's 11.5 milliseconds at about 116 million parameters (33 million without the embedding). A full 4,000-step run of a 126-million-parameter model takes 49.3 seconds, against KVM's 46.1, while a 105-million-parameter model takes 10.7 milliseconds per step. SGLang's decoding drops to KVM's 1,076 tokens per second at about 713 million parameters (508 million without the embedding): a 697-million-parameter model decodes 1,102 tokens per second, and three runs of a 721-million-parameter model give 1,061 to 1,063. vLLM gets there sooner, at about 455 million. KVM trains and serves the same model, so it beats both well-configured baselines only if its model has more than about 713 million parameters.
KVM's own throughput limits the model from the other side. Training takes about 6 floating-point operations per parameter for every token, and 116 of a B200's 148 SMs can do at most about 1.76 petaFLOPS of dense BF16 math (NVIDIA lists 36 petaFLOPS for 8 GPUs with sparsity, which is 2.25 per GPU without it). At KVM's 355,000 tokens per second, that caps the model at about 830 million parameters even at 100 percent of the peak, and a 713-million-parameter model would need about 86 percent of it, or about 69 percent if the operations are counted the way Lambda's MFU paper counts them, without the embedding but with attention. The 86 percent is a lower bound, since it leaves out attention, and with tied embeddings the output layer is a real matrix multiplication, so counting both, the model needs about 93 percent. The best published training runs reach 47 to 60 percent of the peak (Megatron-LM, llm.c's GPT-2 reproduction, Lambda), all with half a million tokens or more per step. KVM's demo trains on 4,096 tokens per step, and at that batch, configured Megatron reaches 7 percent for the 42-million-parameter model and 14 percent for the 126-million-parameter one. So even 47 to 60 percent is generous to KVM, and at that level its model would have about 390 to 500 million parameters, where SGLang decodes 1,240 to 1,480 tokens per second, 15 to 38 percent faster than KVM. For inference, a simple copy kernel on 24 SMs of our B300 moves at most 2.3 TB/s, which caps a model decoded at 1,076 tokens per second at about a billion parameters, so the training bound is the tighter one.
So KVM's speed claim can only hold for a model of roughly 713 to 830 million parameters, and only if its training runs at more than 69 to 86 percent of the GPU's peak, depending on how the operations are counted, which is above every published training run. The video's own baselines point the other way. An unconfigured Megatron taking 17.5 milliseconds per step and vLLM decoding 710 tokens per second without CUDA graphs both match a model of around 40 million parameters (an unconfigured Megatron already takes 26 milliseconds per step at 111 million), and at that size, configured baselines are 1.4 to 1.7 times as fast as KVM. The demo's small batch is also the case that favours a megakernel most. With 16 times the batch in one micro-batch (65,536 tokens), Megatron trains the 126-million-parameter model at 470,000 tokens per second, 1.41 times its speed at 4,096, but splitting the same batch into 16 micro-batches of 4,096 gains nothing. So the configured Megatron's fixed costs per step, such as the optimizer and the launches, are already small, and the gain comes from larger kernels, which spend less of their time starting up and winding down. That start-up and wind-down is what a megakernel saves at small batches, and how KVM compares at a realistic batch isn't published. None of this makes the demo less interesting, since its point is that three programs share one launch, but its speed comparison doesn't show an advantage over well-configured tools. The caveats are that our GPU is a B300 rather than a B200 (the same SM count, but a different host CPU, which matters for runs limited by overhead), that MPS may limit the SMs differently from however the video did it, that each baseline ran alone, as in the video, while KVM's programs share the memory system with each other, that runs vary by up to 5 to 10 percent, and that I read their numbers off the video.
12.3 Why Put Them in One Kernel
Splitting the SMs is the simplest way to "overlap memory-bound inference with compute-bound training", as the announcement puts it, and the GLM-5.3 step from this article shows why the two fit together. Each byte of NVFP4 weights that the step reads feeds about 14 floating-point operations (2 per weight for each of the 4 tokens, at a little over half a byte per weight). A B300 can do about 15 petaFLOPS of dense NVFP4 math, which is about 2,000 operations for every byte it can read at its 7.67 TB/s, so while the megakernel streams its weights at close to full speed, the tensor cores do less than 1 percent of the work they could do. Training is the opposite case. A training step multiplies each weight by every token in its batch, often thousands of them, so a large training GEMM keeps the tensor cores busy and needs only a small part of the memory bandwidth.
But why one kernel instead of three programs on three groups of SMs? CUDA can already run several kernels on one GPU at the same time, through streams, through the Multi-Process Service (MPS), which can also give each process a fixed set of SMs, or through green contexts, which split the SMs between kernels of one process. Flappy Kernel's notes show what goes wrong next to a persistent kernel like Mirage's. When another process shared the GPU through ordinary time-slicing, Mirage aborted without producing a valid token. When the trainer and the game ran as a second kernel in the same process, they got one training update and one frame during a whole request, even with 32 SMs left free. MPS did work, but only after its per-process thread limit was sized in whole pairs of SMs and one learner was dropped. (MPS's static SM partitions, the other option, come in chunks of 8 SMs on Hopper and newer GPUs.) As extra thread blocks inside Mirage's own launch, the same jobs worked without any tuning, and the LLM stayed within about 2 percent of its speed alone.
I reran Flappy Kernel's measurements on one of our B300s, which only needed a small change so that Mirage would use its Blackwell code on a GPU of compute capability 10.3. Most of them carry over. Inside Mirage's launch, the trainer runs exactly as fast as it does alone (642 updates per second), the trainer started as a second kernel in the same process got a single update during a whole request, and an Nsight Systems trace shows one persistent kernel with nothing else running next to it. Two things differ. Time-slicing between processes didn't break Mirage on the B300, but it made decoding 2.3 times slower. And the split of the SMs costs more: the co-located LLM decodes only 0.3 to 0.6 percent more slowly than the same LLM alone on the same 96 workers, but in Mirage's single-kernel mode, 96 workers plus the co-tenants decode 11.6 percent more slowly than all 128 workers alone, where the same comparison on the H100 showed 0.1 percent. A B300 decodes Qwen3-8B fast enough that Mirage still gains from the SMs that the co-tenants take away.
One kernel also lets the programs share memory directly. In the demo, the inference program serves the weights that the training program has just updated, so the model can be tried out while it trains without copying the weights to a separate server. (In Flappy Kernel, the game reads the trainer's live weights in the same way.)
12.4 How I Think It Works
The video confirms a virtual machine that runs graphs built in Python, an automatic backward pass, and fixed groups of SMs for each program within one launch. Here is how I think the rest fits together. The starting point is the interpreter from section 10.8, in which every SM runs a loop that fetches an instruction, waits on counters in global memory until the instruction's inputs are ready, takes shared-memory pages, loads, computes and stores, and then increments the counters that later instructions wait on.
The first piece is a compiler from the graphs to instructions. Since g.backward(loss) builds the backward pass, every node of the forward and backward graphs has to become instructions of the virtual machine, cut into tiles and scheduled over the program's SMs. Hazy Research's Llama-70B post already argued that more of the work should move to "the CPU-side scheduler", so that new models need less CUDA expertise. KVM looks like that idea carried through, and I suspect that only the virtual machine itself is written in CUDA.
The second is a queue in place of a fixed schedule. The Llama-1B megakernel ran a schedule that the host computed ahead of time and reused for every forward pass, but a server has to accept requests whenever they arrive. So the kernel would keep running and pull its work from queues in memory that the host keeps filling. Flappy Kernel does exactly this: its single launch lasts the whole session, and the host talks to it through pinned memory that the kernel reads and writes directly, so the host never launches anything. A kernel that never exits also never pays for a launch, which would remove the problem that section 10.7 describes for Qwen3.5, where the step becomes limited by the host.
The third is sharing an SM between programs, which the demo doesn't do. Splitting the SMs works when the inference program needs only a few of them, as a small model does, but the GLM-5.3 megakernel's MoE engine uses 132 of the B300's 148 SMs to keep the memory busy. To put the idle tensor cores of those SMs to work, a compute-bound and a memory-bound instruction would have to run on the same SM at the same time. This can't be left to the hardware, since a thread block keeps its SM until it finishes: the GLM-5.3 megakernel runs more than 600 kernels per step, and if each of them waited just 5 microseconds for a training block to finish, the step would get about 3 milliseconds slower.
Blackwell makes the sharing easier than Hopper did. On Hopper, a GEMM keeps its running sums in registers, and the number of registers per thread is fixed for the whole kernel by its most demanding code. On Blackwell, the tensor-core instructions (tcgen05) keep the sums in a separate tensor memory of 256 KB per SM, and both the bulk copies (TMA) and the tensor-core instructions are issued by a single thread and then run in the background. So one group of warps could stream decode weights into some of the shared-memory pages while another keeps a training tile on the tensor cores, with the interpreter splitting the shared memory and the tensor memory between them, much as Hazy Research's interpreter passes pages from one instruction to the next. When decode work is ready, the interpreter would give it the next free pages and the next turn on the tensor cores, so that training fills whatever decoding leaves over, as illustrated in Figure 18 below. Flappy Kernel's notes list this as the alternative they didn't build, since it needs a work-stealing queue, and it is the most speculative part of this section.
The fourth is communication from inside the kernel, across nodes as well as within one. Training at the "trillion-parameter pretraining scale" that the announcement mentions spans many nodes, so gradients and activations have to cross the network as well as NVLink. Within a node, a kernel can already write straight into the other GPUs' memory, like the mailbox in section 2.2 or the Llama-70B megakernel's remote stores, and Hazy Research's ParallelKittens turns these into a small set of primitives. Between nodes, the GPU can drive the network card itself (NVSHMEM's GPU-initiated InfiniBand transfers, which DeepEP uses), so the kernel never has to stop and let the host send anything.
That leaves Doom. A game step is branchy work on the ordinary CUDA cores with no matrix math in it, so running one in the same kernel mostly shows that the virtual machine isn't limited to tensor operations, and the element-wise PlayerCmd function suggests that the game is written with the same Python front end as the model. Before I saw the video, I had guessed that a model would play the game, which would put a whole reinforcement learning loop into one kernel. In the demo, Doom is an independent third program, and the link between the programs is between training and inference instead: the model is served while it trains.
12.5 What Would Be Hard
Several things make this harder than the single-model megakernels in section 10, and Flappy Kernel ran into two of them even at a small scale.
First, every type of instruction is compiled into the same kernel, so the registers each thread needs and the amount of code that the SM's small instruction cache has to hold both grow with the number of instruction types. When Flappy Kernel's extra code was inlined next to Mirage's worker loop, the compiler serialized every Hopper tensor-core instruction (wgmma) in the kernel, and the project had to move that code behind function calls that are never inlined.
Second, the programs share the memory system. Flappy Kernel's first version decoded 30 percent more slowly than the LLM alone, although its trainer used only 3 percent of the memory bandwidth. One array in the trainer was indexed at run time, so the compiler placed it in local memory, and the resulting traffic through the L2 cache (about 900 GB/s) delayed the decode's own L2 accesses, which batch-1 decoding depends on. Making the index a compile-time constant cut that traffic by a factor of 122. On the B300, Mirage's own per-task profiler shows where the remaining cost of sharing goes: with the trainer and the game running, the LLM's weight-streaming matrix tasks, 93 percent of its task time, each take about 1.3 percent longer, while its scheduling tasks don't slow down at all. Power is shared too: a B300 running dense FP4 math at full speed can reach its power limit and lower its clock, which would slow decoding's hand-offs, since those are mostly latency.
Third, a kernel that never exits never gets back to the host to allocate memory, so the activations that training keeps for the backward pass, the KV cache and the game's state all have to come from memory that the framework reserves up front and hands out itself.
Fourth, one kernel is one point of failure. A bad memory access in the game stops the training run and the serving with it, and a hang anywhere hangs everything, all the more since every block has to be resident at once while the blocks wait on each other (Flappy Kernel checks at startup that its blocks fit on the GPU's SMs). Profilers report time per kernel, which says little when there is only one kernel, so the framework would also need its own tracing.
12.6 What I Would Want to See
The video gives the first numbers, and section 12.2 shows that against well-configured baselines they only hold for a model of roughly 713 to 830 million parameters. Three more things would show how far the idea goes: the size of the model, together with a comparison against Megatron and SGLang in their best configurations, at a realistic batch as well as the demo's; the same comparison for a model large enough that decoding needs most of the SMs, where a fixed split works less well; and the time of a decode step when training shares its SMs, compared with a GPU that only serves. If decoding stays close to its stand-alone speed while training runs on the same SMs, the idle tensor cores of every serving GPU become training capacity, which would matter much more than any of the speedups in Figure 15.
13. Summary
For one user, sgl-nvidia-mega's GLM-5.3 megakernel is 1.54 times as fast as stock SGLang, mainly because it runs most of the model's layers as 8 kernels built for 4 tokens instead of 22 general-purpose ones. Each kernel loads its weights before it is allowed to read its input, and the kernels on either side of each all-reduce do the exchange and also compute the router scores and the MoE's combine. Together, these changes take about 31 microseconds off each layer. It pays for that with a KV cache that holds 18 percent fewer tokens, and its gain falls to 1.13 times at 4 users. The largest part of what remains is the exchange between the GPUs, and the other megakernels in section 10 differ mostly in how many kernel boundaries they leave in a layer. Flapping Airplanes' demo (section 12) goes further, with one kernel that trains a small model on most of a B200's SMs, serves it on 24 others and runs Doom on the last 8. Rebuilt on a B300, well-configured Megatron and SGLang beat its numbers unless its model has more than about 713 million parameters, which its own training speed allows only at 86 percent of the GPU's peak, but if a scheduler like it can also share an SM between programs, the tensor cores that decoding leaves idle could train a model at the same time.
Sources
- sgl-nvidia-mega, SGLang's megakernel repository
- How GPUs Talk to Each Other During LLM Inference
- sgl-nvidia-mega's GLM-5.3 NVFP4 megakernel: #19 and #24
- sgl-nvidia-mega's GLM-5.3 FP8 MegaMLA and MegaMoE
- sgl-nvidia-mega's DeepSeek-V4.1-Flash megakernel
- sgl-nvidia-mega's Kimi K3 megakernel
- sgl-nvidia-mega's Qwen3.5-397B-A17B megakernel and SGLang's runtime changes for it
- vLLM's GLM-5.3 latency-specialized decode: #63386 and #63387
- vLLM's GLM-5.3-Flash specialized decode
- vLLM's DeepSeek-V4.1-Flash specialized decode: #61868 and #61869
- vLLM's Kimi K3 specialized decode
- TensorRT-LLM
modeling_v2targets: #20267, #20524 and #20517 - Look Ma, No Bubbles! Designing a Low-Latency Megakernel for Llama-1B, Hazy Research
- How Many Llamas Can Dance in the Span of a Kernel?, Hazy Research
- MPK: A Compiler and Runtime for Mega-Kernelizing Tensor Programs
- DeepGEMM (Mega MoE)
- Flapping Airplanes' announcement on October 21, 2026: the Series A and the megakernel framework
- Taking Flight: Our Investment in Flapping Airplanes, Index Ventures
- Year-old AI research lab Flapping Airplanes raises $1B at a reported $6B valuation, SiliconANGLE
- ThunderKittens: Simple, Fast, and Adorable AI Kernels
- ParallelKittens: Systematic and Practical Simplification of Multi-GPU AI Kernels
- Flappy Kernel, an independent demo of an LLM, a trainer and a game in one Mirage launch, and Mirage
- Megatron-LM at core_v0.19.2, SGLang at 6563312 and vLLM v0.32.0, the versions used in section 12.2
- Published training MFU: Megatron-LM's README, llm.c's GPT-2 (124M) reproduction and Lambda's MFU paper
- NVIDIA HGX B200 summary (FP16/BF16 tensor throughput, with sparsity) and Apple's Cut Cross-Entropy
- CUDA green contexts
- SGLang and FlashInfer
- GLM-5.3 NVFP4 checkpoint
- PTX ISA, grid dependency control (
griddepcontrol)