RL-Kernel x verl: Zero mismatch RL on DeepSeek-V4-Flash¶
By RL-Kernel Team
TL;DR¶
We achieved zero-mismatch RL training on the full 43-layer DeepSeek-V4-Flash. Across 100 GRPO steps, every response token's log-prob from the training engine is bitwise identical to the one from the rollout engine. On the same setup, verl's reference DeepSeek-V4 LoRA recipe mismatches on 616k response tokens per step on average.
Figure 1: 100 GRPO steps on the full DeepSeek-V4-Flash. Left: training reward. Middle: AIME 2024 accuracy. Right: mean \(|\log p_{\text{actor}} - \log p_{\text{rollout}}|\) per response token.
RL-Kernel is exactly 0 at every step; the baseline averages 0.096.
- What is mismatch? The rollout engine samples a token and records its log-prob. The trainer then recomputes that log-prob with the same weights. Before any update the two should be equal. When they are not, the importance ratio carries numerical noise that the optimizer cannot tell apart from a real policy change. (Background in our Qwen3 post.)
- How we did it? RL-Kernel runs the rollout and the trainer on one set of batch-invariant kernels. This holds through DeepSeek-V4's MoE under expert parallelism, its compressed sparse attention, mHC, FP8 and MXFP4 weights, and LoRA adapters that change every step. (See How It Works)
- How to start? verl and vLLM are unmodified. RL-Kernel plugs in as a verl engine backend and a vLLM model plugin (see Quick Start).
How It Works: What Makes DeepSeek-V4-Flash Hard¶
We follow five design rules to build batch-invariant kernels: 1. The kernel fixes the order of every sum. No split-K and no atomics on the forward path. Where a library chooses its strategy from the input shape, we replace the call. 2. Sizes come from the config, never from the batch. Workspaces, capacities and split counts are the same whether a step holds one token or sixteen thousand. 3. One code path for prefill, chunked prefill and decode. If two kernels compute the same thing, sooner or later one row rounds differently. 4. Across GPUs, move bytes and do not add them. Each rank owns whole requests, so the only cross-rank traffic is the expert exchange, in a fixed order. (This applies to current DP/EP layout, but not for all RL-Kernel's design pattern.) 5. Fail closed. A missing kernel or an unpinned dependency is a hard error. There is no silent fallback to a faster path that is not batch-invariant.
Our test suite enforces these rules bytewise, never with a tolerance. Under these rules the kernels also stay efficient: every forward operator is within 1.3× of its non-invariant baseline, and several are faster.
Below we go through the DeepSeek-V4 modules where batch invariance breaks and how we fix each one: mHC, attention (CSA / HCA and KV cache management), MoE (router and experts) and expert parallelism. Each part ends with its kernels: the ones we wrote (paths under csrc/cuda/) and the libraries we reuse.
mHC¶
DeepSeek-V4 carries four residual streams instead of one. Around every attention and MoE sublayer, mHC (manifold-constrained hyper-connections) collapses the four streams into one input and then writes the sublayer's output back into all four.
- Why it breaks batch invariance. The mixing weights come from a controller: a GEMM over all four streams (K = 4H = 16,384 per token), followed by a sigmoid, a softmax and repeated Sinkhorn normalization. A fast GEMM splits that long K range into partial sums. If the number of splits follows the token count, the same token gets different partial sums in a batch of 1 and a batch of 1,000, and the normalization steps that follow carry the difference into every stream.
- How we solve it. Our mHC kernels use a fixed 16-way split whatever the batch, and merge the partials by halving (8 + 8, then 4, 2, 1). Every per-token step is correctly rounded with no implicit FMA, a sum of four is always
(a0 + a1) + (a2 + a3), and the H-long dot products use one fixed partition. The RMSNorm that follows is fused into the same kernel under the same contract. - Kernels. Ours:
mhc/dsv4_mhc.cu(the per-token math, including the Sinkhorn iterations, and the fused RMSNorm). Reused: DeepGEMMtf32_hc_prenorm_gemmfor the controller GEMM.
Attention¶
A DeepSeek-V4 layer uses one of three attention types: a 128-token sliding window only, CSA (KV compressed 4×, with an indexer that picks the top 512 entries per query), or HCA (KV compressed 128×, attending to every compressed entry).
CSA / HCA¶
- Why it breaks batch invariance. Three things. First, an attention kernel normally plans its work (split count, workspace) from the batch it is given, and the plan decides the order of the reduction. Second, prefill and decode usually run on different kernels, so a token computed in a decode step and the same token recomputed in the trainer's prefill take different arithmetic. Third, for CSA the accumulation follows the order of the selected indices: the same 512 entries in a different order give different bytes, and a tie in the top-k can change the set itself.
- How we solve it. Each request owns a workspace of fixed size, derived from the config, and the split count is fixed too. Prefill, chunked prefill and decode all call the same sparse attention kernel. The sliding window runs through that kernel as well (window positions are appended to each query's index list), so there is no separate window path to keep in sync. For CSA, one stable top-k on exact integer keys serves both prefill and decode, and the selected indices are sorted into a canonical order before attention.
- Kernels. Ours:
topk/stable_topk.cu(stable top-512, ties to the larger index),indexer/indexer_q_rope_fp8.cu(indexer query RoPE and FP8, byte-equal to vLLM's CuTe-DSL kernel) andquant/fp8_group_quant.cu(FP8 activation quantization for the projections: absmax per group of 128, UE8M0 scale). Reused: FlashMLA for the sparse attention forward, sliding window included; DeepGEMM for the FP8 projection GEMMs and the indexer's MQA logits.
KV cache management¶
- Why it breaks batch invariance. A KV entry is written once and then read by every later query that reaches it. One entry rounded differently does not stay a one-token error: it contaminates every token after it. Writing an entry involves RMSNorm, RoPE and FP8 quantization, and on compressed layers a weighted pooling over a window of tokens. With chunked prefill that window can span two chunks, so the entry depends on where the scheduler cut the prompt. We also found fused write kernels that matched their reference on every probe and still rounded a rare row differently in mixed batches.
- How we solve it. All cache writes are row-local kernels with one fixed reduction order. The compressor pools per channel in ascending token order, without FMA, and reads only its own request's saved state, so a window split across chunks gives the same entry as one pass. Decode reads the paged cache and gets the bytes prefill would have produced.
- Kernels. Ours:
attention/dsv4_qo.cu(q norm and RoPE, KV RoPE, and the insert into thefp8_ds_mlacache),attention/dsv4_cache.cu(reads and writes of the KV and indexer caches) andcompressor/compress_fp8.cu(KV compression for CSA, HCA and the indexer).
MoE¶
Each MoE block has 256 routed experts (top-6 per token, MXFP4 weights) and one shared expert, summed with the residual.
Router¶
- Why it breaks batch invariance. The gate is a GEMM, and a general-purpose BLAS picks its kernel from the row count. The score then goes through
sqrt(softplus(x)), where different kernels use different formulas and approximate math. A router error is also discrete: a last-bit difference in a score can flip the sixth expert, and the token then runs through different weights. - How we solve it. The gate runs on a pinned BF16 GEMM that reduces the full K in one fixed order, with FP32 output. A single kernel computes the scores with correctly rounded steps for both scored and hash-routed layers. Ties go to the smaller expert id, and the six weights are summed left to right before normalization.
- Kernels. Ours:
router/dsv4_router.cu(sqrt(softplus)scores, top-6 or hash routing). Reused: DeepGEMM's BF16 GEMM for the gate.
Experts¶
- Why it breaks batch invariance. Tokens must be grouped by expert. Existing fused MoE kernels size their buffers from the busiest expert in the batch and assign slots with atomics, so the order of rows inside an expert depends on thread timing. The per-expert GEMM sees a different row count in every batch. Finally, the six expert outputs are usually combined with a scatter-add, whose order is not defined.
- How we solve it. The route plan is an integer counting sort, stable on (expert, token, slot). The routed experts run on our own Hopper kernel for MXFP8 activations × MXFP4 weights, which walks K in a fixed order with no split-K. Activations are quantized once per token, per 32-element block inside its own row, with an integer max so that even a fast-math build emits the same bytes. The combine is a fixed-order sum per token in FP32 (slot 0 to slot 5, then the shared expert, then the residual) with one final round to BF16.
- Kernels. Ours:
moe/moe_route_plan.cu(route plan),moe/mxfp8_act_quant.cu(MXFP8 activation quantization),moe/sm90_fused_moe_mlp.cuandmoe/moe_swiglu_quant.cu(the MXFP8 × MXFP4 expert GEMMs on SM90),moe/moe_slot_sum.cu(the combine) andactivation/silu_and_mul_clamp.cu(the shared expert's clamped SwiGLU, byte-equal to vLLM). Reused: DeepGEMM's FP8 GEMM for the shared expert.
Expert parallelism¶
- Why it breaks batch invariance. With EP, a token's rows travel to whichever GPU holds each expert, and the number and order of rows on a rank change with the layout. Anything that chooses a strategy from the row count now breaks even if it looked invariant on one GPU. We hit this ourselves: an FP32
torch.mmpassed every single-GPU test and failed as soon as EP changed each rank's row count. - How we solve it. We run data-parallel attention with expert-parallel MoE, so each rank owns whole requests and nothing on the attention path reduces across ranks. The EP exchange only moves bytes: activations are quantized before they are sent (a block's max never crosses a row, so it never crosses a rank), rows travel in plan order, and the receiver's stable sort restores the single-GPU (expert, token, slot) order. EP 2, 4 and 8 reproduce the bytes of EP 1.
- Kernels. No kernel of our own on the wire. Reused: NCCL all-to-all, which only moves rows in a fixed order.
The full reduction order of every module is in the design document.
Results¶
Setup¶
Both runs train the full DeepSeek-V4-Flash (43 layers) on 8 × H200 for 100 GRPO steps: DAPO-Math-17k with verl's DAPO math reward, 32 prompts × 16 responses per step, responses of up to 4,096 tokens, LoRA rank 16, and AIME 2024 evaluated with greedy decoding every 10 steps. They share the verl commit, data, reward, batch, optimizer and PPO settings. What differs is the stack underneath:
| RL-Kernel + verl | Baseline (verl #7483) | |
|---|---|---|
| Actor | RL-Kernel's model as a verl engine backend, batch-invariant kernels, EP 8 | Megatron, EP 8 |
| Rollout | vLLM with RL-Kernel's model plugin, DP 8 / EP 8 | vLLM 0.32 with its own LoRA, DP 8 / EP 8 |
| Off-policy handling | none | token-level importance sampling |
Mismatch per step¶
| RL-Kernel + verl | Baseline (verl #7483) | |
|---|---|---|
| Mismatched response tokens per step | 0 at all 100 steps | 616k on average (344k to 1.01M) |
| Mean \(\lvert\Delta \log p\rvert\) per response token | 0 | 0.096 |
| Time per step | 296 s | 228 s |
| Actor peak memory per GPU | 60 GB | 102 GB, with offload |
- Is \(\log p_{\text{rollout}} - \log p_{\text{train}} = 0\) ? Yes, for every response token at all 100 steps. The check is verl's own metric: an exact FP32 comparison per response token, with no tolerance. It holds while the adapters change every step. To check that the kernels are what makes the difference, we turned batch invariance off in our rollout only and kept everything else: 156k to 437k tokens per step mismatched again.
- Does RL-Kernel improve RL stability? Yes, training was clearly more stable (Figure 1). The baseline's 10-step mean reward swings between about 0.12 and 0.49, and single steps fall below zero; ours stays between about 0.48 and 0.68. The baseline's AIME 2024 accuracy drops from 0.64 to 0.56 between steps 30 and 40 before recovering to 0.65, while ours rises from 0.63 to 0.80 and never falls back below its starting point. The two stretches where the baseline's reward falls, around step 35 and after step 85, are also where its log-prob gap is largest.
- Does RL-Kernel keep its kernels efficient? Yes, every forward operator is within 1.3× of its non-invariant baseline, and batch invariance costs the rollout server 12 to 14% over the same server with it switched off. End to end: our actor side is faster than the baseline's, but our generation is slower, which nets out to 1.3× per step. That gap comes from our rollout stack, which is not yet as tuned as vLLM's TP path, and closing it is our main open work.
Quick Start¶
This guide only supports Hopper GPUs (H100 or H200); the full model needs 8 × H200. Setup builds vLLM from source and downloads a checkpoint of about 160 GB, so allow 3 to 4 hours the first time.
git clone https://github.com/RL-Align/RL-Kernel && cd RL-Kernel
cd scripts/verl_e2e_lora
bash setup.sh rlkernel # environment: RL-Kernel, vLLM, verl, DeepGEMM, FlashMLA
bash setup.sh data # checkpoint and DAPO-Math-17k
bash run.sh gate # 2 GPUs: byte-for-byte check of rollout, actor and training forward
bash run.sh rlkernel # 8 GPUs: 20 GRPO steps
Limitations and Next Steps¶
- One node, eight Hopper GPUs. Everything in this post ran on a single node of 8 × H200. The kernels target Hopper (SM90) only, and bytes do not carry over between GPU generations: a new architecture needs its own numeric profile and its own validation. Next: multi-node training and more hardware.
- Rollout speed. Generation takes 1.77× the baseline's time per token. Batch invariance accounts for 12 to 14% of the rollout's cost; the rest is our rollout stack. Next: a lighter expert exchange between GPUs, a fused LoRA path, and expert GEMMs tuned for decode-sized batches.
- Parallelism strategy. We support data-parallel attention with expert-parallel MoE. This is the layout in which nothing in attention is reduced across GPUs, which made it the first one we could make exact. Tensor parallelism inside attention and context parallelism are not supported yet. Next: more layouts, each with its own fixed cross-GPU reduction order.
- LoRA only. Training updates LoRA adapters on the attention projections and the experts; the base weights stay frozen, and all routed experts share one adapter. Full-parameter training is not supported yet. Next: per-expert adapters, and full-parameter training after that.
Acknowledgments¶
Open-Source Ecosystem and Framework Collaboration¶
This work stands on open-source projects that we use unmodified: verl for the RL loop, vLLM for the rollout, whose batch-invariant mode (vLLM #54955) gave us our first rules, and DeepGEMM and FlashMLA for the GEMM and sparse attention kernels.
Core Contributors - DeepSeek-V4¶
Special thanks to the contributors of DeepSeek-V4 support in RL-Kernel.
KJLdefeated (Kai-Jie Lin): * DSv4 CUDA lead and MoE lead; implemented CSA / HCA attention and expert parallelism; end-to-end integration and validation.
Flink-ddd Vensen Mu(EmbeddedLLM): * Project lead; MoE combine lead.
zhangj1an (Jian Zhang): * mHC + RMSNorm lead.
inaniloquentee (Jiajie Li): * Attention lead; DSv4 roadmap; attention contract and start kit.
maxiaosong1124 (Xiaosong Ma): * Router contracts and deterministic top-6 lead.
hihaluemen (Huihong Lu): * RoutePlan assembler lead.
ryankert01 (Ryan Huang): * MXFP8 activation quantization.
origamyee0402 (Hsiu-I Liao): * Clamped weighted SwiGLU.
ScottNi0809 (Loring Ni): * Shared grouped LoRA delta; routed-expert EP placement.
Bignonia7: * MXFP8 × MXFP4 routed-expert grouped GEMM.
jyizheng (Yizheng Jiao): * Shared expert MLP.
nodeeeeee: * mHC h_aggregate with a Triton backend.
why1te: * rmsnorm_residual (CUDA + Triton).
Junyifannnn: * fp32_gemm_rms.
carsontung666: * MQA attention and grouped o-proj.
KKSK-DON(Yang Liu): * Router backward.
quan-yi-ai: * Router validation infrastructure.
AlanX-Yan: * Placement and token ownership.
bitborne: * Fixed-order MoE combine.
Endeavor-19: * Sampling-parameter gate and M10 contract.
Yuteng-Chen: * Megatron training readback and fail-closed gate.