TOP dense parity for Qwen3 on Blackwell: flashinfer attention, batch-invariant kernel seam, non-reentrant recompute - #70
Open
adrenaline21 wants to merge 35 commits into
Open
Conversation
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: Yueming Yuan <yym022502@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
- Detach output layer params to prevent MTP gradient flowing to output layer - Add mtp_kwargs interface for flexible MTP label/loss_mask passing - Roll mtp_labels and loss_mask for RL training compatibility Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: Yueming Yuan <yym022502@gmail.com>
…yers (#10) - Add is_mtp flag to MoE layers and multi_token_prediction module - Bypass routing replay for MTP layers (MTP uses fresh routing) - Replace rdxa/dev's built-in RouterReplay with miles.utils.routing_replay: - moe_utils.py: use get_routing_replay_compute_topk() wrapper - router.py: use register_routing_replay() for initialization Co-authored-by: Yueming Yuan <yym022502@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: Yueming Yuan <yym022502@gmail.com>
After bumping Megatron (rdxa/dev), colocated IPC weight update fails with torch.AcceleratorError: CUDA error: invalid argument during torch.multiprocessing serialization of CUDA tensors. Root cause: Megatron's new TMS hook (PR NVIDIA#3048) alters allocator behavior in training flow, causing allocations via cuMemCreate/cuMemMap which are incompatible with CUDA IPC (_share_cuda_() fails). Fix: resolve mapping.py and dynamic_context.py conflicts to isolate hook side effects so TMS/allocator state remains IPC-compatible during the weight update phase. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- merge(): truncate dp_reshardable padding on optimizer/param_state path - load_parameter_state_from_dp_reshardable: tolerate missing 'padding' key - ShardedTensor: relax flattened_range to deprecation warning Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This PR rebases from radixark Megatron fork [miles-20260218](https://github.com/radixark/Megatron-LM/tree/miles-20260218) and resolve conflicts. Upgrade Megatron from Dec 17 (3714d81) to Feb 13 (1dcf0da) PR link: #13 Co-authored-by: Yueming Yuan <yym022502@gmail.com> Made-with: Cursor
…se `--disable-weight-backuper` in miles (#18) Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: fzyzcjy <5236035+fzyzcjy@users.noreply.github.com>
Co-authored-by: fzyzcjy <5236035+fzyzcjy@users.noreply.github.com>
Squash merge of the dense true-on-policy Megatron branch. Co-authored-by: zju-stu-lizheng <lizheng.cs@zju.edu.cn> Co-authored-by: zyxiyy02 <282300612+zyxiyy02@users.noreply.github.com> Co-authored-by: Yi Zhang <1109276519@qq.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: fzyzcjy <5236035+fzyzcjy@users.noreply.github.com>
Co-authored-by: Zhiyao Jiang <jessicajiang324@gmail.com>
Co-authored-by: zyzshishui <82826991+zyzshishui@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
yueming-yuan
force-pushed
the
miles-main
branch
from
August 24, 2026 19:59
2e64d78 to
235952d
Compare
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.