Skip to content

Use Protocols to type-check linear_proj submodules of Attention - #3434

Merged
ericharper merged 8 commits into
NVIDIA:mainfrom
nschank:linearproj
May 14, 2026
Merged

Use Protocols to type-check linear_proj submodules of Attention#3434
ericharper merged 8 commits into
NVIDIA:mainfrom
nschank:linearproj

Conversation

@nschank

@nschank nschank commented Feb 15, 2026

Copy link
Copy Markdown
Contributor

What does this PR do ?

Defines Protocols representing linear_proj submodules, and uses them instead of ModuleSpec to enable typechecking of its construction in SelfAttention, CrossAttention, and MLA.

I also updated Backend to return linear_proj specifically, allowing type-checking of RowParallelLinear types as instances of linear_proj directly (otherwise Backend "hides" the type and makes no type-checking occur).

While I was in attention, I also updated the naming conventions of the existing interfaces to match what we've finalized on.

Associated design doc: Typed ModuleSpec.pdf

Contribution process

flowchart LR
    A[Pre-checks] --> B[PR Tests]
    subgraph Code Review/Approval
        C1[Expert Review] --> C2[Final Review]
    end
    B --> C1
    C2 --> D[Merge]
Loading

Pre-checks

  • I want this PR in a versioned release and have added the appropriate Milestone (e.g., Core 0.8)
  • 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

The following process is enforced via the CODEOWNERS file for changes into megatron/core. For changes outside of megatron/core, it is up to the PR author whether or not to tag the Final Reviewer team.

For MRs into `main` branch

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!

(Step 1): Add PR label Expert Review

(Step 2): Collect the expert reviewers reviews

  1. Attach the Expert Review label when your PR is ready for review.
  2. GitHub auto-assigns expert reviewers based on your changes. They will get notified and pick up your PR soon.

⚠️ Only proceed to the next step once all reviewers have approved, merge-conflict are resolved and the CI is passing.
Final Review might get declined if these requirements are not fulfilled.

(Step 3): Final Review

  1. Add Final Review label
  2. GitHub auto-assigns final reviewers based on your changes. They will get notified and pick up your PR soon.

(Optional Step 4): Cherry-pick into release branch

If this PR also needs to be merged into core_r* release branches, after this PR has been merged, select Cherry-pick to open a new PR into the release branch.

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.

Merging your PR

Any member of core-adlr and core-nemo will be able to merge your PR.

@nschank
nschank requested review from a team as code owners February 15, 2026 16:42
@copy-pr-bot

copy-pr-bot Bot commented Feb 15, 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.

@ko3n1g
ko3n1g requested a review from a team February 15, 2026 16:42
@Phlip79 Phlip79 added Expert Review [deprecated] Apply this label to indicate that your PR is ready for expert review. complexity: medium labels Feb 17, 2026
@Phlip79

Phlip79 commented Feb 17, 2026

Copy link
Copy Markdown
Member

/ok to test 9db13d6

Comment thread megatron/core/models/gpt/gpt_layer_specs.py Outdated
@chtruong814 chtruong814 added the needs-follow-up Issue needs follow-up label Mar 2, 2026
@nschank

nschank commented Mar 7, 2026

Copy link
Copy Markdown
Contributor Author

Resynced after coming back from travel, sorry for delay!

@chtruong814 chtruong814 added needs-follow-up Issue needs follow-up and removed needs-follow-up Issue needs follow-up labels Mar 7, 2026

@yashaswikarnati yashaswikarnati 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.

synced offline, just had a minor comment,overall lgtm!

@chtruong814 chtruong814 added the needs-follow-up Issue needs follow-up label Mar 14, 2026
@jaredcasper

Copy link
Copy Markdown
Contributor

I also updated Backend to return linear_proj specifically, allowing type-checking of RowParallelLinear types as instances of linear_proj directly (otherwise Backend "hides" the type and makes no type-checking occur).

Can you expand on this a bit? I'm guessing this is adding the row_parallel_linear_proj() function in addition to the "row_parallel_linear()" function? Don't those have the same inputs/outputs so same types? Why the need for a special one for "_proj"?

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

nschank commented Mar 19, 2026

Copy link
Copy Markdown
Contributor Author

@jaredcasper Sure! Fair criticism, this is sorta in a partial state so maybe I should update with a TODO for clarity or something. I'm trying to solve the following problem:

backend: BackendSpecProvider = ...
submodules = SelfAttentionSubmodules(..., linear_proj=backend.get_type(), ...)

SelfAttentionSubmodules.linear_proj has a specific interface it wants to require - it knows the exact signature that a LinearProjBuilder is supposed to satisfy, and same for the LinearProjInterface it must return. So whenever you provide something via linear_proj=, the type checker is given the opportunity to check that the interface actually matches.

It can only do so if the thing being passed to linear_proj= actually has a type which can be tested against that interface. This is true of specific classes (so if I pass something of type type[RowParallelLinear]), unions of classes, Callables, functools.partial, etc.

But the return type of BackendSpecProvider.row_parallel_linear() is just type. type is basically equivalent to 🤷 as far as the type-checker is concerned, so doing linear_proj=backend.row_parallel_linear() will not catch a type error. Individual subclasses of BackendSpecProvider can provide a narrower return type for row_parallel_linear, which helps somewhat (if callers are using a subclass directly), but any time a caller is using something which the type-checker only knows is a BackendSpecProvider (but not which kind) then it will not type-check row_parallel_linear.

I don't have a great Protocol to use here for what generically a method named row_parallel_linear() should actually return - there are at least two distinct Protocols that row_parallel_linear() needs to satisfy (LinearProjBuilder and LinearFc2Builder), and it's not entirely obvious those two things are required to have identical interfaces. The ideal world would be if I could just say the return type is LinearProjBuilder & LinearFc2Builder (i.e. it must satisfy both at once) but Python doesn't support that.

Thus, my proposed solution here is effectively to have BackendSpecProvider offer individual methods for each particular Builder protocol that we end up introducing. If we later merge LinearProjBuilder and LinearFc2Builder into a single LinearLayerBuilder then both column_parallel_linear and row_parallel_linear could use it; but in the meantime I think we should have row_parallel_linear_proj (returning LinearProjBuilder) and I will rename row_parallel_linear() to row_parallel_linear_fc2() -> LinearFc2Builder. This basically means BackendSpecProvider might return the same class from multiple separate methods, but each one is enforcing that that class satisfies a different interface.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the Final Review PR is in the "final review" stage label Mar 19, 2026
@chtruong814 chtruong814 added needs-follow-up Issue needs follow-up and removed waiting-on-customer Waiting on the original author to respond labels Apr 20, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed needs-follow-up Issue needs follow-up labels Apr 21, 2026
@Phlip79

Phlip79 commented Apr 30, 2026

Copy link
Copy Markdown
Member

/ok to test 6776b0d

@Phlip79
Phlip79 enabled auto-merge April 30, 2026 04:07
auto-merge was automatically disabled May 8, 2026 20:42

Head branch was pushed to by a user without write access

@nschank

nschank commented May 8, 2026

Copy link
Copy Markdown
Contributor Author

Sorry for delayed response! Synced and fixed import issue.

@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 May 9, 2026
@yashaswikarnati

Copy link
Copy Markdown
Contributor

/ok to test bf377a2

@svcnvidia-nemo-ci svcnvidia-nemo-ci removed the waiting-on-maintainers Waiting on maintainers to respond label May 12, 2026

@mathemakitten mathemakitten 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.

Re-approving on behalf of @santhnm2

@ericharper
ericharper added this pull request to the merge queue May 14, 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/25877464990

Merged via the queue into NVIDIA:main with commit dbfc96b May 14, 2026
62 of 63 checks passed
SpencerGarnets added a commit to ai-blaise/Megatron-LM that referenced this pull request May 16, 2026
Upstream main tip: f92a207

Pulled commits:

- f92a207 Update copy-pr-bot.yaml [skip ci]

- b3b6719 ci: tolerate git-gc race in /home/runner chown after checkout (NVIDIA#4808)

- 9b4074b Inference: Optimize Prefill Engine Steps for Nemotron (NVIDIA#4764)

- a53107c chore: Update nightly tests golden values (NVIDIA#4805)

- e9a0930 ci: Update workflow to use same commit for build+test (NVIDIA#4787)

- 266562f Update owners (NVIDIA#4794)

- 98031e1 Bump nvidia-modelopt>=0.44.0 (NVIDIA#4803)

- d167123 fix tokenizers in respect to newer transformers (NVIDIA#4608)

- dbfc96b Use Protocols to type-check linear_proj submodules of Attention (NVIDIA#3434)

Conflict resolutions:

- .github/CODEOWNERS: --theirs (upstream granular team mapping)

- megatron/core/transformer/attention.py: composed -- kept ours StreamBP imports, dropped dead ModuleSpec/build_module import (replaced by Protocol in NVIDIA#3434), kept ours attn_proj_manager pattern because our fine_grained_activation_offload.py keeps group_offload API while upstream split to static group_commit, but adopted apply_module(self.linear_proj) wrapper from NVIDIA#3434

- megatron/core/transformer/multi_latent_attention.py: same apply_module+attn_proj_manager composition; took ours ChunkRange parameter for StreamBP plus upstream BaseInferenceContext type annotation

- pyproject.toml: bumped modelopt >=0.44 (upstream); kept transformer-engine[pytorch,core_cu13]>=2.9.0a0,<2.12.0 pin (custom for CUDA 13 / SM100)

- uv.lock: --ours; modelopt bump is non-breaking. uv lock regenerate blocked by stale /home/sjpat/wheelhouse torchcomms path (pre-existing).

Gates:

- git diff --check: clean

- conflict markers: none

- py_compile (15 changed .py files): OK

- attention.py + multi_latent_attention.py import OK

- indexcache: 27/28 pass (same single GPU-env failure as pre-merge base)

- transformer gdn/mtp/moe suite: 53 failed / 7 passed / 55 skipped / 5 errors -- identical to base (all failures are cudaErrorDevicesUnavailable from sglang occupying all H200s)

- 2-rank torchrun smoke: blocked (no free GPUs)

Custom preserved: StreamBP (megatron/core/transformer/streambp.py + tests/unit_tests/transformer/test_streambp.py + tools/streambp_prod_verify.py), IndexCache config + NVFP4 indexer, HISA topk1024 backward, emerging_optimizers v0.2.0 pin, mHC/MTP/MoE composition.
Victarry pushed a commit to yanring/Megatron-LM that referenced this pull request May 18, 2026
* origin/main: (138 commits)
  Refactor CUDA graph API: decompose cuda_graph_scope into full_iteration impl, inference scope, and per-layer capture modules (NVIDIA#4292)
  Add high-priority A2A stream and HybridEP preprocessing SMs (NVIDIA#4694)
  add is_torch_min_version in fsdp src (NVIDIA#4812)
  [Main][feat] Support A2A Overlap for Megatron-FSDP (NVIDIA#3797)
  Reorder mtp_post_process after attention backward in 1F1B schedule plan (NVIDIA#4695)
  [fix] Use MSC for checking checkpoint existence (NVIDIA#4251)
  Combine GEMM + SwiGLU fused MLP PRs (3890, 4071, 4095, 4219, 4311, 4324) → main (NVIDIA#4636)
  Strengthen test_checkpoint to verify distributed checkpoint behavior (NVIDIA#4711)
  Disable MSC by default; opt in via --enable-msc (NVIDIA#4629)
  additional tests for nvrx (NVIDIA#4522)
  Update copy-pr-bot.yaml [skip ci]
  ci: tolerate git-gc race in /home/runner chown after checkout (NVIDIA#4808)
  Inference: Optimize Prefill Engine Steps for Nemotron (NVIDIA#4764)
  chore: Update nightly tests golden values (NVIDIA#4805)
  ci: Update workflow to use same commit for building docker image and running tests (NVIDIA#4787)
  Update owners (NVIDIA#4794)
  Bump nvidia-modelopt>=0.44.0 (NVIDIA#4803)
  fix tokenizers in respect to newer transformers (NVIDIA#4608)
  Use Protocols to type-check linear_proj submodules of Attention (NVIDIA#3434)
  Fix recompute checkpointing + training CGs (NVIDIA#3919)
  ...

# Conflicts:
#	megatron/core/transformer/moe/moe_utils.py
janEbert pushed a commit to janEbert/Megatron-LM that referenced this pull request Jun 2, 2026
…IA#3434)

Co-authored-by: gautham-kollu <gkollu@nvidia.com>
Co-authored-by: Yashaswi Karnati <144376261+yashaswikarnati@users.noreply.github.com>
Co-authored-by: Philip Petrakian <ppetrakian@nvidia.com>
yhgalaxy pushed a commit to yhgalaxy/Megatron-LM that referenced this pull request Jun 17, 2026
…IA#3434)

Co-authored-by: gautham-kollu <gkollu@nvidia.com>
Co-authored-by: Yashaswi Karnati <144376261+yashaswikarnati@users.noreply.github.com>
Co-authored-by: Philip Petrakian <ppetrakian@nvidia.com>
Signed-off-by: yhgalaxy <yhgalaxy@outlook.com>
jon-barker pushed a commit to jon-barker/Megatron-LM that referenced this pull request Jul 10, 2026
…IA#3434)

Co-authored-by: gautham-kollu <gkollu@nvidia.com>
Co-authored-by: Yashaswi Karnati <144376261+yashaswikarnati@users.noreply.github.com>
Co-authored-by: Philip Petrakian <ppetrakian@nvidia.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
…IA#3434)

Co-authored-by: gautham-kollu <gkollu@nvidia.com>
Co-authored-by: Yashaswi Karnati <144376261+yashaswikarnati@users.noreply.github.com>
Co-authored-by: Philip Petrakian <ppetrakian@nvidia.com>
svcnvidia-nemo-ci pushed a commit to dimapihtar/Megatron-LM that referenced this pull request Aug 4, 2026
…IA#3434)

Co-authored-by: gautham-kollu <gkollu@nvidia.com>
Co-authored-by: Yashaswi Karnati <144376261+yashaswikarnati@users.noreply.github.com>
Co-authored-by: Philip Petrakian <ppetrakian@nvidia.com>
Signed-off-by: Dmytro Pykhtar <dpykhtar@nvidia.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 community-request complexity: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.