Skip to content

Support efficient TEGroupedMLP (moe_grouped_gemm=True) for Minitron Pruning#1955

Draft
kevalmorabia97 wants to merge 1 commit into
mainfrom
kmorabia/minitron-moe-grouped-gemm
Draft

Support efficient TEGroupedMLP (moe_grouped_gemm=True) for Minitron Pruning#1955
kevalmorabia97 wants to merge 1 commit into
mainfrom
kmorabia/minitron-moe-grouped-gemm

Conversation

@kevalmorabia97

@kevalmorabia97 kevalmorabia97 commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

What does this PR do?

Type of change: New feature

Add Minitron pruning support for MoE models loaded with the efficient fused grouped GEMM experts (TEGroupedMLP), in addition to the existing TESequentialMLP path.

  • New _DynamicTEGroupedLinear + _DynamicTEGroupedMLP dynamic modules slice the per-expert grouped weights (num_moe_experts / moe_ffn_hidden_size / hidden_size) and reorder/drop experts via num_gemms, mirroring the SequentialMLP path with a minimal DynamicModule diff.
  • Since Minitron prunes homogeneously, a single shared moe_ffn_hidden_size is pruned across experts (SequentialMLP keeps one per expert). Same pruned width and independent per-expert weights; only the kept-channel index set is shared.
  • examples/megatron_bridge/prune_minitron.py uses grouped GEMM by default (--no_moe_grouped_gemm to fall back to SequentialMLP).

Usage

torchrun --nproc_per_node 2 prune_minitron.py \
    --hf_model_name_or_path <moe-model> \
    --prune_target_active_params 3e9 \
    --output_hf_path /tmp/pruned   # add --no_moe_grouped_gemm to use SequentialMLP

Testing

Verified in an nvcr.io/nvidia/nemo:26.06 container (TE 2.16, 2x RTX 6000 Ada):

  • GPT MoE dynamic-module + pruning + parameter-sorting tests parametrized over both expert impls.

  • Mamba hybrid NAS metric tests: params-based now covers grouped GEMM, memory-based stays SequentialMLP (exact param counts / top-k / search-space-size assertions hold identically).

  • NemotronH end-to-end test_prune_minitron exercises real-forward NAS without grouped GEMM (to be enabled in 26.08 container)

  • Compare Nemotron-3-Nano-30B-A3B pruning: SequentialMLP vs GroupedGEMM (accuracy + speed)

Before your PR is "Ready for review"

  • Is this change backward compatible?: ✅
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: ✅
  • Did you get Claude approval on this PR?: ❌

Summary by CodeRabbit

  • New Features

    • Expanded MoE pruning and search-space support to work with both grouped and non-grouped expert layouts.
    • Added an option to choose the default MoE implementation during pruning, with a fallback to the previous behavior when needed.
    • Broadened test coverage to validate both MoE modes across GPT and Mamba workflows.
  • Documentation

    • Updated changelog and inline guidance to reflect the new MoE pruning option and behavior.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 99575dce-2be9-4329-a1f4-b16b9f3a946c

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds grouped-GEMM MoE expert support (TEGroupedMLP) to the dynamic module and pruning frameworks, introducing new dynamic classes, importance estimation for grouped weights, a CLI flag in the pruning example script, and corresponding test coverage for both grouped and sequential MoE paths.

Changes

Grouped GEMM MoE Pruning

Layer / File(s) Summary
Dynamic TEGroupedMLP/TEGroupedLinear modules
modelopt/torch/nas/plugins/megatron.py
Adds _DynamicTEGroupedLinear and _DynamicTEGroupedMLP for dynamic slicing, reordering, and exporting of grouped-GEMM expert weights, and updates _DynamicSequentialMLP.modify/_DynamicMoELayer.modify to delegate FFN hparam updates.
Grouped MLP importance estimation
modelopt/torch/prune/plugins/mcore_minitron.py
Registers _DynamicTEGroupedMLP in the importance estimator registry and adds _register_grouped_mlp_importance, which hooks fused linear_fc2 activations to score moe_ffn_hidden_size.
Pruning example CLI flag and bridge loading
examples/megatron_bridge/prune_minitron.py, modelopt/torch/utils/plugins/mbridge.py, CHANGELOG.rst
Adds --no_moe_grouped_gemm flag controlling moe_grouped_gemm passed to model loading, updates related comment, and documents the change.
NAS dynamic module tests for grouped GEMM
tests/gpu_megatron/torch/nas/plugins/test_megatron_gpt_dynamic_modules.py
Parameterizes MoE search-space test/helper over moe_grouped_gemm, adjusting module-type and search-space-size assertions.
Pruning tests for grouped GEMM MoE and Mamba hybrid
tests/gpu_megatron/torch/prune/plugins/test_mcore_gpt_minitron_pruning.py, tests/gpu_megatron/torch/prune/plugins/test_mcore_mamba_minitron_pruning.py
Parameterizes GPT MoE sorting/pruning tests over moe_grouped_gemm with branching weight assertions, and updates Mamba hybrid NAS tests to exercise both settings.

Estimated code review effort: 4 (Complex) | ~60 minutes

Suggested reviewers: ChenhanYu, jenchen13, AAnoosheh

🚥 Pre-merge checks | ✅ 5 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns ✅ Passed PASS: Touched files contain no builtin eval/exec, torch.load(weights_only=False), numpy.load(allow_pickle=True), hardcoded trust_remote_code=True, or # nosec; no manifest deps changed.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly states the main change: adding TEGroupedMLP grouped-GEMM support to Minitron pruning.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch kmorabia/minitron-moe-grouped-gemm

Comment @coderabbitai help to get the list of available commands.

@copy-pr-bot

copy-pr-bot Bot commented Jul 9, 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.

@kevalmorabia97 kevalmorabia97 changed the title Add Minitron pruning support for grouped-GEMM MoE (TEGroupedMLP) Support efficient TEGroupedMLP (moe_grouped_gemm=True) for Minitron Pruning Jul 9, 2026
@kevalmorabia97

Copy link
Copy Markdown
Collaborator Author

/claude review

@kevalmorabia97

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit full review

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://NVIDIA.github.io/Model-Optimizer/pr-preview/pr-1955/

Built to branch gh-pages at 2026-07-14 20:27 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator Author

/ok to test 21269a2

@codecov

codecov Bot commented Jul 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 3.96040% with 97 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.20%. Comparing base (f479e78) to head (1073a71).

Files with missing lines Patch % Lines
modelopt/torch/nas/plugins/megatron.py 1.23% 80 Missing ⚠️
modelopt/torch/prune/plugins/mcore_minitron.py 0.00% 17 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1955      +/-   ##
==========================================
- Coverage   76.33%   76.20%   -0.13%     
==========================================
  Files         522      522              
  Lines       58452    58542      +90     
==========================================
- Hits        44618    44611       -7     
- Misses      13834    13931      +97     
Flag Coverage Δ
unit 55.31% <3.96%> (-0.08%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
modelopt/torch/utils/plugins/mbridge.py (1)

106-107: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Stale docstring contradicts this PR's new grouped-GEMM pruning support.

The moe_grouped_gemm arg docstring still says "Pruning does not support grouped GEMM yet," but this PR adds exactly that support, and prune_minitron.py now defaults to moe_grouped_gemm=True. Please update this line to reflect current behavior.

📝 Proposed fix
-        moe_grouped_gemm: Whether to use grouped GEMM for MoE.
-            Pruning does not support grouped GEMM yet.
+        moe_grouped_gemm: Whether to use grouped GEMM for MoE.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modelopt/torch/utils/plugins/mbridge.py` around lines 106 - 107, The
docstring for `moe_grouped_gemm` in `MBridge` is stale and still says pruning
does not support grouped GEMM; update that description to match the new behavior
introduced by this PR, since grouped-GEMM pruning is now supported and
`prune_minitron.py` defaults to `moe_grouped_gemm=True`. Keep the wording
aligned with the current implementation so the documentation in `mbridge.py`
accurately reflects the `moe_grouped_gemm` flag.
🧹 Nitpick comments (1)
modelopt/torch/prune/plugins/mcore_minitron.py (1)

1390-1391: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Unclear purpose of the inserted middle dimension.

[:, None, :] inserts a size-1 dim that is immediately collapsed by the subsequent .mean(dim=0) / .sum(dim=0), making it a no-op given the following reductions. If this is intentionally mirroring a [seq, batch, hidden] shape convention from the non-grouped path, a short comment would help; otherwise it can be simplified.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modelopt/torch/prune/plugins/mcore_minitron.py` around lines 1390 - 1391, The
`acts` computation in `mcore_minitron.py` has an inserted singleton middle
dimension that is immediately removed by the later `mean(dim=0)` and
`sum(dim=0)`. Either simplify the
`gather_from_tensor_model_parallel_region`/`acts` pipeline to remove the no-op
`[:, None, :]` shape expansion, or keep it and add a brief clarifying comment in
the `acts` assignment block explaining why the `[seq, batch, hidden]`-style
dimension is needed for consistency with the non-grouped path.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@modelopt/torch/utils/plugins/mbridge.py`:
- Around line 106-107: The docstring for `moe_grouped_gemm` in `MBridge` is
stale and still says pruning does not support grouped GEMM; update that
description to match the new behavior introduced by this PR, since grouped-GEMM
pruning is now supported and `prune_minitron.py` defaults to
`moe_grouped_gemm=True`. Keep the wording aligned with the current
implementation so the documentation in `mbridge.py` accurately reflects the
`moe_grouped_gemm` flag.

---

Nitpick comments:
In `@modelopt/torch/prune/plugins/mcore_minitron.py`:
- Around line 1390-1391: The `acts` computation in `mcore_minitron.py` has an
inserted singleton middle dimension that is immediately removed by the later
`mean(dim=0)` and `sum(dim=0)`. Either simplify the
`gather_from_tensor_model_parallel_region`/`acts` pipeline to remove the no-op
`[:, None, :]` shape expansion, or keep it and add a brief clarifying comment in
the `acts` assignment block explaining why the `[seq, batch, hidden]`-style
dimension is needed for consistency with the non-grouped path.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: f6ded485-9fc1-4504-b19d-855a1c305887

📥 Commits

Reviewing files that changed from the base of the PR and between 0593df0 and 21269a2.

📒 Files selected for processing (8)
  • CHANGELOG.rst
  • examples/megatron_bridge/prune_minitron.py
  • modelopt/torch/nas/plugins/megatron.py
  • modelopt/torch/prune/plugins/mcore_minitron.py
  • modelopt/torch/utils/plugins/mbridge.py
  • tests/gpu_megatron/torch/nas/plugins/test_megatron_gpt_dynamic_modules.py
  • tests/gpu_megatron/torch/prune/plugins/test_mcore_gpt_minitron_pruning.py
  • tests/gpu_megatron/torch/prune/plugins/test_mcore_mamba_minitron_pruning.py

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude review passed — no blocking issues found. LGTM

Summary

Findings — CRITICAL: 0, IMPORTANT: 0, SUGGESTION: 1

Reviewed all 8 changed files. Prioritized the three modelopt/torch/ source files (nas/plugins/megatron.py, prune/plugins/mcore_minitron.py, utils/plugins/mbridge.py), the example driver, and the three GPU test files. (Note: the two-dot diff against the shallow base tip surfaced unrelated main-branch churn in examples/onnx_ptq/* and modelopt/onnx/*; those are not part of this PR's file list and were excluded.)

This is a clean, well-scoped feature that adds a TEGroupedMLP (grouped-GEMM) dynamic-module path alongside the existing SequentialMLP path for Minitron MoE pruning. I traced the algorithm end-to-end:

  • Mode/State composability ✅ — The num_local_experts TracedHp is the same object shared across linear_fc1, linear_fc2, and (via _DynamicMoELayer) the router, so _slice_order-based expert reorder/drop stays consistent across all three. moe_ffn_hidden_size is a single shared hparam (correct for Minitron's homogeneous pruning), and the search-space-size / sortable-hparam-count test assertions were updated accordingly.
  • Export fidelity ✅_DynamicTEGroupedLinear.export() reads all reordered+sliced weight{i}/bias{i} via the dynamic getters before mutating, clones them, drops the per-expert params, folds num_gemms/in_features/out_features through super().export(), then re-registers exactly the active kept experts. Ordering is correct.
  • Importance estimator ✅_register_grouped_mlp_importance reuses the SequentialMLP expert-L2 hook for num_local_experts and adds an fc2-input activation score for moe_ffn_hidden_size matching the dense _DynamicMLP reduction. The score is stashed in _activations["ffn_activations"] so it round-trips through the per-rank score checkpoint.
  • Performance ✅ — No hot-path CPU sync: the _slice_order.tolist() in the expert getter only runs post-sort, and _DynamicMoELayer.forward already blocks forward in the sorted/trimmed state until export.

The single finding is a non-blocking stale docstring in mbridge.py (the inline comment below it was correctly updated, but the Args: entry still says pruning doesn't support grouped GEMM).

Risk: low. Additive change mirroring an established, tested pattern; both paths are exercised by the parametrized GPU tests.

@kevalmorabia97 kevalmorabia97 force-pushed the kmorabia/minitron-moe-grouped-gemm branch from 21269a2 to fc29d46 Compare July 10, 2026 05:54
@kevalmorabia97

Copy link
Copy Markdown
Collaborator Author

/ok to test fc29d46

@kevalmorabia97 kevalmorabia97 force-pushed the kmorabia/minitron-moe-grouped-gemm branch from fc29d46 to 5db72ad Compare July 13, 2026 13:05
Support pruning MoE models loaded with moe_grouped_gemm=True (fused
TEGroupedMLP) in addition to the existing TESequentialMLP path.

- Add _DynamicTEGroupedLinear + _DynamicTEGroupedMLP dynamic modules that
  slice per-expert grouped weights (num_moe_experts / moe_ffn_hidden_size /
  hidden_size) and reorder/drop experts via num_gemms, mirroring the
  SequentialMLP path. A single shared moe_ffn_hidden_size is pruned across
  experts since Minitron prunes homogeneously.
- Route ffn/expert importance for grouped experts and store scores in the
  checkpoint-tracked _activations dict so reprune-from-checkpoint works.
- prune_minitron.py uses grouped GEMM by default (--no_moe_grouped_gemm opts out).
- Cover both expert impls in tests: parametrize the GPT MoE dynamic-module and
  pruning tests, and switch the mamba hybrid params NAS test to grouped GEMM
  (memory NAS test stays SequentialMLP).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
@kevalmorabia97 kevalmorabia97 force-pushed the kmorabia/minitron-moe-grouped-gemm branch from 5db72ad to 1073a71 Compare July 14, 2026 20:23
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