-
Notifications
You must be signed in to change notification settings - Fork 17
Add OutputFixPass to fix invalid graph outputs #269
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
caf1539
Initial plan
Copilot 622ae7d
Add IdentityFixPass to fix invalid graphs with direct input-output co…
Copilot e848c91
Fix linting issues in identity_fix pass
Copilot cec1a44
Address code review feedback - simplify metadata_props update
Copilot 9a38e88
Merge branch 'main' into copilot/add-identity-node-pass
justinchuby 371c1dc
Update
justinchuby d247885
lint
justinchuby 4c90386
Tests
justinchuby c4b8c79
Update src/onnx_ir/passes/common/output_fix_test.py
justinchuby ed5baf7
Update src/onnx_ir/passes/common/output_fix.py
justinchuby 74c56ff
Update src/onnx_ir/passes/common/output_fix.py
justinchuby 5576b95
Update
justinchuby da8c261
docs
justinchuby fe5a574
Apply suggestion from @justinchuby
justinchuby bc9e650
docs
justinchuby 791cdec
lint
justinchuby 9e6ab23
Update
justinchuby b73f540
Merge branch 'main' into copilot/add-identity-node-pass
justinchuby File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| # Copyright (c) ONNX Project Contributors | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| """Output fix pass for adding Identity nodes. | ||
|
|
||
| - Graph inputs are directly used as outputs (without any intermediate nodes). | ||
| - A value is used multiple times as a graph output (ensuring each output is unique). | ||
|
|
||
| This ensures compliance with the ONNX specification for valid output configurations. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| __all__ = [ | ||
| "OutputFixPass", | ||
| ] | ||
|
|
||
| import logging | ||
|
|
||
| import onnx_ir as ir | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class OutputFixPass(ir.passes.InPlacePass): | ||
| """Pass for adding Identity nodes to fix invalid output configurations. | ||
|
|
||
| This pass adds Identity nodes according to the following rules: | ||
|
|
||
| - If a graph input is directly used as a graph output (without any intermediate nodes), | ||
| insert an Identity node between them. The ONNX specification does not allow a graph | ||
| input to be directly used as a graph output without any processing nodes in between. | ||
| - If a value is used multiple times as graph outputs, insert Identity nodes for each | ||
| duplicate usage (keeping the first usage unchanged). This ensures each output value | ||
| is unique, as required by the ONNX specification. | ||
|
|
||
| This pass processes both the main graph and all subgraphs (e.g., in control flow operators). | ||
|
|
||
| Example transformations: | ||
| Direct input-to-output: | ||
| Before: input -> (direct connection) -> output | ||
| After: input -> Identity -> output | ||
|
|
||
| Duplicate outputs: | ||
| Before: value -> [output1, output2] | ||
| After: value -> output1, value -> Identity -> output2 | ||
| """ | ||
|
|
||
| def call(self, model: ir.Model) -> ir.passes.PassResult: | ||
| """Main entry point for the output fix pass.""" | ||
| modified = False | ||
|
|
||
| # Process the main graph | ||
| if _alias_multi_used_outputs(model.graph): | ||
| modified = True | ||
| if _alias_direct_outputs(model.graph): | ||
| modified = True | ||
|
|
||
| # Process functions | ||
| for function in model.functions.values(): | ||
| if _alias_multi_used_outputs(function): | ||
| modified = True | ||
| if _alias_direct_outputs(function): | ||
| modified = True | ||
|
|
||
| return ir.passes.PassResult(model, modified=modified) | ||
|
|
||
|
|
||
| def _alias_multi_used_outputs(graph_like: ir.Graph | ir.Function) -> bool: | ||
| """Insert Identity nodes for values that appear in the graph output list multiple times.""" | ||
| modified = False | ||
|
|
||
| for graph in (graph_like, *graph_like.subgraphs()): | ||
| # Count usage of each output | ||
| seen: set[ir.Value] = set() | ||
|
|
||
| # Add Identity nodes for outputs used multiple times | ||
| for i, output in enumerate(graph.outputs): | ||
| if output not in seen: | ||
| # Skip the first occurrence | ||
| seen.add(output) | ||
| continue | ||
|
|
||
| # Create an Identity node | ||
| identity_node = ir.node("Identity", inputs=[output]) | ||
| identity_output = identity_node.outputs[0] | ||
|
|
||
| # Copy metadata from the original output | ||
| # TODO: Use a better unique naming strategy if needed | ||
| identity_output.name = f"{output.name}_alias_{i}" | ||
| identity_output.shape = output.shape | ||
| identity_output.type = output.type | ||
| identity_output.metadata_props.update(output.metadata_props) | ||
| identity_output.doc_string = output.doc_string | ||
|
|
||
| # Add the node to the graph | ||
| graph.append(identity_node) | ||
| graph.outputs[i] = identity_output | ||
| logger.debug( | ||
| "Added Identity node for graph output '%s' used multiple times", output | ||
| ) | ||
| modified = True | ||
| return modified | ||
|
|
||
|
|
||
| def _alias_direct_outputs(graph_like: ir.Graph | ir.Function) -> bool: | ||
| """Insert Identity nodes for graph inputs used directly as outputs.""" | ||
| modified = False | ||
|
|
||
| for graph in (graph_like, *graph_like.subgraphs()): | ||
| # Check each output to see if it's directly a graph input | ||
| outputs_to_fix: list[tuple[ir.Value, int]] = [] | ||
| for i, output in enumerate(graph.outputs): | ||
| if output.is_graph_input(): | ||
| outputs_to_fix.append((output, i)) | ||
|
|
||
| # Add Identity nodes for each output that needs fixing | ||
| for output, index in outputs_to_fix: | ||
| # Create an Identity node | ||
| identity_node = ir.node("Identity", inputs=[output]) | ||
| identity_output = identity_node.outputs[0] | ||
|
|
||
| # Copy metadata from the original output | ||
| # Preserve the original output name | ||
| identity_output.name = output.name | ||
| identity_output.shape = output.shape | ||
| identity_output.type = output.type | ||
| identity_output.metadata_props.update(output.metadata_props) | ||
| identity_output.doc_string = output.doc_string | ||
|
|
||
| # Create a new name for the old output | ||
| # TODO: Use a better unique naming strategy if needed | ||
| output.name = f"{output.name}_orig" | ||
justinchuby marked this conversation as resolved.
Show resolved
Hide resolved
justinchuby marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # Add the node to the graph | ||
| graph.append(identity_node) | ||
| graph.outputs[index] = identity_output | ||
|
|
||
| logger.debug("Added Identity node for graph input '%s' used as output", output) | ||
| modified = True | ||
|
|
||
| return modified | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.