Skip to content

MBridge VLM distillation / QAD support#1938

Open
kevalmorabia97 wants to merge 3 commits into
mainfrom
kmorabia/vlm-distill
Open

MBridge VLM distillation / QAD support#1938
kevalmorabia97 wants to merge 3 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

  • 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 support for exporting distilled Megatron checkpoints to Hugging Face, including separate LLM and VLM flows.
    • Extended Megatron-Bridge distillation support for vision-language language-model components.
  • Bug Fixes

    • Updated quantization and distillation workflows to use the unified Hugging Face exporter instead of older export commands.
  • Documentation

    • Refreshed Megatron-Bridge READMEs and tutorials to reflect the new export scripts and CLI guidance.
  • Tests

    • Expanded and refactored Megatron-Bridge distillation, QAD, and quantization/export tests for LLM and VLM coverage, including conditional skipping where needed.

@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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: e4c5f748-572e-4f00-9277-39e9b78c77fc

📥 Commits

Reviewing files that changed from the base of the PR and between 623b6c9 and 3b7106a.

📒 Files selected for processing (15)
  • 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/_test_utils/examples/megatron_bridge.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
✅ Files skipped from review due to trivial changes (6)
  • examples/megatron_bridge/tutorials/README.md
  • examples/megatron_bridge/quantize.py
  • examples/megatron_bridge/export_quantized_megatron_to_hf.py
  • CHANGELOG.rst
  • examples/megatron_bridge/tutorials/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16/README.md
  • examples/megatron_bridge/README.md
🚧 Files skipped from review as they are similar to previous changes (9)
  • tests/_test_utils/examples/megatron_bridge.py
  • tests/examples/megatron_bridge/test_prune_minitron.py
  • examples/megatron_bridge/_distillation_provider.py
  • tests/examples/megatron_bridge/test_quantize_export.py
  • examples/megatron_bridge/export_distilled_megatron_to_hf.py
  • modelopt/torch/utils/plugins/mbridge.py
  • tests/examples/megatron_bridge/test_qad.py
  • examples/megatron_bridge/distill.py
  • tests/examples/megatron_bridge/test_distill.py

📝 Walkthrough

Walkthrough

Adds VLM-aware Megatron-Bridge distillation, a new distilled checkpoint export script, updated checkpoint restore behavior, and broad renames from export.py to export_quantized_megatron_to_hf.py across docs, scripts, and tests.

Changes

Megatron-Bridge distillation and export flow

Layer / File(s) Summary
Distillation provider wrapper
examples/megatron_bridge/_distillation_provider.py
Adds convert_to_distillation_provider that defers KD conversion to a post-weight-load hook and supports optional submodule-restricted distillation.
mbridge state restore and MoE support
modelopt/torch/utils/plugins/mbridge.py, tests/_test_utils/examples/megatron_bridge.py, tests/examples/megatron_bridge/test_prune_minitron.py
Removes the Qwen3.5 MoE sequential-expert patch helper, adds conditional ModelOpt state restoration for checkpoint loading, and adds MoE bridge support gating for prune tests.
distill.py VLM-aware training and export
examples/megatron_bridge/distill.py
Detects VLMs, restricts distillation to the language model submodule, restores student weights from Megatron checkpoints, and switches export handling to the new HF helpers.
New distilled-to-HF exporter
examples/megatron_bridge/export_distilled_megatron_to_hf.py, examples/megatron_bridge/export_quantized_megatron_to_hf.py
Adds a script that exports distilled Megatron checkpoints to Hugging Face format with separate VLM and LLM paths, and updates the quantized exporter example command.
Distillation and MoE test coverage
tests/examples/megatron_bridge/test_distill.py, tests/examples/megatron_bridge/test_qad.py, tests/examples/megatron_bridge/test_quantize_export.py
Replaces the LLM distillation test, adds VLM distillation coverage, and updates QAD and quantize/export tests for the new exporter names and support gating.

Megatron-Bridge export name updates

Layer / File(s) Summary
Docs and changelog updates
CHANGELOG.rst, examples/megatron_bridge/README.md, examples/megatron_bridge/tutorials/README.md, examples/megatron_bridge/tutorials/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16/README.md
Updates changelog and Megatron-Bridge documentation to reference the new export scripts and revised conversion flow.
Quantize docs, logs, and tests
examples/megatron_bridge/quantize.py, tests/examples/megatron_bridge/test_quantize_export.py
Updates quantize script messaging and export examples, and switches the quantize export test to the new script name while dropping the VLM-only path.

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

Sequence Diagram(s)

sequenceDiagram
  participant distill.py
  participant convert_to_distillation_provider
  participant _convert_hook
  participant mtd.convert
  participant export_llm_to_hf
  participant save_vlm_to_hf

  distill.py->>convert_to_distillation_provider: build distillation provider
  convert_to_distillation_provider->>convert_to_distillation_provider: append _convert_hook to _pre_wrap_hooks
  distill.py->>convert_to_distillation_provider: load weights
  convert_to_distillation_provider->>_convert_hook: invoke _convert_hook
  _convert_hook->>mtd.convert: convert KD model

  distill.py->>save_vlm_to_hf: export VLM after distillation
  distill.py->>export_llm_to_hf: export LLM checkpoint after distillation
Loading

Suggested reviewers: jenchen13, claude

🚥 Pre-merge checks | ✅ 5 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly reflects the main change set: Megatron-Bridge VLM distillation and QAD support.
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 Scanned all changed Python files; no unsafe torch.load/numpy.load, eval/exec, # nosec, or hardcoded trust_remote_code=True found.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 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

QR code for preview link

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

Built to branch gh-pages at 2026-07-09 15:48 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

Comment thread examples/megatron_bridge/_distillation_provider.py
@codecov

codecov Bot commented Jul 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 77.14%. Comparing base (42458de) to head (3b7106a).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1938      +/-   ##
==========================================
- Coverage   77.79%   77.14%   -0.66%     
==========================================
  Files         519      519              
  Lines       57926    58059     +133     
==========================================
- Hits        45064    44789     -275     
- Misses      12862    13270     +408     
Flag Coverage Δ
examples 43.21% <100.00%> (-0.19%) ⬇️
gpu 57.83% <0.00%> (-0.63%) ⬇️
regression 14.93% <0.00%> (+0.07%) ⬆️
unit 55.23% <0.00%> (+0.01%) ⬆️

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 and others added 3 commits July 9, 2026 08:45
- 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>
@kevalmorabia97 kevalmorabia97 force-pushed the kmorabia/vlm-distill branch from 623b6c9 to 3b7106a Compare July 9, 2026 15:45
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.

2 participants