Skip to content

[4/12] Add DLA quantization and FP32 preprocessing - #3184

Open
mgohil-png wants to merge 1 commit into
dla/onnxscript-03-matrix-indexingfrom
dla/onnxscript-04-preprocessing
Open

mgohil-png wants to merge 1 commit into
dla/onnxscript-03-matrix-indexingfrom
dla/onnxscript-04-preprocessing

Conversation

@mgohil-png

@mgohil-png mgohil-png commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: new feature

Adds selected Q/DQ bypass, Constant materialization, connected FP32-region preparation and eligible static dequantization folding. Standard and Microsoft Q/DQ share the same policies; matrix weight eligibility from PR 3 prevents folding weight chains needed by later lowering.

Usage

Internal preprocessing stage. Default Q/DQ bypass targets INT16/UINT16 storage; the final public operation exposes explicit dtype selection or removal of all Q/DQ.

Testing

  • CI readiness check (2026-11-05): latest unit tests, code quality, and documentation workflows passed for this head. Aggregate checks still include cancelled duplicate runs.

  • Focus: Q/DQ domains and endpoint dtypes, constants, connected Cast analysis, native/control-flow constraints, optional inputs and shared static DQ expressions.

  • Slice validation: 53 tests passed on this slice using python -m pytest tests/unit/onnx/graph_surgery/dla_transforms tests/unit/onnx/graph_surgery/test_graph_utils.py -o addopts= -q -p no:cacheprovider --strict-markers.

  • Repository checks: Ruff, formatting, license, security, whitespace and applicable repository hooks passed. Mypy reports the preexisting Windows os.sched_getaffinity error; it was excluded from commit hooks after confirming the same unrelated error.

  • Added source lines against this PR's base: 448 added Python source lines; tests and documentation excluded.

Before your PR is "Ready for review"

Follow the Contributor guidelines and Security Coding Practices. Commits are signed and signed off.

  • Is this change backward compatible?: Yes - additive internal/public functionality; existing graph-surgery entry points retain their contracts.
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md?: N/A - uses existing dependencies; no external source copied.
  • Did you write any new necessary tests?: Yes - see Testing; graph behavior and relevant ownership contracts are exercised.
  • Did you update Changelog?: N/A - internal enabling slice; the public feature is documented in the final integration PR.
  • Did you get Claude approval on this PR?: No - pending external review.

Additional Information

Base: #3183. Merge after that PR; this slice builds on the preceding stack changes.

Merge order is 1 through 12. Review against the immediate base so earlier slices are excluded from this diff. Series: 1/12, 2/12, 3/12, 4/12, 5/12, 6/12, 7/12, 8/12, 9/12, 10/12, 11/12, 12/12

Q/DQ bypass intentionally removes rounding/clipping, and eligible integer-to-FLOAT Cast promotion changes truncation semantics. These are preparation policies rather than exact graph simplifications.

Summary by CodeRabbit

  • New Features
    • Added DLA model preprocessing that can simplify eligible quantize/dequantize paths, convert constants into initializers, promote compatible values to FP32, and fold supported static dequantization.
    • Preprocessing supports standard and Microsoft quantization operators, while preserving graph outputs and quantizer uses that should remain.
    • These transformations help prepare supported ONNX models for downstream DLA processing.

@copy-pr-bot

copy-pr-bot Bot commented Nov 3, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Walkthrough

The change adds DLA preprocessing rules for QDQ, Constant, Cast, and static dequantization transformations. A new stage applies these rules in the default and Microsoft domains. Unit tests check transformed models and compare model outputs.

Changes: DLA preprocessing

Layer / File(s) Summary
QDQ and Constant rewrites
modelopt/onnx/graph_surgery/dla_transforms/preprocessing/rules.py, tests/unit/onnx/graph_surgery/dla_transforms/test_preprocessing.py
Adds selected QDQ bypass and converts supported Constant attributes to initializers. Tests check selected storage types, output handling, and output equivalence.
FP32 Cast analysis and promotion
modelopt/onnx/graph_surgery/dla_transforms/preprocessing/passes.py, modelopt/onnx/graph_surgery/dla_transforms/preprocessing/rules.py, tests/unit/onnx/graph_surgery/dla_transforms/test_preprocessing.py
Analyzes eligible Cast values without modifying the graph, rewrites approved Cast nodes, and promotes analyzed values to FLOAT. Tests cover supported and blocked cases.
Static dequantization folding
modelopt/onnx/graph_surgery/dla_transforms/preprocessing/rules.py, tests/unit/onnx/graph_surgery/dla_transforms/test_preprocessing.py
Adds validation and folding for supported static DequantizeLinear nodes. Tests cover scalar and per-axis values, shared values, and INT32 data.
Preprocessing stage wiring
modelopt/onnx/graph_surgery/dla_transforms/preprocessing/__init__.py, modelopt/onnx/graph_surgery/dla_transforms/stages.py, tests/unit/onnx/graph_surgery/dla_transforms/test_preprocessing.py
Exports the rules and passes and adds a stage that applies them in both domains. Test helpers run the stage and validate its output.

Estimated code review effort: 4 (Complex) | ~40 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Preprocessing
  participant SelectedQdq
  participant ConstantInitializer
  participant AnalyzeFp32Casts
  participant Fp32Cast
  participant PromoteFp32Values
  participant StaticDequantization
  Preprocessing->>SelectedQdq: Apply selected QDQ rules in both domains
  Preprocessing->>ConstantInitializer: Convert supported Constant attributes
  Preprocessing->>AnalyzeFp32Casts: Analyze eligible Cast values
  Preprocessing->>Fp32Cast: Rewrite candidate Cast nodes
  Preprocessing->>PromoteFp32Values: Set analyzed value types to FLOAT
  Preprocessing->>StaticDequantization: Fold supported static DequantizeLinear nodes in both domains
Loading

Suggested labels: waiting for feedback

Suggested reviewers: vishalpandya1990, hthadicherla, cjluo-nv

Merge Risk: Moderate · up to 9da08

Some control-flow and attribute-typed models may become type-inconsistent during preprocessing. Resolve both promotion issues before merging.

Pre-merge checks: Passed 5

Check name Status Explanation
Title check Passed The title clearly and concisely describes the main changes: DLA quantization preprocessing and FP32 preprocessing.
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.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Security Anti-Patterns Passed The PR (NVIDIA/Model-Optimizer #3184, author mgohil-png) changes five files: four under modelopt/onnx/graph_surgery/dla_transforms (preprocessing/init.py, passes.py, rules.py, stages.py) and one u…
Full details: Security Anti-Patterns

Explanation

The PR (NVIDIA/Model-Optimizer #3184, author mgohil-png) changes five files: four under modelopt/onnx/graph_surgery/dla_transforms (preprocessing/init.py, passes.py, rules.py, stages.py) and one unit test file. I checked every added line in the reviewed diff against the six security criteria. 1. torch.load(..., weights_only=False): no match in added lines. 2. numpy.load(..., allow_pickle=True): no match. The added code imports numpy but does not call np.load. 3. trust_remote_code=True: no match. The change does not load transformers models or tokenizers. 4. eval() or exec() on external input: no match. The only text hit was the word "execution" in a test docstring. No eval or exec call was added. 5. # nosec comments: no match. 6. New pip dependencies: no change to pyproject.toml, requirements*.txt, setup.py, or setup.cfg. The added imports (numpy, onnx, onnxscript) are existing dependencies, as the PR description states. No added line matches a failure condition, so the check passes. The two CodeRabbit comments on passes.py concern graph-semantics correctness (outer-scope captures and attribute-typed outputs). They are not security anti-patterns under this check, and I did not grade them.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • 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 7e590de and 9da08aa.

Files selected for processing: 5

  • modelopt/onnx/graph_surgery/dla_transforms/preprocessing/__init__.py
  • modelopt/onnx/graph_surgery/dla_transforms/preprocessing/passes.py
  • modelopt/onnx/graph_surgery/dla_transforms/preprocessing/rules.py
  • modelopt/onnx/graph_surgery/dla_transforms/stages.py
  • tests/unit/onnx/graph_surgery/dla_transforms/test_preprocessing.py

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

@mgohil-png

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor
Action performed

Full review finished.

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

  • Fix comments: Fix CodeRabbit comments on this PR

@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.50739% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 82.21%. Comparing base (e8ee717) to head (e17fd78).

Files with missing lines Patch % Lines
...raph_surgery/dla_transforms/preprocessing/rules.py 99.15% 1 Missing ⚠️
Additional details and impacted files
@@                          Coverage Diff                          @@
##           dla/onnxscript-03-matrix-indexing    #3184      +/-   ##
=====================================================================
+ Coverage                              82.17%   82.21%   +0.04%     
=====================================================================
  Files                                    738      741       +3     
  Lines                                  82483    82686     +203     
=====================================================================
+ Hits                                   67781    67984     +203     
  Misses                                 14702    14702              
Flag Coverage Δ
unit 64.97% <99.50%> (+0.08%) ⬆️

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.

@mgohil-png
mgohil-png force-pushed the dla/onnxscript-04-preprocessing branch from 9da08aa to cb101bd Compare November 3, 2026 13:56
@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.2

QR code for preview link

🚀 View preview at
https://NVIDIA.github.io/Model-Optimizer/pr-preview/pr-3184/

Built to branch gh-pages at 2026-11-20 06:02 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@mgohil-png
mgohil-png force-pushed the dla/onnxscript-04-preprocessing branch from cb101bd to 7f71f33 Compare November 3, 2026 14:15
@mgohil-png
mgohil-png marked this pull request as ready for review November 5, 2026 05:56
@mgohil-png
mgohil-png requested review from a team as code owners November 5, 2026 05:56
@mgohil-png
mgohil-png requested a review from ajrasane November 5, 2026 05:56
@mgohil-png
mgohil-png force-pushed the dla/onnxscript-04-preprocessing branch from 7f71f33 to e17fd78 Compare November 20, 2026 05:55
continue
parameter = formal[min(index, len(formal) - 1)]
groups[parameter.type_str].append(value)
if "tensor(float)" not in allowed.get(parameter.type_str, [parameter.type_str]):

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.

P1 — An operator attribute can fix its output dtype even when the schema allows FLOAT. Changing the value metadata leaves the operator producing the old dtype, so its consumer can fail type checking. Please skip promotion when the producing attribute fixes the type.

for value in (*graph.inputs, *graph.initializers.values())
if value.dtype != ir.DataType.FLOAT
}
for node in graph:

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.

P1 — A nested graph can use an outer value without listing it as an input to the parent node. Promoting that value can break a branch that needs an integer. Please check captured uses before changing the Cast.

graph.apply_pass(_cleanup.RestoreValueNames(names))
graph.apply_pass(ir.passes.common.RemoveUnusedNodesPass())
count += graph.apply_pattern(preprocessing_rules.ConstantInitializer.rule(graph))
analysis = preprocessing_passes.AnalyzeFp32Casts()

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.

P1 — Q/DQ removal can insert a Cast to preserve the graph output dtype. This pass promotes that Cast too, which changes the public output type. Please keep the output-preserving Cast out of promotion.

shape[axis] = -1
factors, zeros = factors.reshape(shape), zeros.reshape(shape)
else:
factors, zeros = factors.reshape(()), zeros.reshape(())

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.

P2 — An empty per-axis scale reaches the scalar reshape here and makes preprocessing fail on a valid model. Please keep the per-axis broadcast shape when the axis is empty.

blocked.add(value)
for group in groups.values():
for value in group:
adjacent[value].update(group)

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.

P2 — Storing every pair in the type group makes memory use grow quadratically with the input count. Connecting each value to one representative would keep the group reachable with linear storage.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants