Skip to content

MBridge VLM distillation / QAD support#1938

Merged
kevalmorabia97 merged 8 commits into
mainfrom
kmorabia/vlm-distill
Jul 16, 2026
Merged

MBridge VLM distillation / QAD support#1938
kevalmorabia97 merged 8 commits into
mainfrom
kmorabia/vlm-distill

Conversation

@kevalmorabia97

@kevalmorabia97 kevalmorabia97 commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

What

Adds VLM (e.g. Qwen3.5-VL, Gemma3-VL) knowledge-distillation / QAD support to the Megatron-Bridge examples:

  • distill.py distills only the language model submodule (vision tower + projector untouched), reusing the LLM training path.
  • New export_distilled_megatron_to_hf.py converts a distilled Megatron checkpoint (any iteration) to HF. Required especially for VLM distilled ckpt as it only has LM weights so we need to initialize full VLM, swap LLM weights then save to HF
  • Renames export.pyexport_quantized_megatron_to_hf.py.

Related upstream Megatron-Bridge PRs to be available in nemo:26.08 container:

Testing

  • Qwen3.6-35B-A3B Pruning + Distillation with MMLU evaluation sanity check (results below in comments)
  • Cosmos 2 Reason 2B valiadted by SAs (results below in comments)
  • Validated end-to-end on nemo:26.06 (distill → separate HF export; LLM + VLM, incl. TP→TP/PP reshard). test_distill_vlm runs the export script as a CI e2e step.
  • Many CICD tests for wide coverage of all mbridge scripts

Summary by CodeRabbit

Summary

  • New Features

    • Added a dedicated HuggingFace exporter for distilled Megatron checkpoints, with distinct LLM vs VLM conversion flows.
  • Bug Fixes

    • Improved Megatron-Bridge distillation/export consistency, including safer handling of VLMs and targeted submodule distillation.
  • Documentation

    • Updated Megatron-Bridge READMEs and tutorials to reference the new quantized and distilled export scripts and revised CLI guidance.
  • Tests

    • Expanded distillation, QAD, and quantization/export tests to cover LLM/VLM variants, with conditional skipping for unsupported MoE setups.

@copy-pr-bot

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

@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds VLM-aware Megatron-Bridge distillation, a distilled-checkpoint Hugging Face exporter, conditional checkpoint state restoration, updated quantized export workflows, hybrid-attention pruning support, and expanded tests and documentation.

Changes

Megatron-Bridge distillation and export flow

Layer / File(s) Summary
Distillation provider wrapper
examples/megatron_bridge/_distillation_provider.py
Defers KD conversion until after checkpoint weight loading and supports restricting conversion to a selected submodule.
Checkpoint restore and bridge plugin wiring
modelopt/torch/utils/plugins/mbridge.py, modelopt/torch/nas/plugins/__init__.py, examples/megatron_bridge/prune_minitron.py
Adds conditional ModelOpt state restoration, removes the Qwen3.5 MoE mapping patch, and moves NAS plugin registration to the pruning entrypoint.
VLM-aware distillation and export
examples/megatron_bridge/distill.py
Targets the language model in VLMs, restores student weights before conversion, and uses dedicated LLM and VLM Hugging Face export helpers.
Distilled checkpoint exporter
examples/megatron_bridge/export_distilled_megatron_to_hf.py
Adds separate LLM and VLM conversion paths for distilled Megatron checkpoints.
Distillation, QAD, and MoE validation
tests/examples/megatron_bridge/*, tests/_test_utils/examples/megatron_bridge.py
Adds VLM distillation coverage, parameterizes QAD tests, validates exported artifacts, and gates unsupported Qwen3.5-MoE cases.
Export workflow documentation
CHANGELOG.rst, examples/megatron_bridge/README.md, examples/megatron_bridge/quantize.py, examples/megatron_bridge/tutorials/*
Updates exporter names, conversion commands, VLM guidance, and distilled-checkpoint instructions.

Hybrid-attention pruning support

Layer / File(s) Summary
Per-layer attention pattern handling
modelopt/torch/nas/plugins/megatron_model_stats.py, tests/gpu_megatron/torch/nas/plugins/test_megatron_model_stats.py
Supports periodic and explicit per-layer linear_attention_freq patterns in parameter counting and verifies equivalent results.
Depth-pruning state management
modelopt/torch/prune/plugins/mcore_minitron.py
Slices per-layer configuration during depth pruning and temporarily prunes and restores candidate models during architecture scoring.
Hybrid-attention pruning validation
tests/gpu_megatron/torch/prune/plugins/test_mcore_gpt_minitron_pruning.py
Validates layer counts and sliced attention patterns for Qwen3.5-like hybrid pruning.

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

Sequence Diagram(s)

sequenceDiagram
  participant distill.py
  participant run_provider
  participant convert_to_distillation_provider
  participant save_vlm_to_hf
  participant export_llm_to_hf

  distill.py->>run_provider: Load student checkpoint weights
  run_provider->>convert_to_distillation_provider: Run deferred KD conversion
  convert_to_distillation_provider-->>distill.py: Return distilled model
  distill.py->>save_vlm_to_hf: Export distilled VLM
  distill.py->>export_llm_to_hf: Export distilled LLM
Loading

Possibly related PRs

Suggested reviewers: danielkorzekwa, chenhanyu, j-rausch, jenchen13

🚥 Pre-merge checks | ✅ 5 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.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 No listed anti-patterns were found in the changed modelopt/examples Python files; trust_remote_code is caller-controlled and defaults false, and there are no torch.load/np.load/eval/exec/nosec addi...
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: Megatron-Bridge VLM distillation and QAD support.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch kmorabia/vlm-distill

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

@kevalmorabia97 kevalmorabia97 changed the title feat: VLM distillation and HF export for Megatron-Bridge examples MBridge VLM distillation / QAD support Jul 7, 2026
@kevalmorabia97
kevalmorabia97 marked this pull request as ready for review July 7, 2026 17:08
@kevalmorabia97
kevalmorabia97 requested review from a team as code owners July 7, 2026 17:08
@github-actions

github-actions Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-07-16 15:16 UTC

Comment thread examples/megatron_bridge/_distillation_provider.py
@codecov

codecov Bot commented Jul 7, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.18182% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 75.80%. Comparing base (f479e78) to head (5f65a35).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
modelopt/torch/prune/plugins/mcore_minitron.py 97.87% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1938      +/-   ##
==========================================
- Coverage   77.87%   75.80%   -2.08%     
==========================================
  Files         522      525       +3     
  Lines       58452    61240    +2788     
==========================================
+ Hits        45522    46423     +901     
- Misses      12930    14817    +1887     
Flag Coverage Δ
examples 43.22% <85.45%> (-0.23%) ⬇️
gpu 57.92% <94.54%> (-0.66%) ⬇️
regression 15.07% <1.81%> (+0.06%) ⬆️
unit 54.97% <1.81%> (-0.42%) ⬇️

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.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator Author

/claude review

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

Warning

CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.

Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.

👉 Steps to fix this

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (1)
tests/examples/megatron_bridge/test_quantize_export.py (1)

15-83: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Keep the VLM export coverage test_qad.py only reaches export_quantized_megatron_to_hf.py on the non-VLM path; the VLM branch returns before export, so it does not replace the removed case.

🤖 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 `@tests/examples/megatron_bridge/test_quantize_export.py` around lines 15 - 83,
The VLM export path still needs direct coverage because the QAD flow exits
before reaching export_quantized_megatron_to_hf.py, so this test should keep
validating the quantize-and-export bridge for the VLM-specific Megatron
checkpoint. Preserve the existing quantize/export steps in
test_quantize_and_export, using the same helpers like create_tiny_qwen3_dir,
extend_cmd_parts, and run_example_command, so the removed coverage is not lost.
🧹 Nitpick comments (1)
tests/examples/megatron_bridge/test_prune_minitron.py (1)

26-40: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate helper across test files.

_qwen35_moe_bridge_supported() is duplicated verbatim in tests/examples/megatron_bridge/test_qad.py. Consider moving it to a shared location (e.g. a local conftest.py in tests/examples/megatron_bridge/) to avoid drift between the two copies.

♻️ Suggested consolidation
# tests/examples/megatron_bridge/conftest.py
from megatron.bridge.models.conversion import model_bridge


def qwen35_moe_bridge_supported() -> bool:
    """Whether MBridge supports Qwen3.5-MoE per-expert weight assembly, i.e. nemo:26.08+."""
    try:
        return hasattr(model_bridge, "_fuse_per_expert_hf_weight")
    except Exception:
        return False

Then import qwen35_moe_bridge_supported from the shared module in both test files.

🤖 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 `@tests/examples/megatron_bridge/test_prune_minitron.py` around lines 26 - 40,
The helper _qwen35_moe_bridge_supported() is duplicated in multiple Megatron
bridge test files, so consolidate it into a shared test fixture/module such as a
local conftest.py under tests/examples/megatron_bridge/. Move the logic that
checks model_bridge for _fuse_per_expert_hf_weight into a single shared function
(for example qwen35_moe_bridge_supported), then import and use that shared
helper from both test_prune_minitron.py and test_qad.py to keep the behavior in
sync.
🤖 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.

Inline comments:
In `@examples/megatron_bridge/distill.py`:
- Around line 377-391: In the VLM export path inside distill.py, the call to
save_vlm_to_hf is using the wrong source HF identifier for config/tokenizer
lookup. Update the export block under if args.hf_export_path and is_vlm so it
passes args.student_hf_path instead of args.student_hf_model, matching the
standalone export_distilled_megatron_to_hf flow and the intended VLM source path
semantics.

In `@examples/megatron_bridge/quantize.py`:
- Around line 417-420: The post-save message in quantize.py is too generic
because it tells all users to convert with export_quantized_megatron_to_hf.py
even though VLM checkpoints remain Megatron-only. Update the print_rank_0 hint
near the quantized model save path to branch on is_vlm (or explicitly mention
the VLM exception) so non-VLM users see the conversion guidance while VLM users
are warned that the conversion path is unsupported.

---

Outside diff comments:
In `@tests/examples/megatron_bridge/test_quantize_export.py`:
- Around line 15-83: The VLM export path still needs direct coverage because the
QAD flow exits before reaching export_quantized_megatron_to_hf.py, so this test
should keep validating the quantize-and-export bridge for the VLM-specific
Megatron checkpoint. Preserve the existing quantize/export steps in
test_quantize_and_export, using the same helpers like create_tiny_qwen3_dir,
extend_cmd_parts, and run_example_command, so the removed coverage is not lost.

---

Nitpick comments:
In `@tests/examples/megatron_bridge/test_prune_minitron.py`:
- Around line 26-40: The helper _qwen35_moe_bridge_supported() is duplicated in
multiple Megatron bridge test files, so consolidate it into a shared test
fixture/module such as a local conftest.py under
tests/examples/megatron_bridge/. Move the logic that checks model_bridge for
_fuse_per_expert_hf_weight into a single shared function (for example
qwen35_moe_bridge_supported), then import and use that shared helper from both
test_prune_minitron.py and test_qad.py to keep the behavior in sync.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: a418a2b7-0f1b-4330-a397-723d252f5670

📥 Commits

Reviewing files that changed from the base of the PR and between d290839 and f423708.

📒 Files selected for processing (14)
  • CHANGELOG.rst
  • examples/megatron_bridge/README.md
  • examples/megatron_bridge/_distillation_provider.py
  • examples/megatron_bridge/distill.py
  • examples/megatron_bridge/export_distilled_megatron_to_hf.py
  • examples/megatron_bridge/export_quantized_megatron_to_hf.py
  • examples/megatron_bridge/quantize.py
  • examples/megatron_bridge/tutorials/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16/README.md
  • examples/megatron_bridge/tutorials/README.md
  • modelopt/torch/utils/plugins/mbridge.py
  • tests/examples/megatron_bridge/test_distill.py
  • tests/examples/megatron_bridge/test_prune_minitron.py
  • tests/examples/megatron_bridge/test_qad.py
  • tests/examples/megatron_bridge/test_quantize_export.py

Comment thread examples/megatron_bridge/distill.py
Comment thread examples/megatron_bridge/quantize.py Outdated
Comment thread examples/megatron_bridge/distill.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

Scope: Reviewed all 14 changed files, prioritizing new/modified source (_distillation_provider.py, distill.py, export_distilled_megatron_to_hf.py, quantize.py, modelopt/torch/utils/plugins/mbridge.py), then tests and README/CHANGELOG. Examples + tests PR plus one backward-compatible signature change (load_modelopt_megatron_checkpoint gains restore_modelopt_state: bool = True; default preserves prior behavior).

Findings: CRITICAL: 0 · IMPORTANT: 0 · SUGGESTION: 1 (posted inline) — the inline VLM export branch in distill.py (--hf_export_path + VLM) is not exercised by CI; test_distill_vlm validates only the standalone export_distilled_megatron_to_hf.py path.

Verified: New public imports resolve (copy_hf_ckpt_remote_code, warn_rank_0/print_args). Removed _patch_qwen35_moe_sequential_expert_mappings and the deleted export.py name have no remaining references in examples/ or docs/. The load_modelopt_megatron_checkpoint change is additive and the new restore_modelopt_state=False call site is correct. dist.cleanup() is guarded so the double-cleanup is safe. The teacher-mirroring __setattr__ foot-gun in _distillation_provider.py is handled via object.__setattr__.

Already flagged by CodeRabbit (not duplicated; worth confirming before merge): inline VLM export passes student_hf_model instead of student_hf_path to save_vlm_to_hf; quantize.py post-save message points all users at the export script though VLM quantized export is unsupported; duplicated _qwen35_moe_bridge_supported() helper across two test files.

Risk: Low. Example/test-scoped with documented temporary WARs (nemo:26.08 container) and one backward-compatible plugin signature change. No mode-registration, config-schema, or checkpoint-state-dict changes affecting existing optimized checkpoints.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator Author

Addressed review comments in 623b6c9:

  • @coderabbitai VLM export template arg (distill.py) — fixed: passes --student_hf_path.
  • @coderabbitai quantize.py post-save hint — fixed: scoped on is_vlm (VLMs note that quantized-HF export is unsupported).
  • @coderabbitai duplicated _qwen35_moe_bridge_supported() — moved to tests/_test_utils/examples/megatron_bridge.py and imported in both test_qad.py and test_prune_minitron.py.
  • @coderabbitai "keep VLM export coverage" (test_quantize_export.py) — skipping: there's no quantized-VLM export path to cover (it's unsupported, and export_quantized_megatron_to_hf.py is LLM-only). The meaningful part of the removed test — PTQ of a VLM producing a Megatron checkpoint — is still covered by test_qad.py's gemma3vl case (Step 1 runs quantize.py on the VLM and asserts modelopt_state).
  • @AAnoosheh / @kevalmorabia97: confirmed — the provider lives upstream in feat(distill): defer KD conversion to a pre-wrap hook and support submodule distillation for VLMs NVIDIA-NeMo/Megatron-Bridge#4707; _distillation_provider.py is a temporary 26.06 vendored copy, removed once nemo:26.08 ships it.

All example-test changes collect cleanly; the code fixes are message/arg-only (no behavior change for the default --student_hf_model == --student_hf_path case).

@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
gh pr view 1938 --repo NVIDIA/Model-Optimizer --json commits --jq '.commits[] | select(.oid | startswith("623b6c9")) | .oid'
gh api repos/NVIDIA/Model-Optimizer/commits/623b6c9 --jq '.files[].filename' 2>/dev/null || true

Length of output: 647


@kevalmorabia97 Confirmed — commit 623b6c9 touches exactly the files you described: examples/megatron_bridge/distill.py, examples/megatron_bridge/quantize.py, tests/_test_utils/examples/megatron_bridge.py, tests/examples/megatron_bridge/test_prune_minitron.py, and tests/examples/megatron_bridge/test_qad.py. This lines up with:

  • distill.py — VLM export template arg fix (--student_hf_path).
  • quantize.py — post-save hint now scoped on is_vlm.
  • _qwen35_moe_bridge_supported() deduplicated into tests/_test_utils/examples/megatron_bridge.py and imported by both test_qad.py and test_prune_minitron.py.

test_quantize_export.py wasn't touched in this commit, consistent with your rationale for skipping that item — agreed, since export_quantized_megatron_to_hf.py is LLM-only and quantized-VLM export isn't supported, the PTQ-of-VLM coverage via test_qad.py's gemma3vl case is sufficient.

Thanks also for confirming the _distillation_provider.py vendoring situation tied to NVIDIA-NeMo/Megatron-Bridge#4707.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@kevalmorabia97
kevalmorabia97 force-pushed the kmorabia/vlm-distill branch 2 times, most recently from 3b7106a to 1fee603 Compare July 13, 2026 13:29
@kevalmorabia97
kevalmorabia97 requested a review from a team as a code owner July 13, 2026 13:29
@nfasfous

Copy link
Copy Markdown

Tested on Cosmos-Reason2-2B:

  • Pruned Model from 28 to 24 dec blocks -> baseline to start KD experiments
  • KD unpruned VLM teacher to pruned VLM student with mbridge then applied PTQ to student down to (a) FP8 and (b) NVFP4
  • Same setup for QAD with (a) FP8 and (b) NVFP4
  • Eval on MMStar dataset and compare to baseline BF16 KD'd student model

Note: KD/QAD only applied only for short run of 50 iters

Results:
image
image

Key takeaways: particularly for NVFP4, QAD recovers drop in performance. FP8 less impacted overall, difference to BF16 is noise.

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

Warning

CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.

Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.

👉 Steps to fix this

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@modelopt/torch/prune/plugins/mcore_minitron.py`:
- Around line 423-454: Update _temporarily_pruned so the original all_layers
list and layer numbers are restored onto model.decoder.layers before calling
sample(model, sample_func=max). Then sample the reattached full layer list to
restore max-subnet state, followed by restoring per-layer patterns and hybrid
configuration as currently handled.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 5cfd7fbc-1d97-4c0e-93b6-c1ff5b3e4b8c

📥 Commits

Reviewing files that changed from the base of the PR and between 1fee603 and 3ea6f6b.

📒 Files selected for processing (6)
  • examples/megatron_bridge/README.md
  • examples/megatron_bridge/prune_minitron.py
  • modelopt/torch/nas/plugins/megatron_model_stats.py
  • modelopt/torch/prune/plugins/mcore_minitron.py
  • tests/gpu_megatron/torch/nas/plugins/test_megatron_model_stats.py
  • tests/gpu_megatron/torch/prune/plugins/test_mcore_gpt_minitron_pruning.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/megatron_bridge/README.md

Comment thread modelopt/torch/prune/plugins/mcore_minitron.py
kevalmorabia97 and others added 3 commits July 14, 2026 14:37
- distill.py: distill only the language_model submodule of a VLM (vision tower
  / projector untouched); reuses the LLM training path for everything else.
- Add export_distilled_megatron_to_hf.py to convert a distilled Megatron
  checkpoint (any iteration) to HF -- LLM/Puzzletron via export_ckpt, VLM via
  in-memory reassembly (vision from HF + distilled LM from the checkpoint).
- Rename export.py -> export_quantized_megatron_to_hf.py; distill.py's final
  export reuses the shared export helpers.
- mbridge: load_modelopt_megatron_checkpoint gains restore_modelopt_state
  (weights-only reload of a full-precision distilled student, no teacher).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
…helper

- distill.py: VLM HF export uses --student_hf_path (the VLM config/tokenizer
  source), not --student_hf_model (which is unused for VLMs and only coincides
  via its default).
- quantize.py: only point non-VLM checkpoints at export_quantized_megatron_to_hf.py;
  quantized-VLM HF export is unsupported, so say so for VLMs.
- Move the duplicated _qwen35_moe_bridge_supported() helper into
  tests/_test_utils/examples/megatron_bridge.py.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>

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

Good work. I reviewed the READE first, let's resolves comments first, then I can review the code as well

Comment thread examples/megatron_bridge/README.md Outdated
Comment thread examples/megatron_bridge/README.md Outdated
Comment thread examples/megatron_bridge/README.md Outdated
Comment thread examples/megatron_bridge/README.md Outdated
Comment thread examples/megatron_bridge/README.md Outdated
Comment thread examples/megatron_bridge/README.md Outdated
Comment thread examples/megatron_bridge/README.md Outdated
`--student_hf_model` is also needed for heterogeneous (Puzzletron/NAS) students whose architecture differs from `--student_hf_path`; for standard (homogeneous) models it defaults to `--student_hf_path`, and it is unused for VLMs.

**Separate conversion** -- convert any saved iteration using the Megatron-Bridge conversion script:
**Separate conversion** -- convert **any** saved iteration (intermediate or final) with [export_distilled_megatron_to_hf.py](export_distilled_megatron_to_hf.py):

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.

why to emphasize it?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The bold any is intentional — it contrasts with the Inline path just above, which only exports the final checkpoint. It flags that the separate script can export any intermediate iteration too. Happy to drop the emphasis if you'd prefer.

Comment thread examples/megatron_bridge/README.md Outdated

## Resources

- 📅 [Roadmap](https://github.com/NVIDIA/Model-Optimizer/issues/1699)

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.

why to have roadmap here under resources, we do not have such resources section at other example readme files? we point road to a specific issue/1699 - will the roadmap always stay under this issue?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The ## Resources + 📅 Roadmap footer is a shared convention across all example READMEs (hf_ptq, pruning, llm_distill, llm_qat, diffusers, onnx_ptq, torch_onnx, torch_trt, speculative_decoding), and #1699 is the canonical Model-Optimizer roadmap issue — so I'd keep it here for consistency with the other examples rather than diverge.

Restructure the Distillation section: non-quantized methods (real-data / VLM)
followed by their HF conversion, then QAD (quantized, exported via
export_quantized) and Slurm; move Sanity-Check Generation last; add a workflows
intro; rename MEGATRON_BRIDGE_SRC_DIR; and clarify the --student_hf_model,
--trust_remote_code, and export --pp_size notes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
@kevalmorabia97

Copy link
Copy Markdown
Collaborator Author

Thanks for the review! Addressed all README comments in d5e97d8 (replied inline; resolved the addressed threads).

Two left open for your call:

  • any emphasis — kept deliberately to contrast with the Inline path (which only exports the final checkpoint); happy to drop it.
  • Roadmap under Resources — it's a shared footer across all example READMEs (hf_ptq, pruning, llm_distill, …), so I'd keep it for consistency.

Ready for the code review whenever you are.

…mporarily_pruned

_prune sets width hparams on all layers before dropping some, so dropped layers
retain pruned per-layer widths. Reattach the full layer list before sample(max)
so every layer -- including previously-dropped ones -- is reset to the max subnet
instead of being reattached in a stale state.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
@kevalmorabia97

kevalmorabia97 commented Jul 16, 2026

Copy link
Copy Markdown
Collaborator Author

Sanity check on Qwen3.6-35B-A3B with MMLU 5-shot (LM Eval Harness)

Original Qwen3.6-35B-A3B (34.7B, A3.5)

Groups Version Filter n-shot Metric Value Stderr
mmlu 2 none acc 0.8222 ± 0.0031
- humanities 2 none acc 0.7834 ± 0.0059
- other 2 none acc 0.8478 ± 0.0061
- social sciences 2 none acc 0.8866 ± 0.0055
- stem 2 none acc 0.7923 ± 0.0070

Pruned (22B, A3.0): Num experts 256->232, MoE FFN 512->384

Pruned 37% total and 15% active params

Groups Version Filter n-shot Metric Value Stderr
mmlu 2 none acc 0.7621 ± 0.0034
- humanities 2 none acc 0.7041 ± 0.0064
- other 2 none acc 0.7895 ± 0.0070
- social sciences 2 none acc 0.8479 ± 0.0064
- stem 2 none acc 0.7377 ± 0.0076

Distilled (100 iters @ 2.5B tokens using Nemotron-Pretraining-SFT-v1)

Groups Version Filter n-shot Metric Value Stderr
mmlu 2 none acc 0.7770 ± 0.0033
- humanities 2 none acc 0.7044 ± 0.0062
- other 2 none acc 0.8153 ± 0.0067
- social sciences 2 none acc 0.8690 ± 0.0060
- stem 2 none acc 0.7577 ± 0.0073


End-to-end tutorials that combine ModelOpt optimization techniques on [NVIDIA Megatron-Bridge](https://github.com/NVIDIA-NeMo/Megatron-Bridge) models.
Each one walks through a complete workflow using the scripts in [examples/megatron_bridge](../README.md) (`prune_minitron.py`, `distill.py`, `quantize.py`, `export.py`).
Each one walks through a complete workflow using the scripts in [examples/megatron_bridge](../README.md) (`prune_minitron.py`, `distill.py`, `quantize.py`, `export_quantized_megatron_to_hf.py`, `export_distilled_megatron_to_hf.py`).

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.

How about having one export script for any kind of megatron checkpoint, distilled or quantized or just pruned? - better UX

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Quantization export will be dropped soon. MBridge has some initial support to export quantized megatron to HF. I plan to extend it and drop custom quantized megatron import/export logic in modelopt. Leaving as it is for now

Comment thread examples/megatron_bridge/distill.py
Comment thread examples/megatron_bridge/distill.py Outdated
)
# Use object.__setattr__ to bypass DistillationProvider.__setattr__, which mirrors every attribute
# set onto the teacher -- assigning ``__class__`` normally would also switch the teacher's class.
object.__setattr__(provider, "__class__", submodule_cls)

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.

it seems hacky, likely this code should be in mbridge (modifying base distillation provider there), and schedule the work, at least put TODO here to refactor it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Everything in this file is already in MBridge but would be available in 26.08 container. Meanwhile this file adds temporary patching to unblock VLM models. Will be removed in next mbridge release

Comment thread examples/megatron_bridge/export_distilled_megatron_to_hf.py
Comment thread examples/megatron_bridge/export_distilled_megatron_to_hf.py
@@ -72,6 +72,11 @@
from modelopt.torch.utils.plugins.megatron_mmlu import megatron_mmlu

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.

is changing this file needed for QAD support for VLMs?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Some bug fixes I discovered when testing Qwen3.6 pruning that was previously not tested properly. Needed to pruned + distill

f"\nSaved quantized model to {args.export_megatron_path} in Megatron format. "
"To deploy this model (TensorRT-LLM / vLLM / SGLang), convert it to a Unified HF ckpt with export.py"
)
if is_vlm:

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.

similar comment as in other places to avoid if else paths for is_vlm

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The branch selects VLM-specific calibration (image-text dataset, calibrating only the language model) vs. text calibration -- inherent to the two modalities. Collapsing it would require unifying the LLM/VLM calibration paths, a larger refactor beyond this PR.

Comment thread modelopt/torch/nas/plugins/megatron_model_stats.py
…ider

Reframe --student_hf_model as a reference HF model with a homogeneous
architecture used as the export template for a heterogeneous (Puzzletron/NAS)
student (arg help in distill.py / export_distilled_megatron_to_hf.py, the
export_llm_to_hf docstring, and the README). Rename the distill.py local
run_provider -> distill_provider for clarity.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
…t TODO

Per review follow-ups: document the vision_config / language_model VLM-detection
convention in distill.py, and add a TODO in export_llm_to_hf to unify the LLM
export onto the in-memory path used for VLMs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
@kevalmorabia97
kevalmorabia97 enabled auto-merge (squash) July 16, 2026 14:20
@kevalmorabia97
kevalmorabia97 merged commit 21d0069 into main Jul 16, 2026
57 of 58 checks passed
@kevalmorabia97
kevalmorabia97 deleted the kmorabia/vlm-distill branch July 16, 2026 15:16
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.

4 participants