-
Notifications
You must be signed in to change notification settings - Fork 72
[IR] Create a shape inference pass using onnx shape inference #2117
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 10 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
5b3de02
[IR] Create a shape inference pass using onnx shape inference
justinchuby f3e2f5f
lint
justinchuby fce00f1
test
justinchuby f04af76
warning
justinchuby b065bfb
strict
justinchuby 7292f25
config
justinchuby 2bad82a
restore
justinchuby 0eb0761
docs
justinchuby 999d9f1
shape
justinchuby fccd8f4
__all__
justinchuby 24087df
Apply suggestions from code review
justinchuby 7385405
Update onnxscript/ir/passes/common/shape_inference.py
justinchuby 9ac3fe9
Address comments
justinchuby 1251e94
Merge branch 'main' into justinchu/shape-inference
justinchuby 2eed545
more tests
justinchuby fce63b3
test
justinchuby d69fb2d
Update modified
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,98 @@ | ||
# Copyright (c) Microsoft Corporation. | ||
# Licensed under the MIT License. | ||
"""Shape inference pass using onnx.shape_inference.""" | ||
|
||
from __future__ import annotations | ||
|
||
__all__ = ["ShapeInferencePass"] | ||
|
||
import logging | ||
|
||
import onnx | ||
|
||
from onnxscript import ir | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class ShapeInferencePass(ir.passes.PassBase): | ||
"""This pass performs shape inference on the graph.""" | ||
|
||
# This pass does not modify the model in place. | ||
in_place = False | ||
|
||
def __init__( | ||
self, check_type: bool = True, strict_mode: bool = True, data_prop: bool = True | ||
) -> None: | ||
"""Initialize the shape inference pass. | ||
|
||
Args: | ||
check_type: If True, check the types of the inputs and outputs. | ||
strict_mode: If True, use strict mode for shape inference. | ||
data_prop: If True, use data propagation for shape inference. | ||
""" | ||
super().__init__() | ||
self.check_type = check_type | ||
self.strict_mode = strict_mode | ||
self.data_prop = data_prop | ||
|
||
def call(self, model: ir.Model) -> ir.passes.PassResult: | ||
# Store the original initializer values so they can be restored | ||
initializer_values = tuple(model.graph.initializers.values()) | ||
tensors = {v.name: v.const_value for v in initializer_values} | ||
original_inputs_len = len(model.graph.inputs) | ||
initializer_names = {v.name for v in initializer_values} | ||
|
||
# Turn the initializers into inputs and clear the initializers | ||
# to limit the model size | ||
for initializer in initializer_values: | ||
# Make sure the initializer has its shape/type set | ||
assert initializer.const_value is not None | ||
if initializer.shape is None: | ||
initializer.shape = initializer.const_value.shape | ||
|
||
if initializer.dtype is None: | ||
initializer.dtype = initializer.const_value.dtype | ||
if initializer not in model.graph.inputs: | ||
model.graph.inputs.append(initializer) | ||
initializer.const_value = None | ||
model.graph.initializers.clear() | ||
|
||
# Perform shape inference | ||
try: | ||
proto = ir.serde.serialize_model(model) | ||
proto = onnx.shape_inference.infer_shapes( | ||
proto, | ||
check_type=self.check_type, | ||
strict_mode=self.strict_mode, | ||
data_prop=self.data_prop, | ||
) | ||
inferred_model = ir.serde.deserialize_model(proto) | ||
except Exception: | ||
|
||
logger.warning("Shape inference failed. The model is not modified", exc_info=True) | ||
return ir.passes.PassResult(model, modified=False) | ||
finally: | ||
# Restore the original initializer values so the model is unchanged | ||
for initializer in initializer_values: | ||
if initializer.name in initializer_names: | ||
initializer.const_value = tensors[initializer.name] | ||
model.graph.register_initializer(initializer) | ||
|
||
# Restore the original inputs | ||
inputs = model.graph.inputs[:original_inputs_len] | ||
model.graph.inputs.clear() | ||
model.graph.inputs.extend(inputs) | ||
|
||
# Add the original initializer tensors to the new (inferred) model | ||
for new_input in inferred_model.graph.inputs: | ||
# Assign the tensors back to the initializers | ||
if new_input.name in initializer_names: | ||
new_input.const_value = tensors[new_input.name] | ||
inferred_model.graph.register_initializer(new_input) | ||
|
||
# Remove the inputs that were added | ||
new_inputs = inferred_model.graph.inputs[:original_inputs_len] | ||
inferred_model.graph.inputs.clear() | ||
inferred_model.graph.inputs.extend(new_inputs) | ||
# Even though modified, we know the pass will not change the model if we ran it again. | ||
justinchuby marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# So set modified to False | ||
return ir.passes.PassResult(inferred_model, modified=False) |
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,48 @@ | ||
# Copyright (c) Microsoft Corporation. | ||
# Licensed under the MIT License. | ||
from __future__ import annotations | ||
|
||
import unittest | ||
|
||
from onnxscript import ir | ||
from onnxscript.ir.passes.common import shape_inference | ||
|
||
|
||
class TestShapeInference(unittest.TestCase): | ||
def test_shape_inference(self): | ||
justinchuby marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# Create a simple ONNX model with shape inference | ||
# Define the model | ||
inputs = [ | ||
ir.Value( | ||
name="input_a", type=ir.TensorType(ir.DataType.FLOAT), shape=ir.Shape((1, 2)) | ||
), | ||
ir.Value( | ||
name="input_b", type=ir.TensorType(ir.DataType.FLOAT), shape=ir.Shape((1, 2)) | ||
), | ||
] | ||
|
||
add_node = ir.Node("", "Add", inputs=inputs) | ||
|
||
model = ir.Model( | ||
ir.Graph( | ||
inputs=inputs, | ||
outputs=add_node.outputs, | ||
nodes=[add_node], | ||
opset_imports={"": 20}, | ||
), | ||
ir_version=10, | ||
) | ||
self.assertIsNone(add_node.outputs[0].shape) | ||
self.assertIsNone(add_node.outputs[0].dtype) | ||
|
||
# Perform shape inference | ||
result = shape_inference.ShapeInferencePass()(model) | ||
gramalingam marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.assertFalse(result.modified) | ||
self.assertEqual(result.model.graph.node(0).outputs[0].shape, ir.Shape((1, 2))) | ||
self.assertEqual(result.model.graph.node(0).outputs[0].dtype, ir.DataType.FLOAT) | ||
self.assertEqual(result.model.graph.outputs[0].shape, ir.Shape((1, 2))) | ||
self.assertEqual(result.model.graph.outputs[0].dtype, ir.DataType.FLOAT) | ||
|
||
|
||
if __name__ == "__main__": | ||
unittest.main() |
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.