Skip to content

[1/12] Replace legacy DLA helpers with an IR foundation - #3181

Open
mgohil-png wants to merge 3 commits into
mainfrom
dla/onnxscript-01-core
Open

mgohil-png wants to merge 3 commits into
mainfrom
dla/onnxscript-01-core

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 the internal graph context, typed initializer helpers, input/opset validation and cleanup primitives used by the DLA transforms. Cleanup preserves public names and merges immutable initializers by exact dtype, shape and contents with bounded-memory hashing and collision checks.

Removes the legacy DLA helpers from graph_surgery/utils/graph_utils.py and their corresponding DLA-specific tests. The IR model already records graph connectivity, and the SDK owns node replacement, cleanup and ordering:

  • GraphCache, get_constant_by_name, get_node_attr_i and set_node_attr_i give way to IR initializer/value access, producer()/uses() links and node attributes.
  • batch_replace_nodes and insert_nodes_at_position are replaced by SDK pattern rewriting and IR node APIs, with RemoveUnusedNodesPass and TopologicalSortPass for cleanup and ordering.
  • add_unique_initializers is replaced by the context's shared initializer naming helper and final exact-content deduplication.
  • resolve_reshape_shape, pad4d, axes_for_rank, check_to_apply_transpose, is_const_dq_input, calculate_clip_range and parse_qdq_quantized_dtype_list move to the owning IR layout, operator or preprocessing checks introduced by this series.
  • The legacy graph_utils.infer_shapes wrapper is retired; the final entry point uses upstream inference and ONNX checking.

This retires the obsolete DLA machinery from PR #2831 without reverting that PR's shared initializer/dtype fixes. The IR replaces duplicate graph state and manual DLA graph editing. The shared graph_utils.py module and helpers still used by GQA replacement and encoder cross-KV surgery remain. These removals are separate from the helpers in modelopt.onnx.utils.

Usage

Internal foundation for later slices; the public DLA operation arrives in PR 12. Rules receive one per-run DlaGraph and create constants through its shared initializer helper.

The removed names are exported helper APIs introduced in the current unreleased cycle. Callers using those APIs from main must migrate to the IR-backed DLA workflow delivered by this stack. Existing non-DLA graph-surgery entry points retain their helpers and contracts.

Testing

  • CI readiness check (2026-11-05): latest unit tests, code quality, and documentation workflows passed for this head.

  • Focus: Cleanup, shared/public initializer ownership, exact payload distinctions and hash-collision handling. The existing storage test gains seven cases covering packed INT4/UINT4, odd padding, chunk boundaries, mixed representations and collisions. Remove tests for retired DLA helpers while retaining coverage for the shared utilities that remain.

  • Slice validation: 21 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.

  • Minimum-version compatibility: all 13 cleanup tests passed with onnx_ir==0.1.16.

  • Packed-tensor memory probe (16 MiB packed payload, traced peak temporary memory): 100,800,067 bytes before versus 628,813 bytes after; elapsed time 0.118 s versus 0.245 s. Hashing and collision comparisons use bounded chunks and ignore padding bits.

  • 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: 522 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?: No for direct callers of the removed exported DLA helper APIs. They were added in the current unreleased cycle; callers must migrate as described above. Existing non-DLA graph-surgery contracts are retained.
  • 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?: Yes - documents the retired helper APIs and migration to ONNXScript IR.
  • Did you get Claude approval on this PR?: No - pending external review.

Additional Information

Base: main. Merge this PR first.

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

Layout lifecycle methods arrive with the layout passes in PR 2. The Q/DQ opset-upgrade helper is defined here and activated by the final entry point.

Summary by CodeRabbit

  • New Features
    • Added ONNX graph cleanup that removes eligible redundant reshapes and identities, restores value names, and deduplicates matching initializers.
    • Added model validation for supported ONNX opsets and model structures, plus automatic quantization-operator upgrades when needed.
  • Breaking Changes
    • Removed legacy graph-cache, graph-editing, shape-handling, and quantization helpers. Update direct imports; use ONNXScript IR APIs for graph transformations.
  • Compatibility
    • The ONNX optional dependency now requires ONNXScript 0.7.2 or later.

@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

This change adds ONNX IR-based DLA transforms, including graph context, validation, quantizer opset conversion, cleanup rules, and initializer deduplication. It removes legacy helpers from graph_utils, updates the changelog and ONNXScript requirement, and adds tests.

Changes: DLA graph transforms

Layer / File(s) Summary
Graph context and shared helpers
modelopt/onnx/graph_surgery/dla_transforms/__init__.py, modelopt/onnx/graph_surgery/dla_transforms/common.py, modelopt/onnx/graph_surgery/dla_transforms/context.py, pyproject.toml
Adds helpers for static shapes, constant arrays, and unique initializer names. Adds DlaGraph to expose graph values and apply rewrite rules and in-place passes. Sets onnxscript minimum version to 0.7.2.
Model validation and quantizer opsets
modelopt/onnx/graph_surgery/dla_transforms/validation.py, modelopt/onnx/graph_surgery/dla_transforms/schemas.py, tests/unit/onnx/graph_surgery/dla_transforms/test_validation.py, tests/unit/onnx/graph_surgery/dla_transforms/test_schemas.py
Adds model and quantized-type validation. Adds upgrade_quantizers to convert eligible models with standard-domain quantizer nodes to opset 19. Tests cover supported opsets and conversion behavior.
Cleanup rules and execution
modelopt/onnx/graph_surgery/dla_transforms/cleanup.py, modelopt/onnx/graph_surgery/dla_transforms/stages.py, tests/unit/onnx/graph_surgery/dla_transforms/*
Adds reshape and Identity cleanup rules, value-name restoration, and initializer deduplication. The cleanup stage applies the rules in order, restores names, removes unused nodes, and topologically sorts the graph. Tests cover cleanup behavior and initializer deduplication.
Legacy graph helper removal
modelopt/onnx/graph_surgery/utils/graph_utils.py, tests/unit/onnx/graph_surgery/test_graph_utils.py, CHANGELOG.rst
Removes legacy graph-cache, graph-mutation, shape, and QDQ helpers and their exports. Removes tests for those helpers. The changelog directs callers to ONNXScript IR APIs for new transformations.

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

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant CleanupStage
  participant DlaGraph
  participant ReshapeChain
  participant IdentityReshape
  participant InternalIdentity
  participant RestoreValueNames
  Caller->>CleanupStage: cleanup(graph)
  CleanupStage->>DlaGraph: apply_patterns in rule order
  DlaGraph->>ReshapeChain: apply rewrite rule
  DlaGraph->>IdentityReshape: apply rewrite rule
  DlaGraph->>InternalIdentity: apply rewrite rule
  CleanupStage->>DlaGraph: apply_pass(RestoreValueNames)
Loading

Possibly related PRs

Merge Risk: Minimal · up to 983ce

This change adds internal DLA IR foundations and removes legacy helpers, with tests and a changelog migration note. No concrete merge-blocking risk was identified.

Security architecture risk: Minimal · up to 983ce

The inspected changes establish internal graph-transformation primitives without introducing a new remotely reachable entrypoint or privilege boundary. Explicit guards protect public graph interfaces and prevent unequal initializer contents from being merged. No introduced security or material failure-containment defect was established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The inspected effects are in-process mutations of the supplied graph and reads of its tensor payloads under the invoking process's authority. The specifically routed entrypoints are tests constructing local ONNX models; they do not establish an attacker-accessible service, tenant crossing or privilege increase.

Trust Boundaries and Controls

  • observed — Deduplication excludes graph inputs, graph outputs and values without constant payloads. Candidates must match dtype, shape and digest, followed by full chunk-stream equality before uses are redirected and storage removed. Constant-control queries also exclude graph inputs, avoiding treatment of overridable inputs as fixed constants, subject to the SDK predicate's semantics.

Resilience and Maintainability Implications

  • observed — The primitives operate in place. Rewrite completion resets batch metadata even on exception, but the wrapper supplies no graph snapshot or rollback, and subsequent name-restoration and cleanup passes run only after rewriting returns successfully. This is a bounded internal ownership fact, not evidence of a violated transactional guarantee.
Pre-merge checks: Passed 5

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the primary change: legacy DLA helpers are replaced with an IR-based foundation. The changeset removes legacy helpers from graph_utils.py and adds the DlaGraph context, IR initializer …
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 security anti-pattern check found no listed violation in the PR's added lines. Scope: The reviewed range changes 14 files, including modelopt/onnx/graph_surgery/dla_transforms/*.py (new), graph_ut…
Full details: Title check

Explanation

The title names the primary change: legacy DLA helpers are replaced with an IR-based foundation. The changeset removes legacy helpers from graph_utils.py and adds the DlaGraph context, IR initializer utilities, validation, schemas, and cleanup passes under dla_transforms. The title is specific and matches the main objective. The leading '[1/12]' stack marker is noise but does not make the title misleading.

Full details: Security Anti-Patterns

Explanation

The security anti-pattern check found no listed violation in the PR's added lines. Scope: The reviewed range changes 14 files, including modelopt/onnx/graph_surgery/dla_transforms/*.py (new), graph_utils.py (removals only), tests, CHANGELOG.rst, and pyproject.toml. No examples/ files changed. Pattern scan of all added lines (git diff base..head): 1. torch.load / weights_only=False: no matches. 2. numpy.load / np.load / allow_pickle: no matches. 3. trust_remote_code: no matches. 4. eval( / exec(: no matches. 5. "# nosec": no matches. 6. New dependencies: the only pyproject.toml change is "onnxscript" → "onnxscript>=0.7.2" in the existing onnx extra. onnxscript was already a dependency, so no new PIP dependency was added. The other matches were from onnxscript import ir imports in new code, which are not dependency changes. No requirement triggers an explicit failure condition. Setup-codeowner approval is not needed.

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 26f90ef and 983cee0.

Files selected for processing: 5

  • CHANGELOG.rst
  • modelopt/onnx/graph_surgery/dla_transforms/validation.py
  • pyproject.toml
  • tests/unit/onnx/graph_surgery/dla_transforms/test_schemas.py
  • tests/unit/onnx/graph_surgery/dla_transforms/test_validation.py

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

@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-3181/

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

@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.03828% with 25 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.58%. Comparing base (e9e80a4) to head (983cee0).

Files with missing lines Patch % Lines
...pt/onnx/graph_surgery/dla_transforms/validation.py 50.00% 11 Missing ⚠️
...delopt/onnx/graph_surgery/dla_transforms/common.py 70.37% 8 Missing ⚠️
...elopt/onnx/graph_surgery/dla_transforms/cleanup.py 96.29% 4 Missing ⚠️
...elopt/onnx/graph_surgery/dla_transforms/context.py 93.54% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3181      +/-   ##
==========================================
- Coverage   82.11%   81.58%   -0.54%     
==========================================
  Files         727      734       +7     
  Lines       82173    82138      -35     
==========================================
- Hits        67480    67012     -468     
- Misses      14693    15126     +433     
Flag Coverage Δ
examples-diffusers 19.82% <0.00%> (+0.02%) ⬆️
examples-gpt-oss 13.55% <0.00%> (+0.03%) ⬆️
examples-hf_ptq 24.45% <0.00%> (-0.82%) ⬇️
examples-llm_distill 13.61% <0.00%> (+0.03%) ⬆️
examples-llm_eval 17.47% <0.00%> (+0.03%) ⬆️
examples-llm_qat 17.41% <0.00%> (+0.08%) ⬆️
examples-llm_sparsity 16.83% <0.00%> (+0.03%) ⬆️
examples-megatron_bridge 25.94% <0.00%> (-0.25%) ⬇️
examples-specdec_bench 13.33% <0.00%> (+0.03%) ⬆️
examples-speculative_decoding 17.72% <0.00%> (+0.03%) ⬆️
examples-torch_onnx 20.94% <0.00%> (+<0.01%) ⬆️
examples-torch_trt 15.23% <0.00%> (+0.03%) ⬆️
examples-vllm_serve 17.66% <0.00%> (+0.03%) ⬆️
gpu 59.71% <0.00%> (-3.67%) ⬇️
regression 15.01% <0.00%> (+0.03%) ⬆️
unit 64.76% <88.03%> (+<0.01%) ⬆️

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.

@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

Comment thread CHANGELOG.rst Resolved
@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

Copy link
Copy Markdown
Contributor Author

Closed all the old PRs since we have moved to new method of applying tranformations

@vishalpandya1990

Copy link
Copy Markdown
Contributor

AI Agent Comments:

  1. Small bug: when an internal Identity right after a graph input is removed, onnx_ir copies the removed value's shape onto the input. RestoreValueNames restores the name but not the shape. Repro: input X [1,3,224,224] → Identity (value_info [N,3,224,224]) → Relu; after cleanup() the public input becomes [N,3,224,224]. Could you save and restore source.shape along with the name?
  2. Question: validate() rejects opset 19, but upgrade_quantizers() converts older Q/DQ models to opset 19. Is that intended? If validate runs after the upgrade, upgraded models would be rejected.
  3. Nit: validation.py and schemas.py aren't tested in this PR. Could you add small tests, or move them to the PR that first uses them?

@mgohil-png
mgohil-png force-pushed the dla/onnxscript-01-core branch from 26f90ef to 983cee0 Compare November 20, 2026 05:55
@mgohil-png

Copy link
Copy Markdown
Contributor Author

Addressed points 2 and 3 from your review. PR #3181 now accepts standard opsets 17 through 21 and includes direct tests for input version validation and Q/DQ schema upgrades. The pipeline validates at entry before the optional FP16 upgrade. PR #3192 also exercises models authored directly at opset 19. On the rebased stack, all 33 graph-surgery tests passed for this PR and all 227 passed at the stack tip.

for existing in bucket:
if all(
left == right
for left, right in zip_longest(

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 large transposed weight and its contiguous copy can have identical bytes, but NumPy can split those bytes into different-sized chunks. Comparing chunks in pairs keeps both weights in the model. Could you compare the bytes across chunk boundaries and add a test that checks only one copy remains?

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.

@mgohil-png to address/respond.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pairwise comparison would miss a duplicate if the byte streams were split at different offsets. In this path, _tensor_chunks() uses buffered np.nditer in logical C order, so the transposed view and its contiguous copy produced the same chunk boundaries.

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.

3 participants