TOP dense parity for Qwen3 on Blackwell: flashinfer attention, batch-invariant kernel seam, non-reentrant recompute#70
Open
adrenaline21 wants to merge 9 commits into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
TOP dense parity for Qwen3 on Blackwell: flashinfer attention, batch-invariant kernel seam, non-reentrant recompute
Summary
Makes dense Qwen3 true-on-policy (TOP) training bitwise-correct and NaN-free, and brings it to Blackwell. TOP requires the training-recomputed logprobs to be bitwise-identical to the rollout logprobs (
train_rollout_logprob_abs_diff == 0); this PR closes the remaining gaps to hold that on Blackwell and to train past step 0 without NaN.Commits
chore: gitignore .rxignore— ignore the rx devbox sync artifact.feat(top): batch-invariant kernel seam with analytic backward—kernels.py.feat(top): dense parity — O(L) attention backward + non-reentrant recompute.refactor(top): rename flashinfer ragged wrapper + configurable workspace.test(top): guard standard Megatron RoPE == SGLang RoPE bitwise.test(top): grad tests for hand-written RMSNorm + attention backwards.fix(top): pin flashinfer prefill backend to sglang's (contractual parity).test(top): grad test for tp-invariant row-linear backward.What changed
Batch-invariant kernel seam (
kernels.py)kernels.pywraps SGLang's forward-only batch-invariant Triton kernels (rms_norm, tp-invariant row-linear) inautograd.Functions with analytic backwards: the forward is the exact inference kernel (so parity comes from running the same kernel as inference, not a reimplementation that can drift), and the backward is defined (the bare kernel has nograd_fn).norm.pyandmatmul.pyroute through this seam. Row-parallel matmul now always uses the tp-invariant kernel (a single deterministic reduction), so parity holds regardless of TP degree.RoPE: dropped the custom sglang-rope path
Previously a custom
sglang_apply_rotary_pos_emb_with_freqsforced Megatron to use SGLang's rotary formula. This PR removes it and relies on Megatron's ownapply_rotary_pos_emb(unfused via--no-rope-fusion, non-interleaved, mscale=1), which is bitwise-identical to SGLang's neox rotary. Guarded by a new CPU unit test (test_standard_megatron_rope_matches_sglang_rope_bitwise) assertingtorch.equalbetween the two on fp32 and bf16 inputs, so the removal cannot silently change the policy. Removesrope.pyand its call sites.Blackwell attention: flashinfer + O(L) backward
FA3/flash-attn varlen is Hopper-only (sm90), so TOP attention couldn't run on Blackwell. The attention backend is selected by an explicit flag
TOP_ATTN_BACKEND, which miles' policy sets to match SGLang's--sglang-attention-backendso training and rollout run the same kernel:flashinferon Blackwell (and usable on Hopper for parity tests),fa3on Hopper (faster, native fused backward). It is not GPU-arch-gated; the standalone fallback isfa3. flashinfer's ragged prefill mirrors SGLang's own design — a shared workspace singleton + plan-per-batch (_ragged_prefill_wrapperinsglang_attention.py, workspace size viaMEGATRON_TRUE_ON_POLICY_FLASHINFER_WORKSPACE_SIZE, default 1 GiB). The wrapper'sbackend=is set tofa2— the flashinfer kernel SGLang's deterministic prefill uses (prefill_backend="fa2", paged wrapper). Matching it makes training and rollout run the identical flashinfer kernel; the choice of ragged-vs-paged wrapper is irrelevant (verified bitwise-equal under fa2). This corrects an earlier setting ofcutlass(SGLang's non-deterministic ragged backend), which silently diverged byabs_diff ≈ 0.012. Guarded by a real output-parity test (ragged+_fmha_backendvs paged+fa2,torch.equal), not just a rule assertion.Backward strategy: flashinfer's
runis forward-only (nograd_fn), so training needs anautograd.Functionwrapper. The backward dispatches aten's fused mem-efficient attention kernel directly, per packed segment, withis_causal=Trueand no dense[L,L]mask — so it's O(max segment length) memory, not O(seq²), essential for long single-sample segments and long context. It deliberately does NOT usetorch.autograd.grad(a recompute-then-autograd.grad nests a second autograd traversal insideFunction.backward, which is reentrant-unsafe); dispatching the fused kernel directly is the safe, analytic path — same rule as the norm and row-linear backwards. The custom O(L) backward is therefore Blackwell-only; on Hopper FA3 supplies its own fused backward.Radix cache: flashinfer is not in SGLang's
RADIX_SUPPORTED_DETERMINISTIC_ATTENTION_BACKEND, so the rollout side must run with radix cache disabled (--disable-radix-cache). TOP's recompute-prefill is radix-free anyway, so this costs nothing here — but it's a required flag, noted so it isn't dropped.Non-reentrant activation recompute
CheckpointFunctionyields NaN gradients in TOP training (reproduced tp=1 and tp=4); non-reentrant (use_reentrant=False) is clean.disabled → non_reentrant), and turning it on in the contract. Not a new mechanism.autograd.Functions, but the precise failure point isn't isolated (a nested-autograd.gradhypothesis was already refuted). @maocheng23 owns this path and should confirm the mechanism / that generalizing his CP fallback is sound.Required config flags
--no-rope-fusion(rope parity),--disable-radix-cache(flashinfer rollout), batch-invariant mode, and the TOP contract (--sglang-true-on-policy-contract qwen3_dense_true_on_policy_v1).Testing
Unit (CPU): rope bitwise-equivalence guard; flashinfer backend selector is
fa2; existing contract-wiring, matmul, and norm tests.Unit (GPU, real parity):
test_flashinfer_output_matches_deterministic_paged_reference— runs our training flashinfer path (ragged +_fmha_backend) and SGLang's deterministic reference (paged + fa2) on identical q/k/v and assertstorch.equal. This is the test that would have caught the cutlass regression (the prior rule-assertion test blessed it instead).Unit (GPU, CUDA-gated): gradchecks for the three hand-written backwards — RMSNorm vjp, O(L) flashinfer attention vjp, tp-invariant row-linear vjp — each against a differentiable reference (the backwards have no inference counterpart, so nothing else validates them). All four (the three gradchecks + the CPU backend guard) pass on H200.
E2E — parity across both parallelism axes:
ess_ratio = 1.0, grad flows. fa3 is used by both training and rollout, so parity is contractual; CP holds bitwise (a2a-gathered layout runs the same kernel as non-CP). (Ring/online-merge CP untested — out of scope.)fa2(matching SGLang's deterministic prefill; see below). CP included. (An earliercutlasssetting gave Δ≈0.012 — a self-inflicted regression, now fixed and covered by a unit test.)ess_ratio = 1.0and nonzero grad_norm — TOP holds during sustained training, not just a smoke step.Honest scoping: the abs_diff gate is computed pre-backward, so E2E proves forward parity; backward correctness rests on the gradchecks + runs not NaN-ing. Reward convergence is a separate follow-up — GSM8K/0.6B starts near-ceiling (~0.81); a 4B/DAPO run (starts ~0.56, real headroom) is the setup for a reward curve.
Not in scope / follow-ups
debug.py+ hooks) — left intact.