Skip to content

Preserve histogram counts during entropy calibration - #2655

Merged
kevalmorabia97 merged 3 commits into
NVIDIA:mainfrom
sylvesterkaczmarek:fix/entropy-preserve-calibration-histogram
Oct 26, 2026
Merged

kevalmorabia97 merged 3 commits into
NVIDIA:mainfrom
sylvesterkaczmarek:fix/entropy-preserve-calibration-histogram

Conversation

@sylvesterkaczmarek

@sylvesterkaczmarek sylvesterkaczmarek commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2654.

What changed

Make the entropy calibration helper copy its input histogram before applying its existing first-bin adjustment. A NumPy slice is a view, so the previous implementation modified the collector's persistent counts. Subsequent percentile/MSE queries and continued collection could then use the altered distribution.

The regression uses the public HistogramCalibrator with both histogram backends. It checks unchanged counts and edges, repeated entropy queries, unchanged percentile thresholds, and equivalence with an untouched reference collector after another batch.

Validation

python -m pytest -q tests/unit/torch/quantization/test_calibrator.py   tests/unit/torch/quantization/test_tensor_quantizer_cpu.py   tests/unit/torch/quantization/test_print.py

79 passed, 1 existing skip on CPU. The focused regression on unchanged upstream gives 1 failure for NumPy histograms and 1 pass for PyTorch histograms. Repository pre-commit checks pass for the changed files.

No new dependencies or public API changes. CUDA execution was not run. This is independent of #2369: its zero-prefix changes affect collection, while this patch changes only the entropy calculation. The changelog is updated.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed entropy-based calibration so repeated calculations preserve collected histogram counts and bin edges. Percentile and entropy results remain consistent, and collecting additional data after a calculation now produces calibration results consistent with uninterrupted collection. The fix applies to both NumPy- and Torch-based histograms, ensuring calibration state remains stable across calculation and collection steps.

@copy-pr-bot

copy-pr-bot Bot commented Oct 4, 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 4, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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 0f7b087 and 6e5c0bf.

Files selected for processing: 3
  • CHANGELOG.rst
  • modelopt/torch/quantization/calib/histogram.py
  • tests/unit/torch/quantization/test_calibrator.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; 11 remain after this review.

Walkthrough

The entropy calibration helper copies the histogram before changing its first bin. Regression tests check histogram preservation and subsequent calibration behavior for both histogram backends.

Changes: Entropy histogram preservation

Layer / File(s) Summary
Copy histogram data and verify repeated calculations
modelopt/torch/quantization/calib/histogram.py, tests/unit/torch/quantization/test_calibrator.py, CHANGELOG.rst
The entropy helper now copies the histogram before adjusting its first bin. Tests cover both histogram backends and check repeated calculations, percentile results, and subsequent collection. The changelog records the fix.

Priority: Normal

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

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: kevalmorabia97, cjluo-nv

Merge Risk: Minimal · up to 6e5c0

No actionable merge-blocking risk remains.

Pre-merge checks: Passed 5 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 2 files. (1 skipped: 1… 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 "Preserve histogram counts during entropy calibration" matches the main change: the entropy calibration helper now copies the histogram before its first-bin adjustment, so persistent NumPy c…
Linked Issues check Passed Issue #2654 requires entropy calibration to use a private histogram copy and to preserve counts during repeated queries and later collection. The PR changes _compute_amax_entropy to use `calib_hist.…
Out of Scope Changes check Passed The source change directly implements issue #2654. The regression test verifies the required behavior. The changelog documents the same fix. The summary reports no public API or dependency changes and…
Security Anti-Patterns Passed PASS. The pull request changes only modelopt/torch/quantization/calib/histogram.py, a test file, and CHANGELOG.rst. The Python additions only copy histogram data and add regression tests. No added…
Full details: Title check

Explanation

The title "Preserve histogram counts during entropy calibration" matches the main change: the entropy calibration helper now copies the histogram before its first-bin adjustment, so persistent NumPy counts are not modified. The title is specific, concise, and describes the primary behavior change. The changelog entry, histogram.py edit, and regression test all support this focus.

Full details: Linked Issues check

Explanation

Issue #2654 requires entropy calibration to use a private histogram copy and to preserve counts during repeated queries and later collection. The PR changes _compute_amax_entropy to use calib_hist.copy(). The added parameterized test covers NumPy and PyTorch backends, unchanged counts and edges, repeated entropy results, percentile results, and continued collection against an untouched reference. Issue #2369 is separate and adds no requirement here.

Full details: Out of Scope Changes check

Explanation

The source change directly implements issue #2654. The regression test verifies the required behavior. The changelog documents the same fix. The summary reports no public API or dependency changes and shows no unrelated changes.

Full details: Security Anti-Patterns

Explanation

PASS. The pull request changes only modelopt/torch/quantization/calib/histogram.py, a test file, and CHANGELOG.rst. The Python additions only copy histogram data and add regression tests. No added torch.load(..., weights_only=False), numpy.load(..., allow_pickle=True), trust_remote_code=True, eval(), exec(), or # nosec usage was found. No dependency files changed.

Full details: Docstring Coverage

Explanation

Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 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.

@sylvesterkaczmarek

Copy link
Copy Markdown
Contributor Author

Resolved the changelog conflict with current main in 0f7b087. The histogram fix is unchanged; 79 CPU tests pass, one existing case skips, and pre-commit passes. Could a maintainer approve the waiting workflows and review?

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

@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 correct one-line fix with a solid regression test. calib_hist[:] returned a NumPy view, so bins[0] = bins[1] overwrote the counts the collector keeps. .copy() stops that.

No action needed:

  • compute_amax always passes a NumPy array to _compute_amax_entropy, because torch histograms are converted with .int().cpu().numpy() first. So .copy() is valid for both backends. The torch path was already making a copy through that conversion, which is why the test only fails on the NumPy backend before the fix.
  • The parametrized test covers both histogram backends. It checks that counts and edges are unchanged and that repeated entropy calls give the same result. It also confirms percentile results stay stable and match an untouched reference collector after another batch is collected.
  • There are no licensing changes, and no existing tests were modified.

Testing: No test plan or testing section found in the PR description.

Suggested test plan:

  • Run the new test_entropy_preserves_collected_histogram against unchanged upstream and against the fix, for both torch_hist=False and torch_hist=True. Confirm it fails on upstream with NumPy histograms and passes with the fix. This shows the test catches the view-aliasing bug.
  • Run the full tests/unit/torch/quantization/test_calibrator.py suite plus the tensor quantizer tests. Confirm the existing entropy, percentile and MSE amax tests still produce the same thresholds. The first-bin adjustment should behave the same; only the input is no longer mutated.
  • Check the torch-histogram path through _compute_amax_entropy. Confirm calib_hist there is always a NumPy array (e.g. from .cpu().numpy()) so that .copy() is valid. If it can be a torch.Tensor, .copy() would raise, so test or convert to np.array(calib_hist, copy=True) instead.
  • If a GPU is available, run the new regression test with CUDA inputs, using torch_hist=True and tensors on the device. CUDA was not exercised, and the torch histogram path may keep counts on the GPU.
  • Do an end-to-end calibration of a small model with method="entropy", then run a further calibration or percentile query on the same quantizers. Confirm the amax values match a fresh collector given identical data.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator

/ok to test 6e5c0bf

@sylvesterkaczmarek

Copy link
Copy Markdown
Contributor Author

Thanks for the heads-up. I merged current main in 6e5c0bf, resolved the changelog conflict while keeping both sets of entries, and verified the PR is mergeable again. The histogram fix and its regression are unchanged relative to main; Python compilation and Git whitespace checks pass. The full CPU suite has not been rerun on this merge.

@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.16%. Comparing base (0b953a3) to head (6e5c0bf).
⚠️ Report is 11 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2655      +/-   ##
==========================================
+ Coverage   77.50%   79.16%   +1.66%     
==========================================
  Files         661      661              
  Lines       74970    74970              
==========================================
+ Hits        58107    59353    +1246     
+ Misses      16863    15617    -1246     
Flag Coverage Δ
examples-diffusers 19.92% <0.00%> (+0.02%) ⬆️
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.02%) ⬇️
examples-llm_sparsity 16.76% <0.00%> (+<0.01%) ⬆️
examples-megatron_bridge 26.50% <0.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.01%) ⬇️
examples-torch_trt 15.17% <0.00%> (+0.01%) ⬆️
examples-vllm_serve 17.40% <0.00%> (+0.01%) ⬆️
gpu 59.01% <100.00%> (+7.98%) ⬆️
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
kevalmorabia97 merged commit cc016cc into NVIDIA:main Oct 26, 2026
55 of 57 checks passed
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.

Entropy calibration mutates the stored NumPy histogram

4 participants