Skip to content

Preserve zero batches in histogram calibration - #2369

Open
MrCapricornLiu wants to merge 1 commit into
NVIDIA:mainfrom
MrCapricornLiu:MrCapricornLiu/fix/histogram-zero-batches
Open

MrCapricornLiu wants to merge 1 commit into
NVIDIA:mainfrom
MrCapricornLiu:MrCapricornLiu/fix/histogram-zero-batches

Conversation

@MrCapricornLiu

@MrCapricornLiu MrCapricornLiu commented Sep 10, 2026 •

Copy link
Copy Markdown

What does this PR do?

Type of change: Bug fix

Histogram calibration can fail when its first batch is all zeros and a later batch contains nonzero values. The initial bin edges are all zero, so growing the range divides by a zero bin width and raises OverflowError. torch.histc also places zeros in the middle of its automatic range when both bounds are zero.

Keep zero-only batches in the first bin, then rebuild the range when the first nonzero batch arrives and carry the previous zero counts into that bin. This preserves the calibrated distribution without imposing a minimum range that would lose resolution for small activations. Ordinary range growth and the NumPy collector are unchanged.

Usage

No API change. Existing histogram-calibrated TensorQuantizer calls accept initial zero batches.

Testing

  • All eight new cases fail on unmodified production code. The complete calibrator module passes 36 tests, with one pre-existing skipped test.
  • Tests compare every bin count with a NumPy histogram over the complete data, including repeated zero batches, negative values, small/large ranges, reset, and calibration followed by quantized inference through TensorQuantizer.
  • On an H800, FP32/FP16/BF16 × percentile/MSE/entropy: incremental calibration after zero batches matches one-shot calibration in histogram counts, amax and quantized output in all nine cases.
  • Changed-file pre-commit checks pass, including Ruff, mypy and Bandit.

This covers the default torch_hist=True, skip_zeros=False collector. Empty input after filtering with skip_zeros=True, nonfinite inputs, distributed calibration and full-model accuracy/performance were not tested or changed.

Before your PR is "Ready for review"

  • Backward compatible: yes; no API or serialized configuration changes.
  • Copied code or new PIP dependencies: none.
  • Necessary tests: added to the existing calibrator module.
  • Changelog: updated.
  • Upstream review: pending.

Additional Information

The histogram collector is separate from the NVFP4 activation headroom algorithm in #2028.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed histogram calibration for inputs that begin with zero-only batches and later contain nonzero values.
    • Preserved zero-valued samples in calibrated distributions and improved handling of all-zero inputs, percentile calculations, resets, and quantized outputs.
  • Tests

    • Added coverage for zero-value batches, histogram ranges, calibration recovery, percentile results, and finite quantized outputs.

@copy-pr-bot

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

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Histogram calibration now preserves zero-valued samples from initial batches, establishes a valid range for all-zero input, and expands the range when later batches contain nonzero values. Tests cover collection, reset, percentile calibration, and quantizer output.

Changes: Histogram calibration

Layer / File(s) Summary
Preserve zero batches during histogram collection
modelopt/torch/quantization/calib/histogram.py, CHANGELOG.rst
The collector preserves counts from zero-only batches, uses a fallback maximum of 1, and expands the histogram range for later nonzero values. The changelog records the fix.
Validate zero-batch calibration
tests/unit/torch/quantization/test_calibrator.py
Tests cover leading zero batches, all-zero input, reset behavior, percentile results, and finite quantizer output.

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

Change: Bug fix

Suggested reviewers: kevalmorabia97

Merge Risk: Minimal · up to 89438

No actionable issue remains from this review. The change is mergeable after normal checks.

Pre-merge checks: Passed 6

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly describes the main change to histogram calibration.
Docstring Coverage Passed Docstring coverage is inconclusive: files from earlier reviews still need to be rechecked within the check's analysis limits. Not blocking.
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 The package changes only modify histogram collection. They introduce none of the listed security patterns. The PR adds no dependencies.
Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 800c3f1 and 89438fa.

Files selected for processing: 2

  • CHANGELOG.rst
  • 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.

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

@kevalmorabia97

Copy link
Copy Markdown
Collaborator

Thanks for the contribution! This PR adds its CHANGELOG.rst entry under the older 0.48.0 section. New entries on main go in the 0.49.0 section at the top of the file. Could you move the entry there when you update your branch with the latest main?

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

kevalmorabia97 pushed a commit that referenced this pull request Oct 26, 2026
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

```sh
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.


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

## 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.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Signed-off-by: Sylvester Kaczmarek <[email protected]>
Keep the counts of an all-zero prefix in the first bin when the first
nonzero batch defines the histogram range, so those samples are not lost
from the calibrated distribution. Squashed the branch onto current main
and moved the CHANGELOG entry to the 0.49.0 section.

Signed-off-by: Chenghao Liu <[email protected]>
@MrCapricornLiu
MrCapricornLiu force-pushed the MrCapricornLiu/fix/histogram-zero-batches branch from 800c3f1 to 89438fa Compare November 6, 2026 07:46
@MrCapricornLiu

Copy link
Copy Markdown
Author

Rebased onto current main and moved the CHANGELOG entry into the 0.49.0 Bug Fixes section. The branch is now a single commit on top of main (89438fa1e).

Local verification with torch 2.15 on CPU:

  • New tests (test_initial_zero_batches, test_only_zero_batches, test_quantizer_calibration_after_zero_batch): 8 passed.
  • Same tests with the histogram.py change reverted: 8 failed — so they do pin the bug.
  • main's own test_entropy_preserves_collected_histogram was kept; the conflict there was only that both tests were appended at the same place.

I did not run the rest of test_calibrator.py. @kevalmorabia97 could you take another look?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants