Where an RL Rollout's Time Goes on a Large MoE
One inference step of a 745-billion-parameter mixture-of-experts model, taken apart mechanism by mechanism, with the numbers that decide which one is your problem
Draft. Every number here comes from a config file, from source at a named commit, or from a log of a command I ran, and every code block was run before publishing, but the text has not been read by anyone else yet. The page asks search engines not to index it.
If you have written a reinforcement-learning loop for a language model, it had two halves. One half is a training step, and it looks like any other training step: forward, backward, optimizer. The other half generates the completions that the training step learns from, and that half is a serving stack. It takes prompts in, runs the model over and over, and hands back tokens.
The second half is where the time goes. In the published recipes, generating the rollouts takes most of a step's wall clock, and the training step is the part you wait for afterwards. An RL engineer's performance problem is therefore almost always an inference problem.
That makes the inference side worth understanding in detail, and in particular worth understanding on the models people actually run RL on today, which are large mixture-of-experts models where almost all of the parameters sit in experts that most tokens never touch. So: on a model like that, where does one rollout step's time and memory actually go, and how much does each of the standard tricks win back?
In this article I am going to answer that by walking through a single step, mechanism by mechanism, and putting one number on each mechanism. Rather than surveying everything that could matter, I picked one reference model and made every number in the article come from it. The model is GLM-5.3, which I had on disk, and I read its real config and its real weights for the numbers below. I am leaving out the RL algorithms themselves (what GRPO does with the completions is somebody else's article), the training step's own arithmetic except where a rollout engine has to live with it, and anything that would need a multi-node run to measure, which is why the expert all-to-all below is counted in bytes rather than timed.
Each mechanism gets the same four questions: what is the bottleneck, how does the mechanism work, what is one number for it on the reference model, and what does it do to RL. The last one is the interesting one, because an RL rollout is not the same workload as serving a chat product, and several of these mechanisms behave differently when the thing on the other end of the engine is a trainer.
Every number comes from a config file, a source file, or a script I ran, and I say which. The code excerpts are cut down from the real files, which I note where it happens, and the snippets that are not excerpts were all run before publishing.
1. One Rollout Step, and Why It Is Memory Bound
Let's start with the shape of the thing. A rollout request is a prompt and a request for a completion. The engine runs the prompt through the model once, which is called prefill, and then generates the completion one token at a time, which is called decode. One decode step produces exactly one token per sequence, so a 2,000-token completion is one prefill and 2,000 decode steps.
As Figure 1 shows, the decode steps are where the step count is, and they are also where the trouble is, because a decode step is a strange shape of work. In prefill, every token of the prompt goes through the model at once, so a weight matrix gets read once and used against hundreds or thousands of rows. In decode, that same weight matrix gets read once and used against one row per sequence. The arithmetic shrinks and the bytes stay the same.
Before we can put a number on that, here is the reference model. GLM-5.3 has 78 layers with a hidden size of 6,144. Three of those layers have an ordinary dense feed-forward block of width 12,288, and the other 75 have a mixture-of-experts block with 256 routed experts of width 2,048, one shared expert that every token uses, and a router that picks 8 of the 256. A shared expert is an expert with no gate in front of it, and the reason to have one is that the patterns every token needs do not have to be learned separately by each of the 256. Attention is the latent kind: 64 heads, a 512-wide compressed key-value vector per token, and 64 rotary dimensions shared by all heads. The vocabulary is 154,880, the checkpoint ships in fp8 with a scale per 128 by 128 block of each weight matrix, and the whole thing is 703.7 GiB on disk across 118,629 tensors.
Counting the parameters from that config gives 745.2 billion in total and 42.1 billion active per token. One expert is 3 x 6,144 x 2,048, or 37.7 million parameters, and the 256 experts plus the shared one come to 9.70 billion per sparse layer, which is why 97.6% of the model's parameters are experts. The attention projections are 165.0 million per layer, plus 26.0 million for the sparse-attention indexer that this model also carries.
Now the bytes. A decode step does 2 FLOPs per active parameter per token, and it has to read every weight it touches once. The ratio of those two is the arithmetic intensity, and we can compute it straight from the config:
cfg = dict(hidden=6144, layers=78, dense_layers=3, experts=256, topk=8,
shared=1, moe_ffn=2048, dense_ffn=12288, vocab=154880,
heads=64, kv_lora=512, q_lora=2048, qk_nope=192, qk_rope=64,
v_head=256, idx_heads=32, idx_dim=128)
def parts(cfg):
h = cfg["hidden"]
attn = (h * cfg["q_lora"]
+ cfg["q_lora"] * cfg["heads"] * (cfg["qk_nope"] + cfg["qk_rope"])
+ h * (cfg["kv_lora"] + cfg["qk_rope"])
+ cfg["kv_lora"] * cfg["heads"] * (cfg["qk_nope"] + cfg["v_head"])
+ cfg["heads"] * cfg["v_head"] * h)
idx = h * cfg["idx_heads"] * cfg["idx_dim"] + h * cfg["idx_dim"]
fixed = (cfg["layers"] * (attn + idx) + cfg["vocab"] * h
+ cfg["dense_layers"] * 3 * h * cfg["dense_ffn"]
+ (cfg["layers"] - cfg["dense_layers"]) * cfg["experts"] * h)
return fixed, 3 * h * cfg["moe_ffn"], cfg["layers"] - cfg["dense_layers"]
def intensity(cfg, batch):
fixed, expert, sparse = parts(cfg)
k, E = cfg["topk"], cfg["experts"]
active = fixed + sparse * (k + cfg["shared"]) * expert
touched = 1 - (1 - k / E) ** batch
read = fixed + sparse * (cfg["shared"] + touched * E) * expert
return 2 * active * batch / read
print([round(intensity(cfg, b), 1) for b in (1, 16, 64, 256, 1024)])
# [2.0, 4.4, 8.3, 29.0, 115.9]
Two FLOPs per byte at batch 1. To know whether that is bad I measured the ridge point of the GPU everything in this article ran on, a B300, instead of quoting a datasheet: a large bf16 GEMM reaches 1,717 TFLOP/s, an fp8 one reaches 4,155, and a large copy reaches 6.47 TB/s, so a kernel needs 265 FLOPs per byte in bf16 or 642 in fp8 before the tensor cores become the limit rather than memory. A decode step at batch 1 is more than 300 times below that line, and even at batch 1,024 it is five times below it.
This is the single most useful fact in the article, because it tells you ahead of time that a faster matrix multiply will not help you and fewer bytes will.
The right-hand panel of Figure 2 is the part that is specific to mixture-of-experts models. A single token touches 8 of 256 experts, so you might expect to read only 3% of the expert table. That is true at batch 1, where 3.1% of experts get a token. But the experts a token picks are nearly independent across tokens, so the union grows fast: at batch 16 the batch touches 39.8% of the experts, at batch 64 it touches 86.9%, and at batch 256 it touches all of them. Past that point the engine is reading the entire 677 GiB expert table on every decode step, regardless of how few tokens it is serving, which is why an MoE is harder to serve efficiently than a dense model with the same number of active parameters.
Everything after this section is an attempt to move fewer bytes, launch fewer kernels, or get more tokens into the batch that reads those bytes.
2. The Parallelism Map
A model this size does not fit on a GPU, so before we go further we need a shared vocabulary for the ways of cutting it up. There are five axes in common use, and the thing to remember about each one is not what it cuts but what it makes the GPUs say to each other.
Tensor parallelism cuts every weight matrix into slices, gives each GPU a slice, and has each GPU compute a partial result. Since those partials have to be added back together, every layer ends in an all-reduce of the hidden state, which is small per token but happens twice per layer and cannot be overlapped with anything that needs its result.
Expert parallelism hands whole experts out to GPUs. A token's hidden state travels to the GPUs that hold its chosen experts, gets processed there, and comes back. That is an all-to-all in each direction, and its size depends on how many tokens are in flight, not on the model's width.
Data parallelism over attention, usually written DP-attention, gives each rank its own batch of sequences and a full copy of the attention weights, so attention costs no communication at all. The ranks only have to come together to feed the MoE block, which they do with one gather.
Pipeline parallelism cuts the layers into stages. Each boundary costs one activation per micro-batch, which is the cheapest message on this list, and buys the most idle time at the start and end of a batch.
Context parallelism cuts a single sequence across ranks, which is the only one of the five that helps when one sequence is too long for one GPU. Its cost is that the keys and values have to travel, and section 10 is about what that costs. Figure 3 puts all five side by side.
As Figure 3 shows, these are not alternatives so much as a set of dials, and a real deployment sets several of them at once. For a large MoE at rollout time the usual combination is expert parallelism for the experts and DP-attention for everything else, and the reason is in the parameter count from section 1: with 97.6% of the parameters in the experts, slicing the experts with tensor parallelism would pay an all-reduce per layer for the privilege of having every rank do a thin slice of every expert, while expert parallelism moves only the tokens that were actually routed.
3. Batching and Scheduling
Figure 2 said that everything depends on the decode batch size, so the scheduler is the most important component in the engine, and it has three jobs.
The first is continuous batching: when a sequence finishes, its slot is given to a waiting request immediately rather than at the end of the current batch. Without it, a batch of 64 requests runs at the speed of its longest member and spends most of its life nearly empty.
The second is chunked prefill. A prefill of a 4,000-token prompt is a large piece of work, and if the engine runs it as one forward pass then every sequence that is decoding has to wait for it. Chunking it into pieces of a few hundred tokens lets the scheduler interleave prefill chunks with decode steps, which trades a little prefill throughput for a much steadier token rate.
The third is deciding whether prefill and decode belong on the same GPUs at all. Prefill/decode disaggregation puts them on separate engines and ships the KV cache between them, because the two phases want opposite things: prefill wants as many tokens per batch as it can get, and decode wants as many sequences per batch as it can get, and a single engine serving both ends up compromising on each.
Here is where an RL rollout differs from a chat workload, and it differs in a way that works against all three. A GRPO step launches a few thousand requests at the same moment, all of them already in the queue, so the batch starts as wide as the engine allows and continuous batching has nothing to do. Then the completions end at wildly different lengths, because a model that is being trained to reason writes 200 tokens for an easy problem and 8,000 for a hard one. The batch narrows as the easy ones finish, and the last stretch of the step is a handful of long rollouts decoding almost alone. That tail is the batch-1 column of Figure 2, and it is the reason the small-batch behaviour of every mechanism below is worth knowing.
4. Prefix Caching and the GRPO Group
There is one piece of structure in an RL rollout that a chat workload does not have, and it is worth a lot. GRPO samples a group of G completions for the same prompt in order to compute advantages within the group. Those G requests have byte-identical prompts.
A prefix cache turns that into one prefill instead of G. The mechanism is a tree keyed on token ids: every request walks down the tree as far as its tokens match, reuses the KV cache for the matched part, and only computes the rest. sglang keeps that tree in RadixCache, and the lookup is match_prefix, which also splits a node when a match ends in the middle of a stored run so that later lookups land on a boundary:
# sglang/python/sglang/srt/mem_cache/radix_cache.py:RadixCache.match_prefix
# @ d5d87899f9 (excerpt, with the docstring and the disabled-cache path cut)
key = params.key
key, _ = key.maybe_to_bigram_view(self.is_eagle)
if self.disable or len(key) == 0:
return self._empty_match_result
key = key.page_aligned(self.page_size)
value, last_node = self._match_prefix_helper(self.root_node, key)
return MatchResult(
device_prefix_len=sum(len(v) for v in value),
last_device_node=last_node,
last_host_node=last_node,
best_match_node=last_node,
)
The RadixKey in that signature carries an optional extra_key alongside the tokens, which exists so that two requests with the same tokens but a different adapter, or a different cache version, are kept in separate parts of the tree and never share a node. We will need that idea again in a moment.
To put a number on it I took real prompts rather than invented ones: 256 rows of the DAPO-Math set that RL recipes use, rendered through GLM-5.3's own chat template and tokenized with its own tokenizer. They come to 87 tokens on average, 80 at the median, and 234 at the longest. For a batch of 64 prompts, counting the tokens an engine would have to prefill, a group size of 1 gives nothing to share: 5,744 tokens get prefilled, of which the tree stores 5,002 because a few prompts happen to share short runs. At a group size of 4, the uncached count is 22,976 and the tree still stores 5,002, which is 4.6 times less. At 16 it is 91,904 against 5,002, or 18.4 times less. At 32 it is 183,808 against 5,002, or 36.7 times less, as Figure 4 shows.
Figure 4 also shows where the sharing stops, which is exactly at the first sampled token. After that the G completions diverge and every one of them needs its own cache, so the saving is bounded by the prompt's share of the sequence. That is the honest caveat here: with 87-token prompts and thousands of generated tokens, 18.4 times less prefill is 18.4 times less of a small number. One uncached G=16 step is 91,904 prefill tokens, which is about 90 decode steps' worth of tokens for the same batch, so we are talking about a few percent of the step rather than a factor.
Two things make it matter more than that sounds. The first is that the ratio is what makes multi-turn rollouts affordable at all. In an agentic rollout, turn n's prompt is turn n-1's prompt plus the model's answer plus whatever the environment returned, so the uncached prefill cost of a T-turn trajectory grows with T squared while the cached cost grows with T. For a long-horizon rollout that is the difference between feasible and not.
The second is the thing the extra_key hinted at. The cache is keyed on token ids and knows nothing about weights. When the trainer finishes a step and pushes new weights into the rollout engine, every KV entry in that tree was computed by the old model and is now wrong, so the whole cache has to be dropped. An RL rollout therefore starts every step with a cold cache, which is not true of a serving deployment, and it means the prompt sharing inside a group is the only sharing you reliably get.
5. The Router, and Two Kinds of Load Balance
Inside a sparse layer, the first thing that happens to a token is that its hidden state is multiplied by a 256 by 6,144 gate matrix to produce one score per expert, and the top 8 scores win. The mechanism is three lines of code. The problem it creates takes the rest of this section.
The problem is load balance. The experts live on different GPUs, and a step is not finished until the slowest GPU is finished, so if the router sends a quarter of the tokens to one expert then that expert's GPU does a quarter of the work and the others wait. Worse, a router left to itself tends to collapse: an expert that gets more tokens trains faster, which makes it better, which makes the router send it more tokens.
There are two ways to fight that, and current models have mostly moved from the first to the second.
The first is an auxiliary loss. You add a term to the training loss that is small when the tokens are spread evenly and large when they are not, and let the gradient push the router towards balance. Megatron's version is the one from the Switch Transformer paper, which multiplies the fraction of tokens each expert received by the average probability the router assigned it:
# Megatron-LM/megatron/core/transformer/moe/moe_utils.py
# :switch_load_balancing_loss_func @ 54f18cd21 (excerpt)
aggregated_probs_per_expert = probs.sum(dim=0)
aux_loss = torch.sum(aggregated_probs_per_expert * tokens_per_expert) * (
num_experts * moe_aux_loss_coeff
/ (topk * total_num_tokens * total_num_tokens)
)
This works, and it has a cost that is easy to state: the gradient it produces is not the gradient of the thing you wanted the model to do. You are asking the router to be balanced and asking the model to be good at the task with the same set of weights, and the coefficient in front of the auxiliary loss is you choosing how much of one to trade for the other.
The second way, which DeepSeek-V3 popularized and GLM-5.3 uses, avoids that trade. Keep one number per expert, add it to the scores only for the purpose of choosing, and leave the scores that get used as mixing weights alone. sglang's reference implementation of the top-k shows the whole idea in six lines:
# sglang/python/sglang/srt/layers/moe/topk.py:fused_topk_torch_native
# @ d5d87899f9 (excerpt)
if correction_bias is not None:
n_routed_experts = gating_output.shape[-1]
scores = scoring_func_impl(gating_output)
scores_for_choice = scores.view(
-1, n_routed_experts
) + correction_bias.unsqueeze(0)
topk_ids = torch.topk(scores_for_choice, k=topk, dim=-1, sorted=False)[1]
topk_weights = scores.gather(1, topk_ids)
scores_for_choice decides which experts run, and scores decides how much each one counts. Because the bias never reaches topk_weights, nudging it cannot change what the model computes for a fixed set of chosen experts, which is why this does not fight the task loss the way an auxiliary loss does. It also means the bias has no gradient and has to be maintained by hand. Megatron maintains it by counting:
# Megatron-LM/megatron/core/transformer/moe/moe_utils.py
# :get_updated_expert_bias @ 54f18cd21 (excerpt)
torch.distributed.all_reduce(tokens_per_expert, group=tp_dp_cp_group)
num_experts = tokens_per_expert.shape[-1]
total_tokens = tokens_per_expert.sum(dim=-1, keepdim=True)
update_direction = torch.sign(total_tokens - tokens_per_expert * num_experts)
updated_expert_bias = (
expert_bias
+ update_direction.to(dtype=expert_bias.dtype) * expert_bias_update_rate
)
Count the tokens each expert got, all-reduce those counts across every rank that shares the router, and move each expert's bias by a fixed step up if it was below average and down if it was above. The comparison is done without dividing, since tokens_per_expert < total / num_experts is the same as tokens_per_expert * num_experts < total and the counts are integers.
Figure 5 draws both paths, and the thing to notice is the arrow that is missing on the right: nothing goes from the bias into the weights. How much does that bias actually have to move? I read it out of the shipped checkpoint, which turned out to be more interesting than I expected. At layer 3 the 256 biases have a mean of 34.46 and run from 33.99 to 34.62. At layer 41 the mean is 6.64 and the span is 0.43. At layer 78 the mean is 15.72 and the span is 0.40.
The means look alarming next to a sigmoid score that lives between 0 and 1, but they do not matter at all, since adding the same constant to all 256 experts cannot change which 8 are largest. The span is what routes tokens, and the span is 0.4 to 0.64 against a score range of 1. The balancing term is therefore not a small correction on top of a router that mostly agrees with it. It is comparable in size to the router's own opinion, which I read as a sign that the raw router really would collapse without it.
I should mention a third mechanism and then skip it. Some implementations give each expert a fixed capacity and drop the tokens that overflow, which bounds the imbalance by throwing work away. sglang does not drop tokens during inference, and GLM-5.3's config has no capacity factor, so I will leave capacity alone.
Now the part that is specific to RL, and it is the reason this section is here at all. Even a perfectly uniform router leaves you with an unbalanced step when the batch is small, because picking 8 of 256 experts for each of a handful of tokens is a sampling problem. I simulated it with a uniform router and 2,000 draws per point. With 32 tokens in the step there are 256 expert slots to spread over 256 experts, the average expert gets 1, and the busiest gets 4.63 while 36.2% of experts get nothing at all. At 128 tokens the busiest gets 2.64 times the mean. At 512 it is 1.76, at 2,048 it is 1.36, and at 8,192 it is 1.18, which is what Figure 6 draws.
Figure 6 is a fact about multinomial draws and not about any model, which is the point. In the shaded region, which is the tail of an RL rollout, nothing you do to the router will balance the step, because the imbalance is coming from the batch size. The only fixes available there are the ones that make the batch bigger or make the imbalance cheaper, and we will see the second one in section 7.
There is one more way the router causes trouble in RL, and it has nothing to do with balance. The rollout engine and the trainer run the same router on the same weights, but not with the same kernels, the same precision, or the same batch shapes. The top-8 of a sigmoid is a hard threshold, so two scores that differ in the last bits can swap places, and then the trainer computes its gradient against an expert that the rollout never used. The fix in current RL frameworks is to stop recomputing the routing: the rollout engine returns the expert ids it actually used, and the trainer replays them. In sglang this is a per-request flag, return_routed_experts, which threads from the request struct through the scheduler to the output. The metadata it returns has shape (sequence length minus one, layers, top-k) in int32, which miles documents as roughly 60 MB per 32K-token sample at 60 layers and top-8. That is a real amount of memory to move per sample, and it buys bit-identical expert allocation between the two engines.
To put this section in one line before we move on: balance is maintained by a bias that only affects selection, the real trained spread of that bias is about half the router's score range, and at the batch sizes an RL rollout ends on, the imbalance you see is the batch and not the router.
6. Expert Parallelism and the All-to-All
With 9.70 billion parameters of experts in every sparse layer, the experts have to live on different GPUs, which means the tokens have to travel. Dispatch sends each token's hidden state to the ranks that hold its chosen experts. Combine brings the outputs back and sums them with the router weights.
The detail that decides how expensive this is comes from DeepEP, the library that implements both directions. Its layout kernel returns a tensor called is_token_in_rank with shape [num_tokens, num_ranks], which tells you that the unit of dispatch is the rank, not the expert. If three of a token's 8 experts happen to live on the same GPU, the token is sent there once and used three times. The traffic therefore depends on how many distinct ranks a token's 8 experts land on, and that is a question we can answer exactly:
import math
E, K = 256, 8
def expected_distinct_ranks(num_ranks):
"""How many ranks hold at least one of a token's K chosen experts."""
per_rank = E // num_ranks
p_none = math.comb(E - per_rank, K) / math.comb(E, K)
return num_ranks * (1 - p_none)
for r in (4, 8, 16, 32, 64):
print(r, round(expected_distinct_ranks(r), 3))
# 4 3.614
# 8 5.295
# 16 6.523
# 32 7.267
# 64 7.676
At an expert-parallel size of 8, each rank holds 32 experts and a token reaches 5.3 of the 8 ranks, so the deduplication saves a third of the sends. At 32 ranks it reaches 7.3 of 8, and at 64 ranks, where each rank holds only 4 experts, it reaches 7.68 of 8 and the deduplication has stopped doing anything useful. I checked the formula against a Monte Carlo draw and they agree to three digits, which is a good use of ten lines of code before trusting an analytic result.
Now the payload. sglang quantizes the hidden state to fp8 before dispatch and combines in bf16, which is the asymmetry you want, because the dispatch is an input to a GEMM that would quantize it anyway and the combine is a sum of outputs that you do not want to round twice. The dispatch call sits right at the top of the normal-mode dispatcher:
# sglang/python/sglang/srt/layers/moe/token_dispatcher/deepep.py
# :_DeepEPDispatcherImplNormal.dispatch_a @ d5d87899f9 (excerpt)
topk_weights, topk_ids = topk_output.topk_weights, topk_output.topk_ids
topk_ids = topk_ids.to(torch.int64)
if deep_gemm_wrapper.ENABLE_JIT_DEEPGEMM and self.use_fp8:
# TODO hard code 128 block quant,use fp8 communication
hidden_states = sglang_per_token_group_quant_fp8(
hidden_states,
128,
column_major_scales=deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0,
scale_tma_aligned=deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0,
scale_ue8m0=deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0,
)
The group size of 128 means one scale per 128 channels, and those scales are ue8m0, which is an exponent and nothing else, packed four to an int32. A dispatched token is therefore 6,144 fp8 values plus 48 scale bytes, or 6,192 bytes, and a combined token is 6,144 bf16 values, or 12,288 bytes.
Multiply those by the rank counts above. At an expert-parallel size of 32, one token's dispatch costs 7.267 x 6,192 = 44,996 bytes and its combine costs 7.267 x 12,288 = 89,294 bytes, for 134,290 bytes in total. The token's own hidden state in bf16 is 12,288 bytes, so moving one token through one MoE layer puts 10.9 times the token's size on the wire. At 64 ranks it is 11.5 times, as Figure 7 shows.
The reason the right-hand side of Figure 7 barely deduplicates is just the pigeonhole: 8 experts spread over 64 ranks of 4 experts each are almost certainly on 8 different ranks. This is the main argument against pushing the expert-parallel size as high as it will go. You get smaller weights per rank and more aggregate bandwidth, and you pay for it with traffic that approaches top-k times the hidden state per token per layer, in both directions.
DeepEP's answer to the two phases having different needs is to ship two different sets of kernels, and the split is the same prefill-versus-decode distinction from section 1. The normal kernels are built for throughput: they forward between the NVLink domain inside a node and the RDMA domain between nodes, they let you control how many SMs they use, and they are what you run for training and for prefill, where there are thousands of tokens per batch and the thing you care about is bytes per second. The low-latency kernels are pure RDMA, built for decode, where there are a few tokens per rank and the thing you care about is the fixed cost. They also return a receive hook instead of blocking, so the transfer happens in the background without occupying any SMs, which is what lets an engine overlap one micro-batch's all-to-all with another micro-batch's attention.
Per rank, the traffic at an expert-parallel size of 32 comes to 0.13 MB per layer when each rank has one token, and 68.76 MB per layer when each rank has 512, which is 5.16 GB per rank per step across the 75 sparse layers. The first of those numbers is why decode all-to-all is a latency problem and not a bandwidth problem: there is nothing to amortize the round trip over.
7. The Expert GEMM
After dispatch, a rank is holding a pile of token rows, each of which belongs to one of the experts it owns. Every group needs a different weight matrix, so this is not one matrix multiply, and the question is how to make it behave like one.
The straightforward way is a loop: select the rows for expert 0, multiply them by expert 0's weights, and repeat. The problem is that each of those multiplies is small, and a small GEMM leaves most of the GPU idle while still paying for the full weight read.
The alternative is a grouped GEMM, which takes all the rows at once plus a group id per row and does the whole thing in one kernel. The arithmetic is identical:
import torch
torch.manual_seed(0)
G, N, Kd = 8, 256, 512
rows = [40, 70, 10, 90, 55, 30, 65, 20]
w = torch.randn(G, N, Kd)
a = torch.randn(sum(rows), Kd)
ids = torch.repeat_interleave(torch.arange(G), torch.tensor(rows))
loop = torch.cat([a[ids == i] @ w[i].T for i in range(G)])
grouped = torch.einsum("rk,rnk->rn", a, w[ids])
print(torch.allclose(loop, grouped, atol=1e-3))
# True
The einsum above is a readable stand-in and not what you would run. The real kernels are DeepGEMM's m_grouped_bf16_gemm_nt_contiguous and its fp8 sibling, which want each group's rows to be contiguous and to start on a multiple of 128, and which mark padding rows with a group id of -1 so they can skip them. (Megatron and Transformer Engine have their own version of the same idea in GroupedLinear, which also carries the backward pass.) That alignment requirement is not an implementation detail you can ignore, because it reaches all the way back into the previous section: sglang passes expert_alignment=128 to DeepEP's dispatch so that the rows arrive already padded to the boundary the GEMM needs.
I measured both at GLM-5.3's expert shapes on a B300, with CUDA graphs on and the GPU time taken from CUPTI, so none of these numbers include the cost of launching anything. The first sweep holds the work fixed at 8,192 expert-token rows and varies how many local experts they are spread over, which is what changing the expert-parallel size does to one rank. With 8 experts of 1,024 rows each, the loop takes 263.8 microseconds and the grouped kernel 266.7, so there is nothing to win. With 32 experts of 256 rows each it is 508.2 against 340.9. With 256 experts of 128 rows each it is 3,074.3 against 2,281.3.
I want to be careful about what that sweep shows, because it moves two things at once. Spreading the same rows over more experts also means more expert weights on the rank, from 384 MiB at 8 experts to 12 GiB at 256, and both kernels have to read those bytes. The growth in absolute time is mostly the bytes, and the growth in the ratio is the tiles: the grouped kernel keeps the GPU full with small groups and the loop does not.
The second sweep is the one that matters for RL. Fix the expert-parallel size at 32, so a rank holds 8 experts, and draw the row counts from a uniform router as the step size grows. A 64-token step puts 16 rows on the rank, which pad to 896, so 98% of the rows the kernel processes are padding; the kernel takes 74.9 microseconds and delivers 11 TFLOP/s of useful work. A 256-token step: 64 rows, 94% padding, 82.4 microseconds, 39 TFLOP/s. A 1,024-token step: 256 rows, 75% padding, 82.6 microseconds, 156 TFLOP/s. A 4,096-token step: 1,024 rows, 38% padding, 90.0 microseconds, 573 TFLOP/s. A 16,384-token step: 4,096 rows, 6% padding, 159.8 microseconds, 1,290 TFLOP/s.
As Figure 8 shows, the same kernel reading the same weights spans a factor of 117 in useful throughput, and it is not because the kernel got better. At a 64-token step the rank has two rows per expert and has to round each group up to 128, so it does 56 times more multiply-adds than the tokens need, and the time barely moves between 64 tokens and 1,024 because the kernel is reading the weights either way. This is section 1 again from a different angle: below a certain batch size you are paying for the model and not for the tokens.
Running the experts in fp8 instead of bf16 helps where it matters, since it halves the weight bytes. At 8 local experts the fp8 grouped kernel takes 163.4 microseconds against the bf16 kernel's 266.7, which is 1.63 times faster, and its output differs from the bf16 result by a relative error of 0.0377 on random inputs. Whether that error is acceptable is section 12's problem.
8. The KV Cache
Attention is the other half of a decode step, and its cost is a different shape. The weights are read once per step regardless of the context length, but the keys and values of every earlier token have to be read too, so attention's bytes grow with how far into the completion you are. For a long rollout that term ends up dominating, and more importantly the cache is what bounds how many rollouts you can run at once, because the cache is the thing that does not fit.
There are three layouts in common use, and they are best understood as three answers to one question: what do you store per token?
Multi-head attention stores a key and a value for every head. With 64 heads of 256 dimensions, that is 64 x 256 x 2 values per token per layer.
Grouped-query attention has several query heads share one key and value, so if you have 8 groups you store 8 keys and 8 values instead of 64 of each. This is the standard choice and it is a straight division of the cache by the group count. Multi-query attention is the same idea taken to one group, which divides the cache by the head count and is the most aggressive version of it.
Multi-head latent attention, which is what the reference model uses, stores neither. It stores one low-rank vector per token, from which the kernel reconstructs the per-head keys and values when it needs them, plus a small shared piece that carries the rotary positions for all heads at once. sglang's pool for it is exactly that wide:
# sglang/python/sglang/srt/mem_cache/memory_pool.py:MLATokenToKVPool
# @ d5d87899f9 (excerpt)
self.kv_lora_rank = kv_lora_rank
self.qk_rope_head_dim = qk_rope_head_dim
self.use_dsa = use_dsa
self.kv_cache_dim = (
override_kv_cache_dim
if self.dsa_kv_cache_store_fp8
else (kv_lora_rank + qk_rope_head_dim)
)
For GLM-5.3 that is 512 + 64 = 576 values per token per layer, in one buffer rather than two. The comparison across the three layouts on the same model's dimensions is a four-line calculation:
L, heads, v_head, kv_lora, qk_rope = 78, 64, 256, 512, 64
mha = L * 2 * heads * v_head * 2 # K and V per head, bf16
gqa8 = L * 2 * 8 * v_head * 2 # 8 key-value groups
mla = L * (kv_lora + qk_rope) * 2 # one latent vector per token
print(mha, gqa8, mla, round(mha / mla, 1), round(gqa8 / mla, 2))
# 5111808 638976 89856 56.9 7.11
Figure 9 puts those three numbers on the same scale: 5,111,808 bytes per token for multi-head, 638,976 for grouped-query with 8 groups, and 89,856 for the latent layout, which is 56.9 times less than multi-head and 7.1 times less than grouped-query. At a 131,072-token context that is 624 GiB against 10.97 GiB, which is the difference between one sequence not fitting on a node and eighty sequences fitting on one GPU.
Two more factors stack on top. The cache can be stored in fp8, which halves the latent to 44,928 bytes per token, and this is a comparatively easy place to use fp8 because the values are read once and never accumulated into. And GLM-5.3's sparse attention carries a second, smaller cache for its index, at 128 fp8 values per token per layer, which adds 9,984 bytes and brings the real total for an fp8 deployment to 54,912 bytes per token.
The one idea in this area that the reference model does not use for keys and values is sharing the cache across layers: letting layer 2 attend to the keys and values that layer 1 already computed, so that a group of layers costs one cache entry instead of several. It divides the cache by the group size and it costs you some of the model's ability to look at different things at different depths. GLM-5.3 does apply exactly this idea, but to its sparse-attention index rather than to K and V: of its 78 layers, 21 compute a full index and 57 share one, in groups of four. I take that as a sign that the technique is considered safe for the cheap auxiliary cache and not yet for the main one, though that is my reading and not something the model card says.
9. Low-Batch Decode and the Cost of Launching Kernels
We have established that a decode step at a small batch does very little arithmetic. Here is the consequence: it can cost more to tell the GPU to do the work than to do it.
Every kernel launch is a call that has to go through the driver and land in a queue, and that costs host time whether the kernel is big or small. To measure it on its own I enqueued chains of trivial kernels and timed the enqueue without synchronizing inside the timed region, so that what I measured is the cost of getting work onto the stream and not the cost of running it. A hundred kernels took 0.354 ms, a thousand took 3.475 ms, and five thousand took 17.264 ms, which is 3.45 microseconds each and admirably linear.
A CUDA graph is the fix. You record the whole sequence of launches once, and from then on you replay the entire recording with a single call into the driver. Those same five thousand kernels, captured and replayed, took 0.005 milliseconds. That is the launch cost of five thousand kernels collapsing into the launch cost of about one.
The catch is that a graph is a recording of specific launches with specific pointers and specific sizes, so it only works for a shape you have already seen. An engine deals with that by capturing a list of batch sizes up front and padding the real batch up to the nearest one:
# sglang/python/sglang/srt/model_executor/runner/base_cuda_graph_runner.py
# :get_batch_sizes_to_capture @ d5d87899f9 (excerpt)
capture_bs = list(get_exec().graph.cuda_graph_config.decode.bs)
num_max_requests = model_runner.req_to_token_pool.size
mul_base = get_cuda_graph_batch_size_alignment(
gathered_buffer_required=gathered_buffer_required
)
num_max_requests = ceil_align(num_max_requests, mul_base)
if max(capture_bs) > num_max_requests:
capture_bs += [num_max_requests]
capture_bs = [bs for bs in capture_bs if bs * alignment_width % mul_base == 0]
capture_bs = [bs for bs in capture_bs if bs <= num_max_requests]
capture_bs = list(sorted(set(capture_bs)))
That padding is the price. A batch of 17 running in a graph captured for 24 does 24 batch rows' worth of work, and the engine has to hold a captured graph and its buffers in memory for every size in the list, which is memory that the KV cache does not get.
How many kernels is a real step? To find out I built a decode stack with GLM-5.3's per-layer shapes: the MLA projections at their real widths, the router, the shared expert, and the 8 routed experts of an expert-parallel-32 rank through DeepGEMM's grouped kernel, with distinct weights for all 78 layers. Two things in it are not real, and they matter for reading the numbers: attention is a stand-in made of two batched matmuls against a latent cache of the right shape rather than a real MLA kernel, and the weights are bf16 rather than fp8. The absolute times are therefore not what sglang would give you. The kernel count and the eager-versus-graph gap are the parts I trust.
At batch 1 the step launches 5,190 kernels and takes 36.05 ms eagerly, against 25.53 ms as a graph replay, which is 1.41 times faster. At batch 4 it is 36.71 against 27.57. At batch 16, 36.52 against 32.24. At batch 64, 52.04 against 51.20, where the graph has stopped mattering. Figure 10 draws both parts of the measurement.
Figure 10 also explains why the gap closes. 5,190 kernels at 3.45 microseconds each is 17.9 ms of host work, and a graph replay of the same step costs 0.005 ms, so the graph's 25.5 ms is essentially pure GPU time. Eagerly, the host is issuing launches while the GPU runs them, and the two overlap right up to the point where the host cannot keep ahead. At batch 1 with bf16 weights the GPU needs 25.5 ms and the host needs 17.9, so the host is just under and the graph still wins 1.41 times, which tells me the overlap is imperfect. With fp8 weights, which halve the bytes and therefore most of the GPU time, the host number would be the larger of the two. At batch 64 the GPU has enough work that 17.9 ms of launches hide completely.
This is also the argument behind the recent work on fusing a whole decode forward pass into a handful of kernels rather than a few thousand. A graph removes the launch cost but not the number of kernels, and each kernel boundary is still a round trip through HBM for the intermediate it produced. Fewer, bigger kernels remove both, and at batch 1 both are the cost.
For RL, the connection is the tail again. A rollout step's last stretch runs at a batch of a few, which is exactly where a step is 5,000 kernels of almost no work each, so graph capture is not an optimization there. It is the thing that makes the tail finish.
10. Long Context, and Why a Ring Needs Striping
Long-horizon rollouts produce long sequences, and at some point a single sequence does not fit on one GPU, either because its activations do not fit during prefill or because its KV cache does not. Context parallelism splits one sequence across ranks.
The usual implementation is a ring. Each rank holds a slice of the queries, keys and values. Every rank computes attention between its queries and its own keys, then the key and value blocks rotate one step around the ring, every rank computes again, and after as many steps as there are ranks each query has seen every key. The appeal is that nothing is ever gathered: the only thing on the wire is a key-value block, and it moves to a single neighbour.
Then you add a causal mask and the balance falls apart. A query at position 100 attends to 100 keys and a query at position 32,000 attends to 32,000, so if you give rank 0 the first eighth of the sequence and rank 7 the last eighth, rank 7 does far more work. Counting the query-key pairs exactly is short enough to do in the article:
import numpy as np
S, R = 32768, 8
def work(kind):
if kind == "contiguous":
n = S // R
parts = [np.arange(r * n, (r + 1) * n) for r in range(R)]
else:
parts = [np.arange(r, S, R) for r in range(R)]
return np.array([sum(int(np.searchsorted(k, q, "right").sum())
for k in parts) for q in parts])
for kind in ("contiguous", "striped"):
w = work(kind)
assert w.sum() == S * (S + 1) // 2
print(kind, round(w.max() / w.mean(), 3))
# contiguous 1.875
# striped 1.0
For 32,768 tokens over 8 ranks, the contiguous split gives the first rank 8,390,656 pairs and the last 125,831,168, with the busiest rank at 1.875 times the mean. Since a ring step cannot finish until every rank's part of it has finished, and the next rotation waits for the step, that factor of 1.875 is the step time: 46.7% of the ranks' time is spent waiting.
The fix is to stop giving each rank a contiguous run. If rank r takes tokens r, r + 8, r + 16 and so on, every rank gets an even mix of early and late positions, and the counts come out at 67,096,576 to 67,125,248, with the busiest rank at 1.000 times the mean. A variant that production frameworks prefer cuts the sequence into 2R chunks and gives rank r chunk r and chunk 2R - 1 - r, which pairs an early chunk with a late one. That lands at exactly 67,110,912 pairs for every rank, which is what Figure 11 compares.
Figure 11 shows why the paired-chunk version is the one in Megatron and in sglang's context-parallel path rather than the single-token stripe: it gets the same perfect balance while keeping each rank's tokens in two contiguous runs, which the attention kernels and the KV cache layout both prefer. Striping by single tokens balances just as well and is easier to reason about, which is why I used it in the snippet.
For a rollout, context parallelism is a prefill mechanism. During decode there is one query token per sequence, there is no triangle to split, and the imbalance question does not come up.
11. Speculative Decoding and the Acceptance Rate
Section 1 said that a decode step reads a fixed pile of weights no matter how few tokens it serves. Turn that around and it becomes an opportunity: if one token is nearly free to run, so are four, and we can spend the spare capacity on guessing ahead.
That is speculative decoding. A cheap draft proposes the next d tokens, the expensive target model runs a single forward pass over all d of them at once, and the proposals are checked against what the target would have produced. Every prefix of the draft that matches is committed, the first mismatch is replaced by the target's own token, and the rest is thrown away. The output distribution is unchanged, which is the part that makes this safe to use in RL: you are not approximating the policy, you are computing the same thing faster.
Drafts come in two shapes, and the difference is whether the draft positions can see each other. A sequentially-dependent draft head feeds its own output back in, so the i-th proposal is conditioned on the first i - 1 and the guesses are good, at the price of d sequential runs of the head. An independent head predicts all d positions from the same hidden state in one go, which is cheaper and visibly worse, because position 3's prediction has no idea what position 2 guessed. GLM-5.3 ships one multi-token-prediction layer in its checkpoint, which is used the sequential way.
How much does that buy? For a linear chain of depth d where each position is accepted with probability p, the expected number of committed tokens per verify is the sum of p to the i for i from 0 to d, counting the free token the target always produces:
def accepted(p, d):
"""Expected committed tokens per verify for a chain draft of depth d."""
return sum(p ** i for i in range(d + 1))
for d in (1, 3, 7):
print(d, [round(accepted(p, d), 2) for p in (0.5, 0.8)])
# 1 [1.5, 1.8]
# 3 [1.88, 2.95]
# 7 [1.99, 4.16]
The numerator is easy. The denominator is the part people get wrong, so I measured it on the same decode stack from section 9, with the same caveats about it being a stand-in. At batch 1, a one-token step takes 23.61 ms and verifying 2, 4 and 8 tokens per sequence takes 25.05, 25.71 and 27.16 ms, which is 1.06, 1.09 and 1.15 times the one-token step. Verification really is nearly free. At batch 16, the one-token step takes 30.40 ms and the same three take 36.53, 49.46 and 79.03, which is 1.20, 1.63 and 2.60 times. Verification is no longer free, because 16 sequences times 8 draft tokens is 128 rows and the GEMMs have started to care.
The draft side is cheap either way. One step of the single MTP layer took 0.312 ms at batch 1 and 0.402 ms at batch 16, which is 1.3% of a target step in both cases.
Put the two together and you get the break-even acceptance probability, the point where the scheme stops being worth it. At batch 1 a depth-1 draft needs p of at least 0.074, depth 3 needs 0.114, and depth 7 needs 0.195. At batch 16 the same three need 0.215, 0.418 and 0.639.
The right-hand panel of Figure 12 says most of what you need to decide a configuration: at batch 1 you can afford to guess deeply and badly, and at batch 16 a depth-7 draft that is right two times in three is a loss. sglang's adaptive controller encodes exactly this, as a table of which depths are even worth trying at which batch size:
# sglang/python/sglang/srt/speculative/adaptive_spec_params.py
# :DEFAULT_ADAPTIVE_CONFIG @ d5d87899f9 (excerpt, hysteresis fields cut)
DEFAULT_ADAPTIVE_CONFIG: dict[str, dict] = {
"1": {
"candidate_steps": [1, 3, 5, 7],
# ...
},
"8": {
"candidate_steps": [0, 1, 3],
# ...
},
"32": {
"candidate_steps": [0, 1],
# ...
},
"64": {
"candidate_steps": [0],
# ...
},
}
Depth up to 7 at batch 1, up to 3 at batch 8, up to 1 at batch 32, and nothing at all at batch 64. At runtime the controller keeps an exponential moving average of how many draft tokens were accepted per request and steps down a tier when that average drops below the next-lower depth, with a little hysteresis so it does not oscillate.
Now the RL-specific failure. Everything above assumed a fixed acceptance rate, and in RL the acceptance rate decays, because every training step moves the target's distribution and the draft was trained against an older one. The miles documentation states the consequence directly: over many steps speculative decoding can become a net negative, because the wasted draft compute outweighs the verified speedup. Combine that with the break-even numbers and you can see how it happens: at batch 16 and depth 7 you need p above 0.639, and a draft that was good enough at step 0 does not stay above that line for a thousand steps.
The two answers are both about keeping the draft current. If the draft is an MTP layer that lives in the checkpoint, you can train it alongside the policy, which miles does with --enable-mtp-training and a loss weight of 0.2. If the draft is a separate model, there is no online path and you retrain it offline every so often and reload it. Either way, the thing to monitor during an RL run is the accepted length, and the thing to be ready to do is turn speculation off.
12. Low-Bit Weights, and Why Activations Are Harder
Fewer bytes per weight is the most direct attack on everything in section 1, which is why the reference checkpoint already ships in fp8. The question this section answers is why weights are the easy half.
Quantizing means replacing a group of numbers with small integers and a scale that the hardware multiplies back in. The error depends almost entirely on how the group is chosen, because one scale has to cover the largest number in its group, and every number much smaller than that loses precision. The design space is therefore the grouping: one scale for the whole tensor, one per row, one per block, or one per handful of values with a second scale above it. Figure 13 draws those four on the same little matrix.
The dark column in Figure 13 is the thing that decides which grouping you need. GLM-5.3's own choice, from its config, is fp8 e4m3 with one scale per 128 by 128 block of each weight matrix and dynamic per-token scales for activations. Its config also lists 541 modules the quantizer was told to leave alone, and that list is a good map of where low precision hurts: every one of the 79 input and post-attention layernorms, every q_a_layernorm and kv_a_layernorm, all 76 router gates and their correction biases, the indexer norms, the embedding, and the output head. Nothing with a small number of parameters and a large influence gets quantized.
To see how much the grouping matters I took two real weight matrices out of the checkpoint, dequantized them from their shipped fp8 using their real block scales, and then requantized them four ways. The first is expert 0's down_proj at layer 40, which is 6,144 by 2,048 with a 48 by 16 grid of block scales. Those scales run from 1.330e-04 to 2.038e-04, a span of only 1.5 times, so the matrix is nearly uniform: one scale for the whole tensor gives a relative error of 0.00349, per output channel gives 0.00233, and the real 128 by 128 blocks give 0.00074.
The second is o_proj at the same layer, 6,144 by 16,384, and its block scales run from 1.237e-04 to 1.212e-03, a span of 9.8 times, with the largest block 7.0 times the median. Here the grouping matters a lot: one scale for the whole tensor gives 0.01830, per output channel gives 0.00304, and the real blocks give 0.00087. Going from a per-tensor scale to the shipped block scales is a factor of 21 in error, on the same matrix, at the same bit width.
The first lesson is that "fp8 weights" is not one thing. The expert matrices are well behaved and the attention output projection is not, which is presumably why the block scheme exists rather than a per-tensor one.
Four bits is a different story. On the same two matrices, four-bit values with one scale per tensor give 0.26068 and 0.96326, which is useless; per output channel gives 0.17641 and 0.22798, still bad; and an NVFP4-style two-level scheme, with an fp8 scale per 16 values sitting under one fp32 scale for the tensor, gives 0.09476 and 0.09495. The two-level scheme makes the two matrices behave identically, which is the point of it: the fine scale absorbs the local structure and the coarse scale absorbs the global range, so the format stops caring which matrix you hand it.
Activations are harder for two reasons. The first is practical: you do not have them ahead of time. A weight can be quantized offline with as much care as you like, and an activation has to be quantized in the middle of a forward pass by a kernel that has only just computed it, which is why the config says activation_scheme: dynamic and why the only groupings on offer are the ones a kernel can compute in one pass, like per-token or per-128-channel.
The second reason is that the channel structure of activations is extreme in a way that weights are not. To show that with real data rather than a story, I took 107 tokens of a real math prompt, embedded them with GLM-5.3's own embedding table, and pushed them through layer 0's dense feed-forward block using the real gate_proj and up_proj weights dequantized from the checkpoint. This skips attention, so what I have is layer 0's MLP seeing the residual stream without the attention term, which is worth stating because it is not quite a real forward pass.
The residual stream itself is mild. Across those 107 tokens, the per-channel maximum has a median of 0.0223 and a largest value of 0.0850, so the heaviest channel is 3.8 times the typical one, the top 1% of channels hold 3.7% of the summed squared channel maxima, and a token's largest component is 6.1 times its own root-mean-square on average.
The tensor after the SwiGLU, which is what down_proj consumes, is not mild at all. Its per-channel maximum has a median of 0.0043 and a largest value of 0.1997, so the heaviest channel is 46.0 times the typical one. Twelve channels out of 12,288, which is the top 0.1%, hold 30.2% of the summed squared channel maxima, and the top 1% hold 48.9%. A token's largest component is 36.9 times its own root-mean-square.
As Figure 14 shows on the right, that structure is exactly what the grouping has to absorb. On that post-SwiGLU tensor, fp8 with one scale for the whole tensor gives a relative error of 0.05486 through the next matrix multiply; one scale per token gives 0.02597; and one scale per 128 channels gives 0.00550. A factor of ten, from nothing but how the scales are grouped, on a tensor where twelve channels are doing the damage. Here is the same experiment in a form you can run anywhere, with the heavy channels put in by hand:
import torch
torch.manual_seed(0)
x = torch.randn(256, 2048)
x[:, :8] *= 40 # eight unusually heavy channels
w = torch.randn(2048, 512) / 2048 ** 0.5
ref = x @ w
def fake_quant(t, qmax, group):
v = t.view(t.shape[0], -1, group)
s = v.abs().amax(-1, keepdim=True).clamp_min(1e-12) / qmax
return ((v / s).round().clamp(-qmax, qmax) * s).view_as(t)
for g in (2048, 128, 16):
e = ((fake_quant(x, 448.0, g) @ w - ref).norm() / ref.norm()).item()
print(g, round(e, 5))
# 2048 0.01739
# 128 0.00438
# 16 0.0016
The other family of answers attacks the outliers instead of the scales. If you multiply the activation by an orthogonal matrix and the weight by its transpose, the product is unchanged but the heavy channels get mixed into all the others, so the per-group range shrinks and a coarse scale becomes good enough. Training-time methods go further and penalize the activations for having outliers in the first place, so that the model you quantize is one that wanted to be quantized. I am not going to go through either in detail here.
The formats themselves are a short list, and the thing to keep straight is the block shape. Block-wise fp8 uses 128 by 128 groups with fp32 scales and runs on Hopper and Blackwell. MXFP8 uses groups of 32 along one dimension with ue8m0 scales, which is the exponent-only format we already met in the all-to-all, and needs Blackwell. NVFP4 uses groups of 16 with the two-level fp8-under-fp32 scheme from the error numbers above, and also needs Blackwell.
For RL, low precision brings a mismatch of its own, and it is the most dangerous one in this article because it is silent. If the rollout engine serves in fp8 and the trainer runs its forward pass in bf16, the two engines compute different log-probabilities for the same tokens, and the policy-gradient estimator takes that difference as information about the policy. The miles documentation puts it plainly: the per-layer numerical disagreement compounds into divergent log-probabilities and gradients pointing in unintended directions. The fix is to make the two forward passes use the same quantization logic rather than to make the trainer more precise, and the compatibility matrix reflects how strict that has to be: an NVFP4 rollout is only supported against an NVFP4 trainer.
13. Getting the New Weights In
Between two RL steps there is a moment that has no analogue in serving: the trainer has new weights and every rollout engine has old ones. 745.2 billion parameters at one byte each is 694 GiB that has to land in each engine's memory, and none of it can be skipped, because an MoE's sparsity is per token and not per step. Every expert might be chosen by somebody.
The simple way is a broadcast. The training ranks all-gather their shards, convert the names to whatever the inference engine calls them, and NCCL-broadcast the result to every rollout rank. It works and it is easy to reason about, and it sends each byte to ranks that will throw most of it away, because a rollout rank under expert parallelism only keeps the experts it owns.
The alternative is to plan the transfer. Each training rank works out which rollout ranks need which of its shards and writes only those, directly into the target's memory over RDMA. miles calls this the p2p mode, and the interesting part is what it needs in order to know where to write: a CPU-side replica of the target engine's model, instantiated purely so that the target's own weight-loading functions can be called to work out the layout. Without that you would be re-deriving the inference engine's sharding rules in the trainer, which is a thing that breaks every time either side changes. Figure 15 compares the two paths.
Both paths in Figure 15 share more than they differ, and the shared parts are where the engineering is. The Megatron tensor-parallel shards are all-gathered within a pipeline stage, the expert shards are gathered per bucket, and the result is flushed in fixed-size buckets of 512 MB by default rather than one parameter at a time, which is what keeps the per-transfer overhead from dominating. Each pipeline stage updates independently, with no cross-stage synchronization, which is what lets this scale. The p2p path adds the transfer plan, the CPU replica, a single pinned buffer registered once for RDMA and reused across every target engine, and pipelined writes so that one engine's transfer overlaps the next one's buffer fill.
The other half of this moment is memory. On a co-located setup, the trainer and the rollout engines want the same HBM, and the trainer's half is large. A bf16 run with Adam needs 18 bytes per parameter for weights, gradients, an fp32 master copy and two optimizer moments, so the training state alone is many times the 694 GiB of weights, which is why these runs shard the optimizer across ranks, recompute activations in the backward pass instead of keeping them, and offload what is left to host memory. Everything the trainer does not give up is KV cache the rollout engine does not get, and from section 8 we know what a GiB of KV cache is worth in sequences. miles keeps even the MTP draft weights on CPU during training for exactly this reason, which is a small instance of a general pattern.
14. Finding Out Which of These Is Your Problem
Twelve mechanisms is a lot to hold at once, so it is worth saying how you would find out which one is costing you. The order that works is to count, then look at a trace, then change a kernel.
Counting is what most of this article was. Bytes of weights read per decode step, bytes on the wire per token, bytes of KV cache per token, kernels per step, rows per expert after padding. All of those came out of a config file or a script of under 150 lines, and all of them can be done before the model is running. The useful thing about counting first is that it tells you what cannot be your problem: at 2 FLOPs per byte against a measured ridge point of 642, a better GEMM is not going to help, and knowing that saves you from a week of kernel work.
Then read a trace, with a specific question in mind. sglang can be profiled against a live server, and the question is usually one of: is the gap between kernels large, which points at section 9; is the all-to-all on the critical path rather than overlapped, which points at section 6; are the expert GEMMs small, which points at section 7 and therefore at the batch; or is one rank's expert GEMM much longer than the others, which points at section 5. For that last one the engine has a counter rather than a trace: the expert distribution recorder gives you the per-expert token counts straight from the dispatch, which is the thing to look at before you go anywhere near a kernel.
Only then does the roofline tell you what to do. A decode step at 2 FLOPs per byte is so far below the ridge point that every useful move is on the bytes axis: fewer bits per weight, a smaller cache per token, fewer kernel boundaries, or more tokens sharing the same weight read. That last one is why most of this article kept coming back to the batch size.
15. Where the Rollout and the Trainer Disagree
One thing came up in almost every section, so let me collect it. A rollout engine and a trainer are two implementations of the same model, and they disagree in four places.
They disagree about routing, because the top-8 of a sigmoid is a threshold and the two engines do not compute the scores bit-identically. The gradient then lands on an expert the rollout never ran. The fix is to have the rollout return its expert ids and the trainer replay them.
They disagree about precision, if one serves in fp8 and the other trains in bf16. This one is silent and it corrupts the gradient rather than slowing anything down. The fix is to run the same quantization in both forward passes.
They disagree about the draft, in the sense that a draft trained against an older policy accepts less and less as the policy moves. This one only costs throughput, and it is the one you can watch directly by logging the accepted length.
And they disagree about the cache, because the prefix cache is keyed on tokens and the weights behind it have changed. That one is not fixable, only accounted for: an RL rollout starts every step cold.
If I had to pick the single idea to take away from all of this, it is the one from section 1. A rollout step is memory bound by more than two orders of magnitude, so almost everything that helps is about reading fewer bytes or getting more tokens to share a read, and almost everything that hurts is something that shrinks the batch. The tail of a long-horizon rollout shrinks the batch, which is why RL inference is a harder problem than serving the same model to users.
Sources
- sglang: https://github.com/sgl-project/sglang
- DeepEP: https://github.com/deepseek-ai/DeepEP
- DeepGEMM: https://github.com/deepseek-ai/DeepGEMM
- Megatron-LM: https://github.com/NVIDIA/Megatron-LM
- GLM-5.3 model card: https://huggingface.co/zai-org/GLM-5.3
- Auxiliary-loss-free load balancing: https://arxiv.org/abs/2408.15664
- Switch Transformer, for the auxiliary loss: https://arxiv.org/abs/2101.03961
- Rollout Routing Replay: https://arxiv.org/abs/2510.11370
- Ring Attention: https://arxiv.org/abs/2310.01889
- EAGLE: https://arxiv.org/abs/2401.15077
- Reducing activation memory in large transformers: https://arxiv.org/abs/2205.05198