Skip to content

[9/12] Add DLA logical rewrites and float consumer views - #3189

Open
mgohil-png wants to merge 1 commit into
dla/onnxscript-08-lstmfrom
dla/onnxscript-09-logical-views
Open

mgohil-png wants to merge 1 commit into
dla/onnxscript-08-lstmfrom
dla/onnxscript-09-logical-views

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 finite zero-branch Where lowering, supported binary Not lowering and private FLOAT views for eligible Greater comparisons. A direct pass gives schema-required FLOAT consumers reusable views of native integer data while retaining other integer/control users.

Usage

Internal logical batch and float-consumer pass after layout. Per-operand conversion and shared ownership checks determine eligibility.

Testing

  • Pre-fix CI readiness check (2026-11-05; head 8e6a940c6b): unit tests, code quality, and documentation workflows passed for that head. These results predate the singleton fix; updated-head CI results are pending. Aggregate checks still include cancelled duplicate runs.

  • Focus: Shared masks/casts, native/refused forms, public boolean endpoints, integer comparison boundaries and mixed intermediate dtype normalization.

  • Slice validation: 124 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: 259 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: #3188. 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

Where lowering assumes finite FP32 data and may change signed zero. NaN/Inf equivalence is outside this arithmetic lowering contract.

Summary by CodeRabbit

  • New Features
    • Added ONNX graph transformations for eligible Where, Not, and Greater operations, using arithmetic-based alternatives in supported cases while preserving native behavior for unsupported cases.
    • Added FLOAT views for selected consumers of integer Unsqueeze outputs, while retaining integer outputs for other consumers.

@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

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change adds three logical ONNX rewrites and a schema-guided pass that inserts shared FLOAT casts for selected consumers of integer Unsqueeze outputs. The rewrite stage applies the pass after the logical rules.

Changes: ONNX operator rewrites

Layer / File(s) Summary
Logical operator rewrites
modelopt/onnx/graph_surgery/dla_transforms/operators/rules.py, tests/unit/onnx/graph_surgery/dla_transforms/operators/test_rules.py
Adds and registers WhereZero, LogicalNot, and GreaterFloat. Tests check their rewrite conditions and compare transformed outputs with reference execution.
Schema-guided float consumer views
modelopt/onnx/graph_surgery/dla_transforms/operators/passes.py, modelopt/onnx/graph_surgery/dla_transforms/operators/__init__.py, modelopt/onnx/graph_surgery/dla_transforms/stages.py, tests/unit/onnx/graph_surgery/dla_transforms/operators/test_passes.py
Adds and exports FloatConsumerViews, then applies it after logical rewrites. Tests check cast insertion, integer-use preservation, and handling of unknown operator schemas.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant individual_op_rewrites
  participant LOGICAL_RULES
  participant FloatConsumerViews
  individual_op_rewrites->>LOGICAL_RULES: Apply registered logical rewrites
  individual_op_rewrites->>FloatConsumerViews: Apply schema-guided consumer pass
Loading

Suggested reviewers: cjluo-nv

Merge Risk: Low · up to 8e6a9

Affected models may fail validation or execution. This narrow case warrants owner awareness.

Pre-merge checks: Passed 5

Check name Status Explanation
Title check Passed The title "[9/12] Add DLA logical rewrites and float consumer views" matches the main changes. The PR adds logical rewrites (WhereZero, LogicalNot, GreaterFloat, registered in LOGICAL_RULES) and the F…
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 "Security anti-patterns" check finds no explicit failure condition in PR #3189 (NVIDIA/Model-Optimizer, head dla/onnxscript-09-logical-views, author mgohil-png). Evidence from the reviewed range (…
Full details: Title check

Explanation

The title "[9/12] Add DLA logical rewrites and float consumer views" matches the main changes. The PR adds logical rewrites (WhereZero, LogicalNot, GreaterFloat, registered in LOGICAL_RULES) and the FloatConsumerViews pass that inserts shared FLOAT Cast nodes for promoted Unsqueeze outputs. The "[9/12]" prefix is a stack-position marker and does not describe the change itself, but the rest of the title is specific and accurate.

Full details: Security Anti-Patterns

Explanation

The "Security anti-patterns" check finds no explicit failure condition in PR #3189 (NVIDIA/Model-Optimizer, head dla/onnxscript-09-logical-views, author mgohil-png). Evidence from the reviewed range (refs/coderabbit/pre-merge-check/base..head): - Changed files: 6 (4 modified or added under modelopt/onnx/graph_surgery/dla_transforms/, 2 test files under tests/unit/onnx/graph_surgery/dla_transforms/). Total 515 insertions, 1 deletion. - Criteria 1 and 2 (torch.load / numpy.load with weights_only=False or allow_pickle=True): no added line matches torch.load, numpy.load, np.load, allow_pickle, or weights_only. - Criterion 3 (trust_remote_code=True): no match in added lines. - Criterion 4 (eval() or exec()): no match for eval(, exec(, or import. A broader scan for pickle, subprocess, shell=, and yaml.load also found nothing. - Criterion 5 (# nosec): no match in added lines. - Criterion 6 (new pip dependencies): no pyproject.toml, requirements*.txt, setup.py, or setup.cfg file is in the changed-file list. The new code (FloatConsumerViews in passes.py, plus WhereZero, LogicalNot, and GreaterFloat in rules.py) uses onnx.defs.get_schema and onnxscript IR APIs only. It does not load files, deserialize untrusted data, or execute dynamic code. Scope note: the check covers only the six listed criteria. It does not cover the broader SECURITY.md guidance, which I did not assess in full.

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 f04824d and 8e6a940.

Files selected for processing: 1

  • tests/unit/onnx/graph_surgery/dla_transforms/operators/test_rules.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 1 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.

@mgohil-png
mgohil-png force-pushed the dla/onnxscript-09-logical-views branch from f04824d to 235d183 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-3189/

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

@mgohil-png
mgohil-png force-pushed the dla/onnxscript-09-logical-views branch from 235d183 to 15b0bb3 Compare November 3, 2026 14:15
@mgohil-png
mgohil-png force-pushed the dla/onnxscript-09-logical-views branch 2 times, most recently from 70453d5 to 8e6a940 Compare November 3, 2026 19:47
@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.03175% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.40%. Comparing base (18bab48) to head (3d16e9a).

Files with missing lines Patch % Lines
...delopt/onnx/graph_surgery/dla_transforms/stages.py 20.00% 4 Missing ⚠️
...x/graph_surgery/dla_transforms/operators/passes.py 97.29% 1 Missing ⚠️
Additional details and impacted files
@@                    Coverage Diff                     @@
##           dla/onnxscript-08-lstm    #3189      +/-   ##
==========================================================
+ Coverage                   82.37%   82.40%   +0.02%     
==========================================================
  Files                         742      743       +1     
  Lines                       83407    83532     +125     
==========================================================
+ Hits                        68710    68831     +121     
- Misses                      14697    14701       +4     
Flag Coverage Δ
unit 65.34% <96.03%> (+0.04%) ⬆️

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 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 force-pushed the dla/onnxscript-09-logical-views branch from 8e6a940 to 83824fa Compare November 5, 2026 11:10
@mgohil-png
mgohil-png force-pushed the dla/onnxscript-09-logical-views branch from 83824fa to 3d16e9a Compare November 20, 2026 05:55
if formal == "tensor(float)" or (
"tensor(float)" in constraints.get(formal, [])
and binding
and all(d == ir.DataType.FLOAT for d in binding)

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.

When two Unsqueeze inputs to a Sum both need a FLOAT cast, each one gets skipped because the other is still INT64. That leaves the Sum with mixed types and it fails ONNX type checking. Could we collect the inputs that need casts before deciding which ones to convert?

if np.broadcast_shapes(*shapes) != np.broadcast_shapes(
shapes[0], shapes[2 - index]
):
return False

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.

When both Where branches are zero, failing the shape check for the first branch ends the search. Dropping the other branch can still preserve the output shape. Could we continue here so the rule tries that branch too?

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