Skip to content

[2/2] Add --fake_quant_weight_cache to the Megatron-Bridge distill example - #3047

Closed
kevalmorabia97 wants to merge 1 commit into
kmorabia/fake-quant-weight-cachefrom
kmorabia/fake-quant-weight-cache-distill
Closed

kevalmorabia97 wants to merge 1 commit into
kmorabia/fake-quant-weight-cachefrom
kmorabia/fake-quant-weight-cache-distill

Conversation

@kevalmorabia97

@kevalmorabia97 kevalmorabia97 commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Type of change: new feature

Part 2 of 2, stacked on #3034 (merge that first). Until it merges, this PR also shows #3034's two commits; only the last commit (Add --fake_quant_weight_cache ...) is new here.

Adds --fake_quant_weight_cache to examples/megatron_bridge/distill.py. It turns on the fake-quant weight cache from #3034 for QAD: each step fake-quantizes every student weight once and reuses it for all micro-batches and activation recomputations of that step.

  • The cache scope is opened and closed with Megatron-Bridge's own training callbacks (on_train_start enrolls the student's weight quantizers, on_train_step_start / on_train_step_end open and close the scope), so no Bridge code is patched. The scope closes before evaluation and the next step, which see the updated weights.
  • Megatron-Bridge's distill() takes no callbacks, so the script now calls pretrain(config, forward_step_modelopt, callbacks=...) directly, which is what distill() does. The only thing skipped is a context-parallel check for distilling a whole mrope VLM, which this script never does (it distills only the language model).
  • The flag requires a quantized --student_megatron_path and fails at startup otherwise.

Why a flag and not always on: the cache keeps an extra BF16 copy of the student's quantized weights on every GPU. On the large-MoE run below that is about +21 GiB/GPU, leaving ~10 GiB of headroom; recipes that already run near the memory limit would go out of memory on upgrade. Some recipes also cannot use it (pass_through_bwd=False, composed quantizers such as W4A8) and enrollment rejects them.

Usage

torchrun --nproc_per_node 8 distill.py \
    --student_megatron_path /output/qwen3_8b_nvfp4_ptq ... \
    --fake_quant_weight_cache

Testing

  • tests/examples/megatron_bridge/test_qad.py: the non-LoRA LLM case now trains with --fake_quant_weight_cache, then trains again without it, and checks that every saved model tensor is bit-identical. test_qad[qwen3] passes in nemo:26.08 (1 GPU), and fails when the cache's backward is changed to return a zero gradient. I did not run the LoRA and VLM cases (they do not use the cache path).

  • tests/examples/megatron_bridge/test_mlflow_utils.py: 75 passed.

  • QAD of a large MoE model (GGML IQ2_S + NVFP4 weight-only student, 32 nodes × 4 GB300, GBS 3840, 6 iterations each, 846 cached quantizers per rank):

    Uncached Cached
    s/iter, iters 2-6 423 / 419 / 411 / 417 / 415 (mean 417) 372 / 364 / 348 / 334 / 330 (mean 350)
    Reserved GPU memory, median / max over ranks 249 / 253 GiB 270 / 273 GiB

    −16% step time on average, about −20% by iterations 5-6. KD loss matched within 0.1% per iteration, the same as run-to-run noise (iteration 1 already differs by 1e-4). GGML caches its packed codes and only re-decodes per forward, so formats with more expensive fake quant should gain more.

Before your PR is "Ready for review"

  • Is this change backward compatible?: ✅ (opt-in flag; without it training runs the same step function as before)
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A (adapted from NVIDIA-internal code by the co-authors; no third-party code or new dependency)
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: ✅
  • Did you get Claude approval on this PR?: ❌ (pending)

Additional Information

Part 1: #3034. Co-authored with Frank Sun, Sweta Priyadarshi and Keith Wyss, whose training-loop integration this follows.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added optional caching of fake-quantized weights for QAT/QAD, reusing quantized weights across micro-batches and activation recomputations within an optimizer step.
    • Added a cache option to Megatron distillation when the student checkpoint contains ModelOpt state. Results are bit-identical to uncached training for the documented setup.
    • Added public controls for enabling, disabling, and invalidating the cache, plus cache usage statistics.
  • Documentation
    • Added guidance on cache requirements and memory overhead: caching uses an additional BF16 copy of student weights per GPU.

Open the fake-quant weight cache for each QAD step through Megatron-Bridge
training callbacks, so every micro-batch and activation recomputation of a
step reuses the student's fake-quantized weights. distill() takes no
callbacks, so the script calls pretrain() with the same ModelOpt step.

test_qad checks that a cached run saves bit-identical weights to an
uncached one.

Co-authored-by: Frank Sun <[email protected]>
Co-authored-by: Sweta Priyadarshi <[email protected]>
Co-authored-by: Keith Wyss <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Keval Morabia <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

🗂️ Base branches to auto review: 3
  • main
  • release/.*
  • feature/.*

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

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
Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@shengliangxu shengliangxu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Bot review (bedrock-claude-opus-5-5) — DM the bot to share feedback.

Nudge: the callback integration looks correct and the bit-identical cached-vs-uncached test is solid, but every run, flagged or not, now bypasses Bridge's distill(). A human with Megatron-Bridge context should confirm that's safe.

Needs action:

  • Confirm that calling pretrain(config, forward_step_modelopt, callbacks=...) matches Bridge's distill() in the nemo:26.08 and 26.10 containers. The only check it skips should be the mrope context-parallel one, which this script doesn't need.
  • Run test_qad[qwen3_5_moe_vl] and test_qad[qwen3_lora_nvfp4] on multiple GPUs. The VLM case now passes --fake_quant_weight_cache and, when HAS_MROPE_CP_FIX is set, runs at cp_size>1 with the Bridge check skipped. Neither case was run.
  • Rebase onto main once #3034 merges, so only the distill.py, README, CHANGELOG and test changes remain in this diff.

No action needed:

  • The test_mlflow_utils.py assertion edit is justified: it tracks the distill() → pretrain() call change and isn't weaker.
  • The ExitStack reset in on_train_start correctly handles a scope left open after an in-process restart.
  • About 322 core-logic lines, including #3034's, which is under the 500-line budget. New files carry the standard header, and the code is NVIDIA-internal, not third-party.

@github-actions

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-3047/

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

@kevalmorabia97
kevalmorabia97 changed the base branch from main to kmorabia/fake-quant-weight-cache October 27, 2026 07:31
@codecov

codecov Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.09%. Comparing base (b8c2492) to head (ad42b74).

Additional details and impacted files
@@                        Coverage Diff                        @@
##           kmorabia/fake-quant-weight-cache    #3047   +/-   ##
=================================================================
  Coverage                             79.09%   79.09%           
=================================================================
  Files                                   662      662           
  Lines                                 79097    79097           
=================================================================
  Hits                                  62559    62559           
  Misses                                16538    16538           
Flag Coverage Δ
examples-diffusers 19.95% <ø> (ø)
examples-gpt-oss 13.49% <ø> (ø)
examples-hf_ptq 23.38% <ø> (ø)
examples-llm_distill 13.57% <ø> (ø)
examples-llm_eval 17.23% <ø> (ø)
examples-llm_qat 17.40% <ø> (ø)
examples-llm_sparsity 16.80% <ø> (ø)
examples-megatron_bridge 26.61% <ø> (+0.09%) ⬆️
examples-specdec_bench 13.27% <ø> (ø)
examples-speculative_decoding 17.47% <ø> (ø)
examples-torch_onnx 21.26% <ø> (ø)
examples-torch_trt 15.21% <ø> (ø)
examples-vllm_serve 17.44% <ø> (ø)
gpu 59.00% <ø> (ø)
regression 15.08% <ø> (ø)
unit 61.47% <ø> (-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

Folded into #3034 (commit f272fd7), which now uses distill(config, callbacks=...) from NVIDIA-NeMo/Megatron-Bridge#6686 instead of calling pretrain() directly.

@kevalmorabia97
kevalmorabia97 deleted the kmorabia/fake-quant-weight-cache-distill branch October 27, 2026 08:05
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