-
Notifications
You must be signed in to change notification settings - Fork 9
[Pass] Support CSE constant nodes #92
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
titaiwangms
merged 7 commits into
onnx:main
from
titaiwangms:titaiwang/support_constant_cse
Jun 19, 2025
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
bf29cca
add test and size_limit
titaiwangms 2c04618
other test cases updated
titaiwangms 606af7e
Update src/onnx_ir/passes/common/common_subexpression_elimination.py
titaiwangms 7f853a8
adjust the test
titaiwangms 741f3f5
Update src/onnx_ir/passes/common/common_subexpression_elimination.py
titaiwangms 6cddfea
moved modified into the function
titaiwangms 66112cb
address review
titaiwangms 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
Original file line number | Diff line number | Diff line change | ||
---|---|---|---|---|
|
@@ -17,93 +17,117 @@ | |||
|
||||
|
||||
class CommonSubexpressionEliminationPass(ir.passes.InPlacePass): | ||||
"""Eliminate common subexpression in ONNX graphs.""" | ||||
"""Eliminate common subexpression in ONNX graphs. | ||||
|
||||
Attributes: | ||||
size_limit: The maximum size of the tensor to be csed. If the tensor contains | ||||
number of elements larger than size_limit, it will not be cse'd. Default is 10. | ||||
|
||||
""" | ||||
|
||||
def __init__(self, size_limit: int = 10): | ||||
"""Initialize the CommonSubexpressionEliminationPass.""" | ||||
super().__init__() | ||||
self.size_limit = size_limit | ||||
|
||||
def call(self, model: ir.Model) -> ir.passes.PassResult: | ||||
"""Return the same ir.Model but with CSE applied to the graph.""" | ||||
modified = False | ||||
graph = model.graph | ||||
|
||||
modified = _eliminate_common_subexpression(graph, modified) | ||||
modified = self._eliminate_common_subexpression(graph) | ||||
|
||||
return ir.passes.PassResult( | ||||
model, | ||||
modified=modified, | ||||
) | ||||
|
||||
|
||||
def _eliminate_common_subexpression(graph: ir.Graph, modified: bool) -> bool: | ||||
"""Eliminate common subexpression in ONNX graphs.""" | ||||
# node to node identifier, length of outputs, inputs, and attributes | ||||
existing_node_info_to_the_node: dict[ | ||||
tuple[ | ||||
ir.OperatorIdentifier, | ||||
int, # len(outputs) | ||||
tuple[int, ...], # input ids | ||||
tuple[tuple[str, object], ...], # attributes | ||||
], | ||||
ir.Node, | ||||
] = {} | ||||
|
||||
for node in graph: | ||||
# Skip control flow ops like Loop and If. | ||||
control_flow_op: bool = False | ||||
# Use equality to check if the node is a common subexpression. | ||||
attributes = {} | ||||
for k, v in node.attributes.items(): | ||||
# TODO(exporter team): CSE subgraphs. | ||||
# NOTE: control flow ops like Loop and If won't be CSEd | ||||
# because attribute: graph won't match. | ||||
if v.type in (ir.AttributeType.GRAPH, ir.AttributeType.GRAPHS): | ||||
control_flow_op = True | ||||
def _eliminate_common_subexpression(self, graph: ir.Graph) -> bool: | ||||
"""Eliminate common subexpression in ONNX graphs.""" | ||||
modified: bool = False | ||||
# node to node identifier, length of outputs, inputs, and attributes | ||||
existing_node_info_to_the_node: dict[ | ||||
tuple[ | ||||
ir.OperatorIdentifier, | ||||
int, # len(outputs) | ||||
tuple[int, ...], # input ids | ||||
tuple[tuple[str, object], ...], # attributes | ||||
], | ||||
ir.Node, | ||||
] = {} | ||||
|
||||
for node in graph: | ||||
# Skip control flow ops like Loop and If. | ||||
control_flow_op: bool = False | ||||
# Skip large tensors to avoid cse weights and bias. | ||||
large_tensor: bool = False | ||||
# Use equality to check if the node is a common subexpression. | ||||
attributes = {} | ||||
for k, v in node.attributes.items(): | ||||
# TODO(exporter team): CSE subgraphs. | ||||
# NOTE: control flow ops like Loop and If won't be CSEd | ||||
# because attribute: graph won't match. | ||||
if v.type in (ir.AttributeType.GRAPH, ir.AttributeType.GRAPHS): | ||||
control_flow_op = True | ||||
break | ||||
# The attribute value could be directly taken from the original | ||||
# protobuf, so we need to make a copy of it. | ||||
value = v.value | ||||
if v.type in ( | ||||
ir.AttributeType.INTS, | ||||
ir.AttributeType.FLOATS, | ||||
ir.AttributeType.STRINGS, | ||||
): | ||||
# For INT, FLOAT and STRING attributes, we convert them to tuples | ||||
# to ensure they are hashable. | ||||
value = tuple(value) | ||||
Comment on lines
+73
to
+81
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this can be improved: value_ints is the same as 1d tensor value int64. Maybe leverage the new ir-py/src/onnx_ir/_convenience/__init__.py Line 400 in e211825
|
||||
elif v.type is ir.AttributeType.TENSOR: | ||||
if value.size > self.size_limit: | ||||
# If the tensor is larger than the size limit, we skip it. | ||||
large_tensor = True | ||||
break | ||||
np_value = value.numpy() | ||||
|
||||
value = (np_value.shape, str(np_value.dtype), np_value.tobytes()) | ||||
attributes[k] = value | ||||
|
||||
if control_flow_op: | ||||
# If the node is a control flow op, we skip it. | ||||
logger.debug("Skipping control flow op %s", node) | ||||
# The attribute value could be directly taken from the original | ||||
# protobuf, so we need to make a copy of it. | ||||
value = v.value | ||||
if v.type in ( | ||||
ir.AttributeType.INTS, | ||||
ir.AttributeType.FLOATS, | ||||
ir.AttributeType.STRINGS, | ||||
): | ||||
# For INT, FLOAT and STRING attributes, we convert them to tuples | ||||
# to ensure they are hashable. | ||||
value = tuple(value) | ||||
attributes[k] = value | ||||
|
||||
if control_flow_op: | ||||
# If the node is a control flow op, we skip it. | ||||
logger.debug("Skipping control flow op %s", node) | ||||
continue | ||||
|
||||
if _is_non_deterministic_op(node): | ||||
# If the node is a non-deterministic op, we skip it. | ||||
logger.debug("Skipping non-deterministic op %s", node) | ||||
continue | ||||
|
||||
node_info = ( | ||||
node.op_identifier(), | ||||
len(node.outputs), | ||||
tuple(id(input) for input in node.inputs), | ||||
tuple(sorted(attributes.items())), | ||||
) | ||||
# Check if the node is a common subexpression. | ||||
if node_info in existing_node_info_to_the_node: | ||||
# If it is, this node has an existing node with the same | ||||
# operator, number of outputs, inputs, and attributes. | ||||
# We replace the node with the existing node. | ||||
modified = True | ||||
existing_node = existing_node_info_to_the_node[node_info] | ||||
_remove_node_and_replace_values( | ||||
graph, | ||||
remove_node=node, | ||||
remove_values=node.outputs, | ||||
new_values=existing_node.outputs, | ||||
continue | ||||
|
||||
if large_tensor: | ||||
# If the node has a large tensor, we skip it. | ||||
logger.debug("Skipping large tensor in node %s", node) | ||||
continue | ||||
|
||||
if _is_non_deterministic_op(node): | ||||
# If the node is a non-deterministic op, we skip it. | ||||
logger.debug("Skipping non-deterministic op %s", node) | ||||
continue | ||||
|
||||
node_info = ( | ||||
node.op_identifier(), | ||||
len(node.outputs), | ||||
tuple(id(input) for input in node.inputs), | ||||
tuple(sorted(attributes.items())), | ||||
) | ||||
logger.debug("Reusing node %s", existing_node) | ||||
else: | ||||
# If it is not, add to the mapping. | ||||
existing_node_info_to_the_node[node_info] = node | ||||
return modified | ||||
# Check if the node is a common subexpression. | ||||
if node_info in existing_node_info_to_the_node: | ||||
# If it is, this node has an existing node with the same | ||||
# operator, number of outputs, inputs, and attributes. | ||||
# We replace the node with the existing node. | ||||
modified = True | ||||
existing_node = existing_node_info_to_the_node[node_info] | ||||
_remove_node_and_replace_values( | ||||
graph, | ||||
remove_node=node, | ||||
remove_values=node.outputs, | ||||
new_values=existing_node.outputs, | ||||
) | ||||
logger.debug("Reusing node %s", existing_node) | ||||
else: | ||||
# If it is not, add to the mapping. | ||||
existing_node_info_to_the_node[node_info] = node | ||||
return modified | ||||
|
||||
|
||||
def _remove_node_and_replace_values( | ||||
|
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
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.