Skip to content

[3/12] Lower DLA indexing and fixed matrix operators - #3183

Open
mgohil-png wants to merge 1 commit into
dla/onnxscript-02-layout-contextfrom
dla/onnxscript-03-matrix-indexing
Open

mgohil-png wants to merge 1 commit into
dla/onnxscript-02-layout-contextfrom
dla/onnxscript-03-matrix-indexing

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 private INT32 index views and fixed MatMul/Gemm lowering to pointwise Conv with the necessary layout adapters. Shared operands retain their original owners, including per-axis quantized weight chains. The read-only weight eligibility predicate is also used by preprocessing in PR 4.

Usage

Internal rules in operators/rules.py; the fixed pipeline registers them before layout. No public API or transform-selection option is added in this slice.

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. Codecov project status is still pending.

  • Focus: Fixed/runtime index views, shared indices, matrix ranks/orientations, quantized weight axes and non-mutating eligibility refusals.

  • Slice validation: 38 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: 328 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: #3182. 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

Runtime or unsupported matrix weights remain native rather than being treated as fixed constants.

Summary by CodeRabbit

  • New Features
    • Added support for DLA-compatible handling of indexing operations with 64-bit indices.
    • Eligible fixed-weight matrix multiplication and linear operations can now be converted to DLA-compatible convolution operations, including supported quantized weights.
    • Unsupported operations remain unchanged when they do not meet conversion requirements.

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

No actionable comments were generated in the recent review.

Walkthrough

Adds DLA graph rewrites for eligible Gather indices and fixed-weight MatMul and Gemm operations. Adds stage functions that apply both rule batches and remove unused nodes. Tests compare transformed graphs with reference outputs and check cases that remain unchanged.

Changes: DLA operator rewrites

Layer / File(s) Summary
Indexing rewrites
modelopt/onnx/graph_surgery/dla_transforms/operators/*, tests/unit/onnx/graph_surgery/dla_transforms/operators/*
Adds Gather and GatherElements rules that convert eligible indices to private INT32 views. Tests check output types, source-model preservation, and reference outputs.
Matrix lowering
modelopt/onnx/graph_surgery/dla_transforms/operators/rules.py, tests/unit/onnx/graph_surgery/dla_transforms/operators/test_rules.py
Adds eligibility checks and MatMul and Gemm rewrites to Conv for supported fixed weights. Tests cover supported and rejected forms, including quantized weights.
Rule batch integration
modelopt/onnx/graph_surgery/dla_transforms/stages.py
Adds functions to instantiate and apply rule batches, run the indexing and matrix batches, remove unused nodes, and return the rewrite count.

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

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant DlaGraph
  participant individual_op_rewrites
  participant apply_rules
  individual_op_rewrites->>apply_rules: Apply INDEXING_RULES to graph with views={}
  apply_rules->>DlaGraph: Instantiate rules and apply patterns
  individual_op_rewrites->>apply_rules: Apply MATRIX_RULES to graph with views={}
  apply_rules->>DlaGraph: Instantiate rules and apply patterns
  individual_op_rewrites->>DlaGraph: Remove unused nodes and return rewrite count
Loading
Merge Risk: Minimal · up to 7e590

No merge-blocking issue was established in this change; it is ready to merge after normal checks.

Pre-merge checks: Passed 5

Check name Status Explanation
Title check Passed The title clearly and concisely describes the main changes: lowering DLA indexing and fixed matrix operators.
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 PR #3183 (NVIDIA/Model-Optimizer, author mgohil-png) changes five files: three under modelopt/onnx/graph_surgery/dla_transforms (operators/init.py, operators/rules.py, stages.py) and two test file…
Full details: Security Anti-Patterns

Explanation

PR #3183 (NVIDIA/Model-Optimizer, author mgohil-png) changes five files: three under modelopt/onnx/graph_surgery/dla_transforms (operators/init.py, operators/rules.py, stages.py) and two test files. I scanned the full added diff against the six failure conditions in the custom check. - Conditions 1 and 2 (torch.load / numpy.load with weights_only=False or allow_pickle=True): no matches. The only numpy use is import numpy as np. - Condition 3 (trust_remote_code=True): no matches. No transformers loading code was added. - Condition 4 (eval() or exec()): no matches. - Condition 5 (# nosec): zero occurrences in the full diff. - Condition 6 (new pip dependencies): pyproject.toml and requirements files are not touched. No new imports outside the existing onnxscript, numpy and in-package modules. The added imports are limited to onnxscript, numpy, typing, collections.abc and package-relative modules. No subprocess, pickle, yaml or file-loading calls appear in the added lines. No condition is present, so the check passes.

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 c209fe7 and 7e590de.

Files selected for processing: 5

  • modelopt/onnx/graph_surgery/dla_transforms/operators/__init__.py
  • modelopt/onnx/graph_surgery/dla_transforms/operators/rules.py
  • modelopt/onnx/graph_surgery/dla_transforms/stages.py
  • tests/unit/onnx/graph_surgery/dla_transforms/operators/__init__.py
  • 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; 10 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.

@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.00000% with 6 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (dla/onnxscript-02-layout-context@b4ded04). Learn more about missing BASE report.

Files with missing lines Patch % Lines
...delopt/onnx/graph_surgery/dla_transforms/stages.py 45.45% 6 Missing ⚠️
Additional details and impacted files
@@                         Coverage Diff                         @@
##             dla/onnxscript-02-layout-context    #3183   +/-   ##
===================================================================
  Coverage                                    ?   82.17%           
===================================================================
  Files                                       ?      738           
  Lines                                       ?    82483           
  Branches                                    ?        0           
===================================================================
  Hits                                        ?    67781           
  Misses                                      ?    14702           
  Partials                                    ?        0           
Flag Coverage Δ
unit 64.89% <96.00%> (?)

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-03-matrix-indexing branch from 7e590de to 67c172f 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-3183/

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

@mgohil-png
mgohil-png force-pushed the dla/onnxscript-03-matrix-indexing branch from 67c172f to fd7524f 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 force-pushed the dla/onnxscript-03-matrix-indexing branch from fd7524f to e8ee717 Compare November 20, 2026 05:55
if indices not in self.views:
array = constant_array(indices)
self.views[indices] = (
self.graph.add_initializer(op, array.astype(np.int32), "index_int32")

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.

An out-of-bounds INT64 index can wrap back into range here. With data [10, 20], index 4294967296 wraps to 0 and returns 10. This affects both Gather and GatherElements, for constant and runtime indices. Can we preserve the bounds error when narrowing to INT32? Code

return False
if dq is not None:
scale_shape = static_shape(dq.inputs[1])
if dq.attributes.get_int("block_size", 0) or scale_shape is None or len(scale_shape) > 1:

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.

A scalar scale or zero point can be a graph input. That passes the shape check and leaves the generated Conv kernel dependent on a runtime value. Could we require a constant scale and, when present, a constant zero point before lowering this MatMul? Code

return False
channels = raw.shape[-2] if node.attributes.get_int("transB", 0) else raw.shape[-1]
if len(node.inputs) > 2 and node.inputs[2] is not None:
if static_shape(node.inputs[2]) != (channels,):

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.

A runtime bias of shape [2] passes this check for a two-output Gemm. The rewrite then feeds that graph input directly to Conv as its bias. Could we check that the bias is constant before applying this fixed-bias rewrite? Code

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