Skip to content

perf(gated_delta_net): fold q/k L2-norm into the gated_delta_rule kernel - #5396

Open
yuchenwang3 wants to merge 3 commits into
NVIDIA:mainfrom
yuchenwang3:fix/gdn-qk-l2norm-in-kernel
Open

yuchenwang3 wants to merge 3 commits into
NVIDIA:mainfrom
yuchenwang3:fix/gdn-qk-l2norm-in-kernel

Conversation

@yuchenwang3

@yuchenwang3 yuchenwang3 commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor
  • I, the PR author, have personally reviewed every line of this PR.

What

Move GatedDeltaNet q/k L2 normalization into the FLA gated_delta_rule kernel instead of materializing normalized q/k before the call.

The current GDN and GDN2 implementations share _prepare_input_for_gated_delta_rule, but GDN2's kernel path does not enable in-kernel normalization. The rebased change therefore makes deferral an explicit helper option:

  • Unfused GDN defers normalization when use_qk_l2norm_in_kernel is enabled; fused preprocessing retains its existing normalization.
  • GDN2 keeps its existing caller-side normalization and continues to pass False to its kernel.

This preserves GDN2 behavior added after the original PR rather than silently removing its normalization during the rebase.

Why

Caller-side normalization leaves an additional pre-split normalized query_key activation live for backward alongside the q/k tensors the gated-delta kernel already needs. Letting FLA own normalization removes that extra caller-side activation and keeps the normalization state with the kernel-owned q/k, which saves activation memory in long-context GDN-heavy hybrids.

The numerical contract is unchanged:

  • both caller-side FLA l2norm and the in-kernel path use eps=1e-6;
  • normalization is per head over the last dimension, so GQA head replication does not change the result;
  • use_qk_l2norm=False remains a no-op.

Validation

Current head

Merged current main (5df6168232) into head 1c61820349 on November 5, preserving the CP size/group routing added upstream. Eight CPU source-method checks pass for GDN/GDN2 output and gradient parity between explicit and in-kernel normalization, covering FP32/BF16 and two sequence lengths. Black, isort, Ruff, syntax parsing, whitespace and kernel determinism coverage checks pass. The CPU harness isolates the actual Torch methods; it does not execute FLA, CUDA, or distributed communication. GPU results below apply to earlier revisions.

Earlier validation

The original change ran in Qwen3.5-35B-A3B 128K SFT on 16×B200. The earlier main replay passed Black, isort, Ruff, Pylint, py_compile, and git diff --check.

The final 398a42b4 head was also exercised with an 8-rank torchrun on 8×B200:

  • the GDN/GDN2 kernel flag-vs-explicit-normalization parity test passed on every rank;
  • the BF16 end-to-end GatedDeltaNet.forward comparison passed on every rank, covering outputs, input gradients, all parameter gradients, and both routing flags;
  • all 12 parameterized deterministic-mode GDN/GDN2 cases passed on every rank.

Assisted-by: OpenAI Codex

@copy-pr-bot

copy-pr-bot Bot commented Jun 17, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@yuchenwang3
yuchenwang3 marked this pull request as ready for review July 10, 2026 01:39
@yuchenwang3
yuchenwang3 requested review from a team as code owners July 10, 2026 01:39
@svcnvidia-nemo-ci
svcnvidia-nemo-ci requested a review from a team July 10, 2026 01:40
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Jul 10, 2026
@yuchenwang3

Copy link
Copy Markdown
Contributor Author

@xuantengh pinging you as the most recent committer on gated_delta_net.py. This folds the explicit q/k l2norm into the FLA gated_delta_rule kernel via use_qk_l2norm_in_kernel=True, dropping a materialized intermediate at long context; it ran in real Qwen3.5-35B-A3B hybrid training at 128K. One-file change, open since Jun 17 — could you review or /ok to test?

@svcnvidia-nemo-ci svcnvidia-nemo-ci removed the waiting-on-maintainers Waiting on maintainers to respond label Aug 6, 2026
@xuantengh

Copy link
Copy Markdown
Contributor

Thanks for the contribution! We had a refactor to the GDN module recently in #5843, would you please rebase that and apply this to the new file?

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-customer Waiting on the original author to respond label Aug 6, 2026
@yuchenwang3

Copy link
Copy Markdown
Contributor Author

Done, @xuantengh — merged latest main and re-applied the change onto the refactored layout from #5843:

  • common.py: the explicit l2norm() in _GDNBase._prepare_input_for_gated_delta_rule is removed (replaced by a NOTE explaining the fold and the eps=1e-6 equivalence).
  • gdn.py: the gated_delta_rule call in GatedDeltaNet.forward now passes use_qk_l2norm_in_kernel=self.use_qk_l2norm.

Net diff vs main is the same two-line semantic change as before (+7/−4 with the comment block). Ready for another look.

@yuchenwang3

Copy link
Copy Markdown
Contributor Author

@xuantengh one more follow-up before I refresh this again: current main added GDN2 sharing _prepare_input_for_gated_delta_rule. I've kept GDN2's caller-side normalization and only defer GDN to the kernel. Does that split match what you'd expect? If so I'll update the branch and request CI.

@yuchenwang3
yuchenwang3 force-pushed the fix/gdn-qk-l2norm-in-kernel branch from b752055 to 39fd9a0 Compare August 25, 2026 07:43
@yuchenwang3

Copy link
Copy Markdown
Contributor Author

Rebased onto current main and adjusted the shared input helper added since the original PR: GDN now defers q/k normalization to its kernel, while GDN2 keeps the existing caller-side normalization. Local formatting, syntax, and routing checks pass. @xuantengh, could you re-review this head when you get a chance?

@svcnvidia-nemo-ci svcnvidia-nemo-ci removed the waiting-on-maintainers Waiting on maintainers to respond label Aug 25, 2026
@xuantengh

Copy link
Copy Markdown
Contributor

Sorry for the delayed reply. Would you please add a test to tests/unit_tests/ssm/test_gated_delta_net.py to validate toggling use_qk_l2norm can produce on-par results?

@yuchenwang3
yuchenwang3 force-pushed the fix/gdn-qk-l2norm-in-kernel branch 2 times, most recently from 8206dc3 to 398a42b Compare August 25, 2026 10:37
@yuchenwang3

Copy link
Copy Markdown
Contributor Author

Done, @xuantengh. I added a small kernel-level parity check plus a BF16 end-to-end test that runs the real GatedDeltaNet.forward path. The latter compares the old caller-normalized route with kernel-owned normalization across outputs, input gradients, and every parameter gradient, and also asserts that both the helper and kernel receive the in-kernel flag and that raw q/k reach the kernel.

The new tests pass on all 8 ranks on 8×B200. While running the existing deterministic matrix I also caught and fixed a current FLA API mismatch in the newly activated fallback (l2norm has no dim argument); all 12 deterministic GDN/GDN2 cases now pass on every rank. The final head is 398a42b4 and DCO is green. Could you take another look and run /ok to test 398a42b4af753c76ffeeb14198d9b41a1bb2de1a when you get a chance?

@xuantengh

Copy link
Copy Markdown
Contributor

Hi @yuchenwang3 thanks for your contribution. Generally LGTM, but currently there is no way to specify use_qk_norm_in_kernel at the module spec level. So would you please also add this as an optional knob (default to False, aligned with upstream FLA interface signature) to TransformerConfig and ModuleSpec. And we can toggle this via config in test, rather than the install_route_probe hook.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-customer Waiting on the original author to respond label Aug 27, 2026
@yuchenwang3
yuchenwang3 force-pushed the fix/gdn-qk-l2norm-in-kernel branch from 398a42b to edf2ff5 Compare August 27, 2026 23:55
@yuchenwang3
yuchenwang3 requested review from a team as code owners August 27, 2026 23:56
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Sep 18, 2026
@yuchenwang3

Copy link
Copy Markdown
Contributor Author

@xuantengh Thanks again for the reviews and enabling auto-merge. The CODEOWNERS check on 192d5d36464927714223d95d6b603f48d1560a31 still reports missing approval from @NVIDIA/core-adlr, and GitHub now also reports a conflict with main. Could you help route the remaining owner approval and coordinate the branch refresh? I have left the approved head unchanged so the existing review and CI state remain available. Happy to resolve the conflict and rerun the relevant checks if that is the preferred next step.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Sep 22, 2026
auto-merge was automatically disabled September 28, 2026 05:59

Head branch was pushed to by a user without write access

@yuchenwang3

Copy link
Copy Markdown
Contributor Author

@xuantengh The conflicts are resolved at 596409881885. GitHub still shows the approvals, but this head only has DCO and the approval-label check, and auto-merge is off. Could you authorize CI for this SHA and check the remaining merge requirements? The recorded B200 results are from earlier revisions.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Sep 30, 2026
@dimapihtar

Copy link
Copy Markdown
Contributor

/ok to test fb1eece

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Oct 5, 2026
@xuantengh
xuantengh enabled auto-merge October 8, 2026 02:32
@yuzhongw-nvidia

Copy link
Copy Markdown
Contributor

Hi @yuchenwang3, please rebase the branch and check the conflicts with fused_streamed_pre_gated_delta_rule, thanks.

@yuchenwang3

Copy link
Copy Markdown
Contributor Author

Rebased on main. The streamed fusion still handles q/k normalization, so the GDR kernel won’t normalize them again. Could you approve CI for the new head?

@guihong-nv

Copy link
Copy Markdown
Contributor

/ok to test 18ae9ce

Copy link
Copy Markdown
Contributor Author

Merged current main in 1c61820349 and resolved the CP size/group changes without altering the reviewed normalization routing. Eight CPU checks pass for explicit versus in-kernel Torch normalization outputs and gradients in FP32/BF16. Formatting and kernel coverage checks pass. Existing approval is retained; full GPU CI still needs to run on this head.

@yuchenwang3

Copy link
Copy Markdown
Contributor Author

@guihong-nv Could you run /ok to test 1c61820? It merges current main on top of the approved changes; the last authorized run was on 18ae9ce. Also, is the @NVIDIA/core-adlr CODEOWNERS approval still outstanding, or has it been satisfied?

@guihong-nv

Copy link
Copy Markdown
Contributor

/ok to test 1c61820

@jiemingz

Copy link
Copy Markdown
Contributor

/review

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a bit-exact replay for GDN2’s changed normalization branch

The changed GDN2 branch, reached with use_qk_l2norm_in_kernel=True, has no bit-exact replay test. The updated kernel replay exercises only GDN. Parameterizing the module deterministic test doesn't reach this branch because GDN2’s module call always passes False. The new explicit-versus-in-kernel test checks numerical parity, not byte-identical replay.

Add one focused replay beside the existing GDN replay. The manifest already registers GDN2 against that test file, so no registry or production-routing change is needed. This restores the required coverage for the changed branch; it isn't a reproduced numerical failure.

Proposed test, not executed; verify it before adopting:

def test_torch_chunk_gdn2_in_kernel_l2norm_replays_fwd_bwd():
    from megatron.core.ssm.gated_delta_net.gdn2 import torch_chunk_gdn2

    seeded()
    shape = (2, 65, 4, 32)
    q = torch.randn(shape, device="cuda", dtype=torch.bfloat16, requires_grad=True)
    k = torch.randn_like(q).requires_grad_(True)
    v = torch.randn(2, 65, 4, 48, device="cuda", dtype=torch.bfloat16, requires_grad=True)
    g = (-torch.rand(shape, device="cuda") * 0.1).requires_grad_(True)
    b = torch.rand(shape, device="cuda").requires_grad_(True)
    w = torch.rand(2, 65, 4, 48, device="cuda").requires_grad_(True)

    def fn(q, k, v, g, b, w):
        return torch_chunk_gdn2(
            q, k, v, g, b, w,
            output_final_state=True,
            use_qk_l2norm_in_kernel=True,
        )

    assert_replays_bit_exact(
        fn, (q, k, v, g, b, w), replays=3,
        contention=True, what="torch_chunk_gdn2 in-kernel L2 norm",
    )

Acceptance: the proposed test must produce byte-identical outputs, final states, and gradients for all six inputs across three runs. Retain the existing FP32/BF16 explicit-versus-in-kernel parity assertions and both GDN replay cases. GDN2’s module must continue normalizing in the caller and passing False to its kernel; enabling this direct-kernel test must not change that routing.

I completed the source-only light review across all eight changed files and their affected paths. No tests were executed.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

Cover the use_qk_l2norm_in_kernel=True branch of torch_chunk_gdn2 with a fwd/bwd bit-exact replay across a chunk boundary, as suggested in review. GDN2's module routing is unchanged.

Assisted-by: Claude
Signed-off-by: Yuchen Wang <[email protected]>
@yuchenwang3

Copy link
Copy Markdown
Contributor Author

@jiemingz Added the bit-exact replay for GDN2's in-kernel q/k normalization suggested in the review, in c8acb9e04. It's test-only and GDN2's module routing is unchanged. I couldn't run it locally because it needs CUDA. Could someone run /ok to test c8acb9e04?

This branch was previously deployed

2 inactive (outdated) deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-request Final Review PR is in the "final review" stage waiting-on-maintainers Waiting on maintainers to respond

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants