Skip to content

Fix nested distillation forward contexts - #2653

Merged
kevalmorabia97 merged 6 commits into
NVIDIA:mainfrom
Michael-RDev:fix/nested-distillation-forward-contexts
Oct 26, 2026
Merged

kevalmorabia97 merged 6 commits into
NVIDIA:mainfrom
Michael-RDev:fix/nested-distillation-forward-contexts

Conversation

@Michael-RDev

@Michael-RDev Michael-RDev commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: Bug fix

I found that nesting only_student_forward() or only_teacher_forward() causes the outer context to stop working when the inner one exits. This also happens when the inner context uses enable=False.

Both context managers reset their flags to False on exit. This change saves the previous value and restores it in finally, so the enclosing context keeps its execution mode, including after an exception.

Public APIs, checkpoint handling, and loss calculations are unchanged.

Testing

Added eight regression cases using small local models and real forward passes. They cover:

  • Both teacher-only and student-only contexts.
  • Enabled and disabled inner contexts.
  • Normal exits and exceptions.
  • Normal execution after leaving a context.
  • Overlapping teacher/student contexts.

All eight cases fail before the fix and pass afterward.

Verified with CPU PyTorch:

  • Distillation and layerwise test modules — 39 passed.
  • All applicable pre-commit checks — passed, including Ruff, mypy, Bandit, and license checks.

GPU and distributed integration tests were not run.

Before this PR is ready for review

  • Backward compatible: Yes.
  • Copied code or new dependencies: None.
  • Necessary tests added: Yes.
  • Changelog updated: Yes.
  • Claude approval: Not obtained, as I don't use Claude.

Summary by CodeRabbit

  • Bug Fixes
    • Nested student-only and teacher-only forwarding contexts now preserve the surrounding execution mode when they exit, including when an inner context is disabled or raises an exception.
    • After nested contexts finish, subsequent model calls use the expected forwarding behavior. This applies when contexts are nested in either order and when exceptions occur inside either scope.

@Michael-RDev
Michael-RDev requested review from a team as code owners October 3, 2026 19:31
@Michael-RDev
Michael-RDev requested a review from ChenhanYu October 3, 2026 19:31
@copy-pr-bot

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

@coderabbitai

coderabbitai Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Review in 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

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between f6018ce and ff48223.

Files selected for processing: 3
  • CHANGELOG.rst
  • modelopt/torch/distill/distillation_model.py
  • tests/unit/torch/distill/test_distill.py
Files skipped from review as they are similar to previous changes: 1
  • CHANGELOG.rst

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 10 remain after this review.

Walkthrough

The student-only and teacher-only forward contexts now restore their saved mode flags when they exit. Tests cover nested contexts, disabled contexts, and exceptions.

Changes: Nested forward contexts

Layer / File(s) Summary
Restore forward mode after nested contexts
modelopt/torch/distill/distillation_model.py, tests/unit/torch/distill/test_distill.py, CHANGELOG.rst
The context managers save and restore their prior mode flags. Tests check nested context behavior, outputs, and call counts, including exception cases. The changelog records the fix.

Priority: Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: kevalmorabia97

Merge Risk: Minimal · up to ff482

The nested context restoration change is ready to merge.

Pre-merge checks: Passed 5 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 2 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed 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 and concisely describes the main change: fixing nested distillation forward contexts.
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. The authoritative diff changes only DistillationModel context restoration, regression tests, and a changelog entry. Added Python lines contain none of the prohibited patterns. No dependency-file…
Full details: Security Anti-Patterns

Explanation

PASS. The authoritative diff changes only DistillationModel context restoration, regression tests, and a changelog entry. Added Python lines contain none of the prohibited patterns. No dependency-file changes are present. SECURITY.md rules therefore identify no CRITICAL anti-pattern in this pull request.

Full details: Docstring Coverage

Explanation

Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 2 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

- Restore the previous teacher/student forward flags on context exit so nested and disabled contexts preserve the enclosing mode
- Add regression tests for nesting, exceptions, and overlapping contexts

Signed-off-by: Michael Rusu <[email protected]>
@Michael-RDev
Michael-RDev force-pushed the fix/nested-distillation-forward-contexts branch from c25fd72 to 5c33d27 Compare October 3, 2026 19:48
@kevalmorabia97

Copy link
Copy Markdown
Collaborator

Thanks for the contribution! This PR now has merge conflicts with main. Could you update your branch with the latest main and fix the conflicts so we can continue the review?

We've added the waiting for feedback label while we wait for your update.

@Michael-RDev

Michael-RDev commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Updated the branch with the lates and resolved the conflicts. Thanks for the heads-up :)

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

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

Approving: this is a small, correct fix. Each context manager now saves the previous value of its flag and puts it back in finally, the same way hide_teacher_model and hide_loss_modules already work. The new regression tests use real forward passes.

No action needed.

No action needed:

  • I checked the test expectations against DistillationModel.forward and they hold:
    • The overlapping contexts give student output in both orders, because _only_student_fwd is checked first.
    • The call counts work out to 3/4/5 in the non-overlapping cases.
  • No existing tests were changed, there are no licensing changes, and the CHANGELOG has an entry.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator

/ok to test ff48223

@kevalmorabia97
kevalmorabia97 enabled auto-merge (squash) October 26, 2026 19:33
@codecov

codecov Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.17%. Comparing base (e19ba61) to head (2d0fd91).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2653      +/-   ##
==========================================
+ Coverage   77.50%   79.17%   +1.66%     
==========================================
  Files         661      661              
  Lines       74972    74974       +2     
==========================================
+ Hits        58107    59360    +1253     
+ Misses      16865    15614    -1251     
Flag Coverage Δ
examples-diffusers 19.92% <0.00%> (+0.01%) ⬆️
examples-gpt-oss 13.45% <0.00%> (+<0.01%) ⬆️
examples-hf_ptq 23.35% <0.00%> (-0.03%) ⬇️
examples-llm_distill 13.53% <0.00%> (-0.01%) ⬇️
examples-llm_eval 17.19% <0.00%> (+0.01%) ⬆️
examples-llm_qat 17.36% <0.00%> (-0.01%) ⬇️
examples-llm_sparsity 16.76% <0.00%> (+<0.01%) ⬆️
examples-megatron_bridge 26.50% <50.00%> (-0.20%) ⬇️
examples-specdec_bench 13.23% <0.00%> (-0.01%) ⬇️
examples-speculative_decoding 17.44% <0.00%> (-0.05%) ⬇️
examples-torch_onnx 21.23% <0.00%> (-0.02%) ⬇️
examples-torch_trt 15.17% <0.00%> (+0.01%) ⬆️
examples-vllm_serve 17.40% <0.00%> (+0.01%) ⬆️
gpu 59.01% <50.00%> (+7.99%) ⬆️
regression 15.05% <0.00%> (-0.01%) ⬇️
unit 61.16% <100.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

/ok to test 2d0fd91

@kevalmorabia97
kevalmorabia97 merged commit 73f34fd into NVIDIA:main Oct 26, 2026
51 checks passed
@Michael-RDev
Michael-RDev deleted the fix/nested-distillation-forward-contexts branch October 26, 2026 20:34
kevalmorabia97 added a commit that referenced this pull request Oct 28, 2026
#2928 #2885 #2908 #2929 #2950 #2972 #2877 #2951 #2816 #3005 #3012 #2971 #3015 #3006 #3026 #2988 #3028 #1860 #3030 #2612 #3033 #2653 #2599 #2655 #2618 #2868 #3032 #3027 #2869 #2984 #2975 #2345 #3020 #2997 (#3072)

## Cherry-picked PRs

- #2817
- #2671
- #2892
- #2876
- #2910
- #2911
- #2919
- #2904
- #2937
- #2928
- #2885
- #2908
- #2929
- #2950
- #2972
- #2877
- #2951
- #2816
- #3005
- #3012
- #2971
- #3015
- #3006
- #3026
- #2988
- #3028
- #1860
- #3030
- #2612
- #3033
- #2653
- #2599
- #2655
- #2618
- #2868
- #3032
- #3027
- #2869
- #2984
- #2975
- #2345
- #3020
- #2997

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Diffusion exports now offer more control over attention-quantizer
metadata and preserve sparse-attention settings in a format compatible
with downstream tooling.
* Model loading better handles select bundled model implementations, and
Docker guidance now covers writable CUDA-extension cache locations.
* **Bug Fixes**
* Improved reliability for model export and checkpoint saving,
quantization across devices, ONNX processing, and calibration.
* Temporary TensorRT and autotuning artifacts now use private
directories by default.
* **Documentation**
* Updated installation guidance, compatibility notes, and links;
corrected typos across guides and examples.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Chad Voegele <[email protected]>
Signed-off-by: Rohan Joshi <[email protected]>
Signed-off-by: LinCanNerd <[email protected]>
Signed-off-by: Keval Morabia <[email protected]>
Signed-off-by: weimingc <[email protected]>
Signed-off-by: Noey Yang <[email protected]>
Signed-off-by: Kai Xu <[email protected]>
Signed-off-by: Zhehao Hu <[email protected]>
Signed-off-by: noeyy-mino <[email protected]>
Signed-off-by: joe-nv <[email protected]>
Signed-off-by: yingguo-trt <[email protected]>
Signed-off-by: Shengliang Xu <[email protected]>
Signed-off-by: Chenjie Luo <[email protected]>
Signed-off-by: anmaurya001 <[email protected]>
Signed-off-by: Connor Baker <[email protected]>
Signed-off-by: wiederse <[email protected]>
Signed-off-by: Vu Dinh <[email protected]>
Signed-off-by: Pratik Gandhi <[email protected]>
Signed-off-by: Michael Rusu <[email protected]>
Signed-off-by: Michael-Rusu <[email protected]>
Signed-off-by: namgyu-youn <[email protected]>
Signed-off-by: Sylvester Kaczmarek <[email protected]>
Signed-off-by: Javier de Jesus <[email protected]>
Signed-off-by: javierdejesusda <[email protected]>
Signed-off-by: Zhiyu Cheng <[email protected]>
Signed-off-by: Juhi Mittal <[email protected]>
Signed-off-by: Dmitry Rantovov <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
Co-authored-by: Chad Voegele <[email protected]>
Co-authored-by: LinCanNerd <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Keval Morabia <[email protected]>
Co-authored-by: Wei-Ming Chen <[email protected]>
Co-authored-by: noeyy-mino <[email protected]>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: kaix-nv <[email protected]>
Co-authored-by: Zhehao Hu <[email protected]>
Co-authored-by: joe <[email protected]>
Co-authored-by: yingguo-trt <[email protected]>
Co-authored-by: Shengliang Xu <[email protected]>
Co-authored-by: Chenjie Luo <[email protected]>
Co-authored-by: anmaurya001 <[email protected]>
Co-authored-by: Connor Baker <[email protected]>
Co-authored-by: Jiao Mingyang <[email protected]>
Co-authored-by: Vu Dinh <[email protected]>
Co-authored-by: Pratik Gandhi <[email protected]>
Co-authored-by: Michael R <[email protected]>
Co-authored-by: Michael-Rusu <[email protected]>
Co-authored-by: namgyu-youn <[email protected]>
Co-authored-by: Sylvester Kaczmarek <[email protected]>
Co-authored-by: Javier De Jesus <[email protected]>
Co-authored-by: Zhiyu <[email protected]>
Co-authored-by: Juhi Mittal <[email protected]>
Co-authored-by: Dmitry Rantovov <[email protected]>
Co-authored-by: h-guo18 <[email protected]>
@rohansjoshi rohansjoshi added the cherry-pick-done Added by bot once PR is cherry-picked to the release branch label Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cherry-pick-0.48.0 cherry-pick-done Added by bot once PR is cherry-picked to the release branch waiting for feedback

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants