Skip to content

[5676209][ONNX][Autocast] Add support for single npz file with multiple samples - #815

Merged
gcunhase merged 3 commits into
NVIDIA:mainfrom
gcunhase:dev/gcunhasergio/5676209_calib_data_npz_multiple_samples
Jan 26, 2026
Merged

gcunhase merged 3 commits into
NVIDIA:mainfrom
gcunhase:dev/gcunhasergio/5676209_calib_data_npz_multiple_samples

Conversation

@gcunhase

@gcunhase gcunhase commented Jan 23, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: New feature

Overview: Currently, Autocast only supports calibration data with shape matching the model's input. This PR adds support for calibration data with shape that is a multiple of the model's input. It does so by re-arranging the data as such that it contains multiple samples with shape matching the model's input.

Simplified example:

  • ONNX input: [1, 3, 224, 224]
  • Calibration data: [10, 3, 224, 224]
  • Calibration data with multiple samples: [1, 3, 224, 224] * 10

Usage

Single npz file with multiple samples:

$ python -m modelopt.onnx.autocast --onnx_path=$MODEL_NAME.onnx --calibration_data=calib_data_10.npz

Testing

See bug 5676209.

Before your PR is "Ready for review"

  • Make sure you read and follow Contributor guidelines and your commits are signed.
  • Is this change backward compatible?: Yes
  • Did you write any new necessary tests?: No
  • Did you add or update any necessary documentation?: No
  • Did you update Changelog?: Yes

Additional Information

Equivalent support is already included in the quantization workflow:

Ex. If a model has input shapes like {"sample": (2, 4, 64, 64), "timestep": (1,),

Summary by CodeRabbit

  • New Features
    • CalibrationDataProvider now accepts both file paths and pre-loaded ONNX models as input.
    • NPZ calibration files can now provide multiple batches for calibration workflows.

✏️ Tip: You can customize this high-level summary in your review settings.

@gcunhase
gcunhase requested review from a team as code owners January 23, 2026 21:50
@gcunhase
gcunhase requested a review from galagam January 23, 2026 21:50
@coderabbitai

coderabbitai Bot commented Jan 23, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto incremental reviews are disabled on this repository.

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.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

These changes modify calibration data handling in ONNX quantization. CalibrationDataProvider now accepts pre-loaded ONNX ModelProto objects in addition to file paths, and the reference runner wraps NPZ calibration data within CalibrationDataProvider to enable batch handling from single files.

Changes

Cohort / File(s) Summary
NPZ Data Wrapping
modelopt/onnx/autocast/referencerunner.py
Added CalibrationDataProvider import; modified _load_inputs_from_npz to wrap NPZ data in CalibrationDataProvider and return calibration_data_list instead of single array for multi-batch support.
Model Input Flexibility
modelopt/onnx/quantization/calib_utils.py
Widened CalibrationDataProvider.init parameter type from str to `str

Sequence Diagram

sequenceDiagram
    participant RR as Reference Runner
    participant CDP as CalibrationDataProvider
    participant ONNX as ONNX Model

    rect rgba(100, 149, 237, 0.5)
    Note over RR,ONNX: New Flow: NPZ Data with CalibrationDataProvider
    RR->>RR: Load NPZ file
    RR->>CDP: Wrap NPZ data + model path
    CDP->>ONNX: Load model from path (if string)
    ONNX-->>CDP: ModelProto returned
    CDP-->>RR: CalibrationDataProvider with batches
    end

    rect rgba(144, 238, 144, 0.5)
    Note over RR,ONNX: Alternative: Pre-loaded Model
    RR->>RR: Load NPZ file + ModelProto
    RR->>CDP: Wrap NPZ data + ModelProto
    CDP->>CDP: Use ModelProto directly (skip loading)
    CDP-->>RR: CalibrationDataProvider with batches
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: adding support for single NPZ files with multiple samples in ONNX Autocast.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Signed-off-by: gcunhase <[email protected]>
@codecov

codecov Bot commented Jan 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 74.29%. Comparing base (4f4558a) to head (a496175).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #815      +/-   ##
==========================================
+ Coverage   74.17%   74.29%   +0.12%     
==========================================
  Files         192      192              
  Lines       19246    19251       +5     
==========================================
+ Hits        14276    14303      +27     
+ Misses       4970     4948      -22     

☔ View full report in Codecov by Sentry.
📢 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.

@gcunhase
gcunhase merged commit 8c36f5a into NVIDIA:main Jan 26, 2026
35 checks passed
danielkorzekwa pushed a commit that referenced this pull request Feb 17, 2026
…iple samples (#815)

## What does this PR do?

**Type of change:** New feature

**Overview:** Currently, Autocast only supports calibration data with
shape matching the model's input. This PR adds support for calibration
data with shape that is a multiple of the model's input. It does so by
re-arranging the data as such that it contains multiple samples with
shape matching the model's input.

Simplified example:
- ONNX input: `[1, 3, 224, 224]`
- Calibration data: `[10, 3, 224, 224]`
- Calibration data with multiple samples: `[1, 3, 224, 224] * 10`

## Usage
Single `npz` file with multiple samples:
```sh
$ python -m modelopt.onnx.autocast --onnx_path=$MODEL_NAME.onnx --calibration_data=calib_data_10.npz
```

## Testing
See bug 5676209.

## Before your PR is "*Ready for review*"
<!-- If you haven't finished some of the above items you can still open
`Draft` PR. -->

- **Make sure you read and follow [Contributor
guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md)**
and your commits are signed.
- **Is this change backward compatible?**: Yes
- **Did you write any new necessary tests?**: No
- **Did you add or update any necessary documentation?**: No
- **Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?**:
Yes

## Additional Information
Equivalent support is already included in the quantization workflow:
https://github.com/NVIDIA/Model-Optimizer/blob/1cc8e6bf3917f61500e81d4ded0af5d5a00e2e25/modelopt/onnx/quantization/calib_utils.py#L50


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

## Summary by CodeRabbit

* **New Features**
* CalibrationDataProvider now accepts both file paths and pre-loaded
ONNX models as input.
* NPZ calibration files can now provide multiple batches for calibration
workflows.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>

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

---------

Signed-off-by: gcunhase <[email protected]>
danielkorzekwa pushed a commit that referenced this pull request Mar 4, 2026
…iple samples (#815)

## What does this PR do?

**Type of change:** New feature

**Overview:** Currently, Autocast only supports calibration data with
shape matching the model's input. This PR adds support for calibration
data with shape that is a multiple of the model's input. It does so by
re-arranging the data as such that it contains multiple samples with
shape matching the model's input.

Simplified example:
- ONNX input: `[1, 3, 224, 224]`
- Calibration data: `[10, 3, 224, 224]`
- Calibration data with multiple samples: `[1, 3, 224, 224] * 10`

## Usage
Single `npz` file with multiple samples:
```sh
$ python -m modelopt.onnx.autocast --onnx_path=$MODEL_NAME.onnx --calibration_data=calib_data_10.npz
```

## Testing
See bug 5676209.

## Before your PR is "*Ready for review*"
<!-- If you haven't finished some of the above items you can still open
`Draft` PR. -->

- **Make sure you read and follow [Contributor
guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md)**
and your commits are signed.
- **Is this change backward compatible?**: Yes
- **Did you write any new necessary tests?**: No
- **Did you add or update any necessary documentation?**: No
- **Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?**:
Yes

## Additional Information
Equivalent support is already included in the quantization workflow:
https://github.com/NVIDIA/Model-Optimizer/blob/1cc8e6bf3917f61500e81d4ded0af5d5a00e2e25/modelopt/onnx/quantization/calib_utils.py#L50

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

## Summary by CodeRabbit

* **New Features**
* CalibrationDataProvider now accepts both file paths and pre-loaded
ONNX models as input.
* NPZ calibration files can now provide multiple batches for calibration
workflows.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>

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

---------

Signed-off-by: gcunhase <[email protected]>
Signed-off-by: Daniel Korzekwa <[email protected]>
gcunhase added a commit that referenced this pull request Nov 20, 2026
…l of them (#2553)

### What does this PR do?

Type of change: Bug fix

`ReferenceRunner.run()` wraps the model with `MARK_ALL`, so every
intermediate tensor becomes a graph output. It then called
`Comparator.run()`, which executes every calibration sample up front and
retains one full-graph activation dump per sample; those results were
then copied a second time into `all_batch_data` before aggregation. Peak
memory therefore grew linearly with the number of calibration samples —
the OOM reported in #2337.

This uses `Comparator`'s streaming mode and folds each batch into the
running per-tensor statistics as it arrives, so the per-sample
activation retention no longer scales with the number of samples.
Loading the input data itself (a JSON input list, or a single NPZ
holding multiple samples) still materializes every sample's inputs
upfront — this only streams the activation side, which was the actual
source of the reported OOM. `streaming` is available in
`polygraphy>=0.53.4`, which is already the floor in `pyproject.toml`, so
no dependency change is needed.

### Testing

Aggregated `absmax`/`min_val`/`max_val` were compared against an
independent onnxruntime run that does not go through `ReferenceRunner` —
exact match for N=2, 5 and 16. Dumping the full statistics before and
after this change over N=1, 2, 7, 16 gives identical values and
identical key sets, and the single-batch raw-array return is preserved.

Peak RSS on a model with ~14 MiB of activations per sample:

| samples | before | after |
|---|---|---|
| 1 | 8.2 MiB | 8.1 MiB |
| 8 | 128.4 MiB | 24.2 MiB |
| 32 | 448.5 MiB | 32.3 MiB |
| 64 | 897.4 MiB | 23.5 MiB |

`tests/unit/onnx/autocast/test_referencerunner.py` passes (20, including
the new test below).

Two regressions found in review, both fixed and verified:
- A single batch of non-numeric data (e.g. a valid string input feeding
a Cast) crashed trying to numerically reduce it, since the streamed fold
no longer checks the batch count before reducing. Fixed by catching that
failure specifically on the first batch, and added
`test_single_batch_with_string_input_is_not_reduced`, a real end-to-end
ORT run (confirmed it fails with the exact reported `TypeError` against
the pre-fix code).
- `test_multi_batch_does_not_accumulate_batches` spied on two methods
that both run for the first batch, double-counting it and inflating
every concurrency count it asserts on. Fixed to spy on only one.

### Before your PR is "*Ready for review*"

- Is this change backward compatible?: ✅
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A
- Did you write any new necessary tests?: ✅
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
✅
- Did you get Claude approval on this PR?: N/A

### Additional Information

Fixes #2337. The first half of that issue was already fixed by #815;
this addresses the second half, which @hychiang-git confirmed was still
open.

---------

Signed-off-by: Siddhardha Nanda <[email protected]>
Co-authored-by: Gwena Cunha <[email protected]>
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