Skip to content

Support SWA and sink attention in dynamic inference - #5249

Merged
shanmugamr1992 merged 16 commits into
NVIDIA:mainfrom
cuichenx:iris-pr5138-pr5140-dynamic-swa-sink-fixes
Jun 24, 2026
Merged

Support SWA and sink attention in dynamic inference#5249
shanmugamr1992 merged 16 commits into
NVIDIA:mainfrom
cuichenx:iris-pr5138-pr5140-dynamic-swa-sink-fixes

Conversation

@cuichenx

@cuichenx cuichenx commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Summary

This is a clean combined branch for PR #5138 and PR #5140, rebased onto current origin/main.

It includes:

  • PR feat(inference): support sliding-window attention in the dynamic batc… #5138: plumb per-layer sliding-window attention window sizes through the dynamic batching flash-attention path.
  • PR Sink attention dynamic inference #5140: add dynamic inference support for sink/off-by-one/learnable softmax correction.
  • Fix dynamic YaRN/RoPE plumbing by passing the configured mscale through dynamic key and query rotary-embedding application.
  • Fix decode-path flash-attention plumbing by forwarding softmax_scale into the non-MLA KV-cache kernels.
  • Handle the no-LSE decode return path explicitly before optional sink correction.

Validation

  • git diff --check origin/main..HEAD
  • GPT-OSS full-forward fused-attention reference vs dynamic flash inference comparison with real unsloth/gpt-oss-20b-BF16 weights:
    • one long English prompt, 374 prompt tokens
    • SWA window [127, 0], window_attn_skip_freq=2
    • static non-KV-cached TE/cuDNN fused attention generated [623] / " The"
    • dynamic flash engine generated [623] / " The"
    • layer-1 selected-token Q after RoPE matched exactly
    • reconstructed dynamic K/V matched static K/V by float32 digest for the full prompt sequence, the SWA window, and the selected token
    • static fused attention output vs dynamic corrected output still had small numeric kernel-level differences, with generated token unchanged
  • GPT-OSS dynamic flash inference smoke on this PR branch with real unsloth/gpt-oss-20b-BF16 weights:
    • one long English prompt, 374 prompt tokens
    • max_new_tokens=8
    • generated tokens: [623, 1825, 10648, 1606, 290, 2461, 50005, 4580]
    • generated text: " The user wants only the run‑time"
    • completed successfully with no runtime error

shanmugamr1992 and others added 4 commits June 9, 2026 16:57
…hing path

The dynamic batching engine calls flash_decode_and_prefill, which dispatched
to FA2/FA3/FA4 with window_size hardcoded to full attention. The static path
already honors config.window_size via the TE wrapper; this change brings
the dynamic path to parity.

For each call, resolve the per-layer window via is_layer_window_attention
(the same helper the TE static path uses), then plumb the (left, right)
tuple to every kernel: flash_attn4_varlen_func, the FA3 _flash_attn_forward
wrapper, flash_attn_varlen_func, flash_attn3_with_kvcache, and
flash_attn_with_kvcache (decode). FlashMLA does not support SWA, so the
MLA branch asserts window_size == (-1, -1).

Tested on H100/FA3 via cog with three SWA configs, including the gpt-oss
configuration (window_size=(127, 0), window_attn_skip_freq=2). The
regression test_simple (no-SWA path) still passes.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: shanmugamr1992 <shanmugamr1992@gmail.com>
@copy-pr-bot

copy-pr-bot Bot commented Jun 10, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

shanmugamr1992 and others added 2 commits June 10, 2026 14:49
…200.

Register the test in moe-dynamic-inference recipes and bootstrap platform
goldens; apply YaRN config in gpt_builders when running inference without
post-training GPT-OSS flags.
@copy-pr-bot

copy-pr-bot Bot commented Jun 10, 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.

@cuichenx
cuichenx marked this pull request as ready for review June 10, 2026 21:58
@cuichenx
cuichenx requested review from a team as code owners June 10, 2026 21:58
@cuichenx

Copy link
Copy Markdown
Contributor Author

/ok to test f81aa44

@cuichenx

Copy link
Copy Markdown
Contributor Author

/claude strict-review

Comment thread gpt_builders.py Outdated
Comment on lines +1201 to +1212
if need_lse:
# FA2/FA3 *_with_kvcache return (out, softmax_lse) when
# return_softmax_lse=True.
output_total, softmax_lse = kvcache_ret
else:
output_total = kvcache_ret
softmax_lse = None
if need_lse:
# output_total: (B, S, H, D); softmax_lse: (B, H, S)
output_total = self._apply_sink_softmax_correction_bshd(
output_total, softmax_lse, softmax_offset
)

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.

[SUGGESTION Simplification] Two consecutive if need_lse: blocks — the first unpacks the return tuple and the second applies the correction. These can be merged into one block:

                    if need_lse:
                        # FA2/FA3 *_with_kvcache return (out, softmax_lse) when
                        # return_softmax_lse=True.
                        output_total, softmax_lse = kvcache_ret
                        # output_total: (B, S, H, D); softmax_lse: (B, H, S)
                        output_total = self._apply_sink_softmax_correction_bshd(
                            output_total, softmax_lse, softmax_offset
                        )
                    else:
                        output_total = kvcache_ret

Comment thread megatron/core/transformer/attention.py Outdated
Comment thread megatron/core/transformer/attention.py

@claude claude Bot 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.

Review Summary

CRITICAL: 0 | IMPORTANT: 1 | SUGGESTION: 3

Overview

This PR adds sliding-window attention (SWA) and sink/off-by-one/learnable softmax correction to the dynamic-batching inference path, along with YaRN RoPE mscale plumbing and a softmax_scale fix for the FA2/FA3 kvcache decode path. The implementation is solid — the core sink-softmax math (out *= sigmoid(lse - offset)) is correct, the NaN/inf guard is well-reasoned, and all flash-attention backends (FA2, FA3, FA4, FlashMLA) are handled consistently.

Most impactful finding

Hardcoded YaRN hyperparameters in gpt_builders.pyyarn_original_max_position_embeddings=4096, yarn_beta_fast=32.0, yarn_beta_slow=1.0 are model-specific (GPT-OSS-20B) but applied unconditionally whenever position_embedding_type == 'yarn', including when the config was built from YAML. Other YaRN params (mscale, mscale_all_dim) are correctly read from args, making this inconsistent.

What looks good

  • The sink-softmax post-correction derivation is mathematically clean and matches the canonical SoftmaxOne formulation used by the static path.
  • The isfinite guard correctly distinguishes NaN LSE (padding artifacts → preserve row) from -inf LSE (no attended keys → zero the row).
  • SWA window resolution via is_layer_window_attention() correctly handles all three modes: globally disabled, every layer, and per-layer skip frequency.
  • The FA3 _flash_attn_forward wrapper's version-adaptive signature introspection handles both window_size tuple and window_size_left/window_size_right scalar styles.
  • The softmax_scale addition to the FA2/FA3 kvcache decode path is a legitimate bugfix (was missing before this PR).
  • The FlashMLA assertion guarding against SWA is the right approach — fail fast with a clear message.
  • Test coverage is thorough: math-only unit tests, monkeypatched wiring verification, and functional tests with golden values on both H100 and GB200.

Risk assessment: Low

No critical issues. The changes are well-scoped to inference-only paths (assert not self.training), so training behavior is completely unaffected. The new softmax_offset parameter defaults to None, preserving existing behavior when softmax_type == "vanilla". The only behavioral change for existing users is the softmax_scale bugfix in the FA2/FA3 kvcache decode path — but this was already broken for custom-scale models, so the fix is strictly an improvement.

…pr5249

refactor(attention): cache YaRN concentration factor in Attention.__i…
@shanmugamr1992

Copy link
Copy Markdown
Contributor

/ok to test a994af9

@svcnvidia-nemo-ci svcnvidia-nemo-ci added Approved All necessary approvals have been made and removed Final Review PR is in the "final review" stage labels Jun 23, 2026
@shanmugamr1992
shanmugamr1992 added this pull request to the merge queue Jun 23, 2026
@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/28064465483

@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/28065394213

@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/28068207953

Merged via the queue into NVIDIA:main with commit fcbb6ed Jun 24, 2026
89 of 96 checks passed
yobibyte pushed a commit to yobibyte/Megatron-LM that referenced this pull request Jun 25, 2026
Signed-off-by: shanmugamr1992 <shanmugamr1992@gmail.com>
Signed-off-by: Shanmugam Ramasamy <111910568+shanmugamr1992@users.noreply.github.com>
Co-authored-by: shanmugamr1992 <shanmugamr1992@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Shanmugam Ramasamy <111910568+shanmugamr1992@users.noreply.github.com>
Signed-off-by: Vitaly Kurin <vitalyk@nvidia.com>
ZoRax-A5 pushed a commit to ZoRax-A5/Megatron-LM that referenced this pull request Jun 29, 2026
Signed-off-by: shanmugamr1992 <shanmugamr1992@gmail.com>
Signed-off-by: Shanmugam Ramasamy <111910568+shanmugamr1992@users.noreply.github.com>
Co-authored-by: shanmugamr1992 <shanmugamr1992@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Shanmugam Ramasamy <111910568+shanmugamr1992@users.noreply.github.com>
jon-barker pushed a commit to jon-barker/Megatron-LM that referenced this pull request Jul 10, 2026
Signed-off-by: shanmugamr1992 <shanmugamr1992@gmail.com>
Signed-off-by: Shanmugam Ramasamy <111910568+shanmugamr1992@users.noreply.github.com>
Co-authored-by: shanmugamr1992 <shanmugamr1992@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Shanmugam Ramasamy <111910568+shanmugamr1992@users.noreply.github.com>
Signed-off-by: Jon Barker <jbarker@aws-cmh-slurm-1-vscode-02.cm.cluster>
terminator123 pushed a commit to 021ai/Megatron-LM that referenced this pull request Aug 3, 2026
Signed-off-by: shanmugamr1992 <shanmugamr1992@gmail.com>
Signed-off-by: Shanmugam Ramasamy <111910568+shanmugamr1992@users.noreply.github.com>
Co-authored-by: shanmugamr1992 <shanmugamr1992@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Shanmugam Ramasamy <111910568+shanmugamr1992@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Approved All necessary approvals have been made complexity: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants