-
Notifications
You must be signed in to change notification settings - Fork 71
[Pass] Graph extractor pass #2119
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
Draft
justinchuby
wants to merge
18
commits into
main
Choose a base branch
from
justinchu/graph-extractor-2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 2 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
28beefd
Graph extractor
justinchuby b4ab30f
rename
justinchuby 30fb4c4
Fix inputs
justinchuby 7455c2e
change signature
justinchuby 78aefc2
warning
justinchuby ca03ed9
print
justinchuby 716413f
Apply suggestions from code review
justinchuby 307c62c
keep initializers
justinchuby b0d1843
sort graph
justinchuby 4479afd
lint
justinchuby c8b391d
Merge branch 'main' into justinchu/graph-extractor-2
justinchuby 18d70b1
Update pass to be inplace
justinchuby 3fcbbbb
Merge branch 'main' into justinchu/graph-extractor-2
justinchuby c99bab7
Merge branch 'main' into justinchu/graph-extractor-2
justinchuby 157d601
Merge branch 'main' into justinchu/graph-extractor-2
justinchuby 0fd082f
Add tests for ExtractGraphPass in `graph_extration_test.py`
justinchuby 35c45cf
2e5191a
Merge branch 'main' into justinchu/graph-extractor-2
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
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,136 @@ | ||
# Copyright (c) Microsoft Corporation. | ||
|
||
# Licensed under the MIT License. | ||
"""Passes for extracting subgraphs from a graph.""" | ||
|
||
from __future__ import annotations | ||
|
||
import itertools | ||
|
||
__all__ = [ | ||
"ExtractGraphPass", | ||
] | ||
|
||
import logging | ||
from collections.abc import Collection | ||
|
||
from onnxscript import ir | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
|
||
def _find_subgraph_bounded_by_values( | ||
graph: ir.Graph, inputs: Collection[ir.Value], outputs: Collection[ir.Value] | ||
) -> tuple[list[ir.Node], list[ir.Value]]: | ||
"""Finds the subgraph bounded by the given inputs and outputs. | ||
|
||
Args: | ||
graph: The graph to search. | ||
inputs: The inputs to the subgraph. | ||
outputs: The outputs of the subgraph. | ||
|
||
Returns: | ||
A list of nodes in the subgraph and the initializers used. | ||
""" | ||
all_nodes = [] | ||
value_stack: list[ir.Value] = [*outputs] | ||
visited_nodes: set[ir.Node] = set() | ||
visited_values: set[ir.Value] = set() | ||
initializers = [] | ||
while value_stack: | ||
value = value_stack.pop() | ||
if value in visited_values: | ||
continue | ||
if value.name in graph.initializers: | ||
# Record the initializer | ||
assert value.const_value is not None | ||
initializers.append(value) | ||
visited_values.add(value) | ||
if (node := value.producer()) is not None: | ||
if node not in visited_nodes: | ||
visited_nodes.add(node) | ||
all_nodes.append(node) | ||
for input in node.inputs: | ||
if input not in visited_values and input is not None: | ||
value_stack.append(input) | ||
return all_nodes, initializers | ||
|
||
|
||
class ExtractGraphPass(ir.passes.PassBase): | ||
"""This pass performs shape inference on the graph.""" | ||
|
||
justinchuby marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# This pass does not modify the model in place | ||
in_place = False | ||
# This pass destroys the input model | ||
destructive = True | ||
|
||
def __init__(self, *, input_names: Collection[str], output_names: Collection[str]) -> None: | ||
"""Extracts sub-model from an ONNX model. | ||
|
||
The sub-model is defined by the names of the input and output tensors *exactly*. | ||
|
||
Args: | ||
input_names: The names of the inputs to extract. | ||
output_names: The names of the outputs to extract. | ||
""" | ||
super().__init__() | ||
self.input_names = input_names | ||
self.output_names = output_names | ||
|
||
def requires(self, model: ir.Model) -> None: | ||
# All inputs and outputs can be found in the model | ||
values = ir.convenience.create_value_mapping(model.graph) | ||
input_names_not_found = sorted(set(self.input_names) - set(values.keys())) | ||
if input_names_not_found: | ||
raise ir.passes.PreconditionError( | ||
f"Input names not found in the model: {input_names_not_found}" | ||
) | ||
output_names_not_found = sorted(set(self.output_names) - set(values.keys())) | ||
if output_names_not_found: | ||
raise ir.passes.PreconditionError( | ||
f"Output names not found in the model: {output_names_not_found}" | ||
) | ||
|
||
# All inputs and outputs must have type and shape | ||
for name in itertools.chain(self.input_names, self.output_names): | ||
value = values[name] | ||
if value.type is None: | ||
raise ir.passes.PreconditionError( | ||
f"Value {name} does not have a type: {value}. " | ||
"Consider setting its type or running shape inference first." | ||
) | ||
if value.shape is None: | ||
raise ir.passes.PreconditionError( | ||
f"Value {name} does not have a shape: {value}. " | ||
"Consider setting its shape or running shape inference first." | ||
) | ||
|
||
def call(self, model: ir.Model) -> ir.passes.PassResult: | ||
values = ir.convenience.create_value_mapping(model.graph) | ||
inputs = [values[name] for name in self.input_names] | ||
outputs = [values[name] for name in self.output_names] | ||
extracted_nodes, initializers = _find_subgraph_bounded_by_values( | ||
model.graph, inputs, outputs | ||
) | ||
# Create a graph with the extracted nodes | ||
model.graph.remove(extracted_nodes) | ||
new_model = ir.Model( | ||
ir.Graph( | ||
inputs, | ||
outputs, | ||
nodes=extracted_nodes, | ||
initializers=initializers, | ||
doc_string=model.graph.doc_string, | ||
opset_imports=model.graph.opset_imports, | ||
name=model.graph.name, | ||
metadata_props=model.graph.metadata_props, | ||
), | ||
ir_version=model.ir_version, | ||
producer_name=model.producer_name, | ||
producer_version=model.producer_version, | ||
domain=model.domain, | ||
model_version=model.model_version, | ||
doc_string=model.doc_string, | ||
functions=tuple(model.functions.values()), | ||
meta_data_props=model.metadata_props, | ||
) | ||
return ir.passes.PassResult(new_model, modified=True) |
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.