Skip to content

[main] feat(attention): add use_head_wise_attn_gate for Step-3.5-Flash#4848

Closed
shifangx wants to merge 1 commit into
NVIDIA:mainfrom
shifangx:shifang/head_wise_attn_gate-main
Closed

[main] feat(attention): add use_head_wise_attn_gate for Step-3.5-Flash#4848
shifangx wants to merge 1 commit into
NVIDIA:mainfrom
shifangx:shifang/head_wise_attn_gate-main

Conversation

@shifangx

Copy link
Copy Markdown
Contributor

What does this PR do ?

use_head_wise_attn_gate: bool -- enable a per-head scalar output gate
(a.k.a. g_proj). The gate is fused into linear_qkv as the trailing
num_attention_heads rows; in the forward pass each rank slices off its
num_attention_heads_per_partition gate scalars, applies sigmoid, and
scales each attention head's output before linear_proj.
Distinct from attention_output_gate, which fuses a full head_dim gate
into linear_qkv. The per-head gate adds only num_attention_heads extra
output rows on linear_qkv (vs. num_attention_heads * head_dim), so the
parameter and FLOP overhead is negligible.
Under tensor parallel, this requires that both num_query_groups and
num_attention_heads be divisible by the TP world size so the QKV and
gate sub-ranges stay aligned per rank.
The new feature defaults to False and has no effect on existing models.

⚠️ For major changes (either in lines of code or in its impact), please make sure to first share a design doc with the team. If you're unsure what's the best way to do so, contact the @mcore-oncall.

Issue tracking

For PRs from open-source community contributors:

  • New features: a linked issue is required. Please open a feature request and reference it here before submitting the PR.
  • Small updates (bug fixes, minor improvements): a linked issue is recommended and will accelerate the PR review process.

Linked issue:

Contribution process

Pre-checks

  • I have added relevant unit tests
  • I have added relevant functional tests
  • I have added proper typing to my code Typing guidelines
  • I have added relevant documentation
  • I have run the autoformatter.sh on my PR

Code review

Feel free to message or comment the @mcore-oncall to help accelerate your merge into main. The less complex your PR is, the faster it will be approved and merged!

All PRs start as draft. If you open a non-draft PR, it will be automatically converted to draft.

Step 1: Mark PR as "Ready for Review"

  1. When your PR is ready, click Ready for Review.
  2. An oncall reviewer is auto-assigned and expert reviewers are notified based on your changes.
    • Some PRs may jump straight to step 2. This is determined by .github/CODEOWNERS.

⚠️ Only mark as ready once merge-conflicts are resolved and the CI is passing.
Final Review might get declined if these requirements are not fulfilled.

Step 2: Final Review

For PRs that change megatron/core, once all expert reviewers have approved, the Final Review label is applied automatically and final reviewers are assigned.

For PRs outside megatron/core, this step is skipped.

Step 3: Approved

Once all required reviewers have approved, the Approved label is applied automatically.

Merge

Any member of mcore-engineers will be able to merge your PR.

For MRs into `dev` branch The proposed review process for `dev` branch is under active discussion.

MRs are mergable after one approval by either eharper@nvidia.com or zijiey@nvidia.com.

Adds an opt-in Step-3.5-Flash-style g_proj: num_attention_heads scalar
gates fused as the trailing rows of linear_qkv, applied as a sigmoid
multiplier per head before linear_proj. Mutually exclusive with the
existing attention_output_gate (full head_dim gate).

Implementation:
- TransformerConfig: head_wise_attn_gate flag plus two init knobs
  (head_wise_attn_gate_init_weight_scale=0.1,
  head_wise_attn_gate_init_bias=2.0) chosen so sigmoid(gate)~=0.88 at
  init (near-identity, no half-scaling regression).
- SelfAttention.get_query_key_value_tensors peels the trailing per-rank
  gate scalars off mixed_qkv before any reshape/AllGather; correctness
  rests on (a) ColumnParallelLinear's contiguous axis-0 split,
  (b) num_attention_heads % tp == 0, (c) global [QKV; Gate] layout
  preserved by a ShardedTensorFactory on save/load.
- SelfAttention.sharded_state_dict installs that factory on
  linear_qkv.weight (and .bias) so dist-ckpt round-trips across TP
  reshape correctly chunk into [QKV_part, gate_part] and concat back.
- Init-time gate-row surgery in SelfAttention.__init__: scales gate
  weight rows and fills gate bias rows so the gate starts near 1.
- Config validation in __post_init__: rejects combination with
  attention_output_gate, num_attention_heads % tp != 0,
  num_query_groups < tp, and (under fp8/fp4) per-partition
  linear_qkv_out_dim misaligned to 16/32.

Tests:
- tests/unit_tests/transformer/test_head_wise_attn_gate.py covers config
  validation, init magnitudes, forward shape, TP=2 saturated-gate
  equivalence, and zero-gate halving.
- tests/unit_tests/dist_checkpointing/test_head_wise_attn_gate_resharding.py
  asserts logits equality across TP=1<->TP=2 dist-ckpt reshard for both
  MHA and GQA, with and without QKV bias.

Unverified paths (follow-ups): context parallelism, fp8 numerical
parity, explicit backward-grad-to-gate, packed_seq_params.qkv_format
== 'thd'.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@shifangx shifangx requested review from a team as code owners May 18, 2026 15:06
@copy-pr-bot

copy-pr-bot Bot commented May 18, 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.

@svcnvidia-nemo-ci svcnvidia-nemo-ci marked this pull request as draft May 18, 2026 15:06
@github-actions

Copy link
Copy Markdown
Contributor

This PR has been automatically converted to draft because all PRs must start as drafts.

When you are ready for review, click Ready for Review to begin the review process. This will:

  1. Add the oncall reviewer (optional reviewer)
  2. Add required review teams based on your changes

See the contribution guide for more details.

@shifangx shifangx closed this May 26, 2026
@shifangx shifangx deleted the shifang/head_wise_attn_gate-main branch May 26, 2026 13:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant