-
Notifications
You must be signed in to change notification settings - Fork 83
[Rewriter] Implement zero bias removal for Conv operations and related rules #2555
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
Open
whyvineet
wants to merge
18
commits into
microsoft:main
Choose a base branch
from
whyvineet:remove-optional-bias
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.
+596
−4
Open
Changes from 2 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
6cfd6fd
[Rewriter] Implement zero bias removal for Conv operations and relate…
whyvineet 48037a8
Merge branch 'microsoft:main' into remove-optional-bias
whyvineet fd028ee
Merge branch 'main' of github-personal:whyvineet/onnxscript into remo…
whyvineet 3742e7b
[Rewriter] Enhance zero bias removal for Conv, ConvTranspose, Gemm, a…
whyvineet 8bfa65f
Refactor zero bias removal tests to use helper function and improve s…
whyvineet 6fc3ca7
Merge branch 'main' of github-personal:whyvineet/onnxscript into remo…
whyvineet b93a56c
Refactor test cases for zero bias removal to improve readability and …
whyvineet e322625
Remove duplicate import of _fuse_batchnorm in rewriter module
whyvineet 121360e
Refactor zero bias removal logic to streamline input handling and enh…
whyvineet ee7dafa
Refactor Gemm operation pattern and check method to align with zero b…
whyvineet 8ef6c41
Enhance zero bias removal logic to filter bias parameters and preserv…
whyvineet 2b9dda4
Refactor bias removal logic to directly use operation inputs, improvi…
whyvineet 153b4e7
Remove redundant domain attribute from operation inputs in _RemoveZer…
whyvineet ce64fb7
Merge branch 'main' into remove-optional-bias
justinchuby a94f8b9
Merge HEAD, branch 'remove-optional-bias' of github-personal:whyvinee…
whyvineet 86de85f
Refactor IR value creation in tests to use `ir.Value` for consistency…
whyvineet d62eafb
Revert "Refactor IR value creation in tests to use `ir.Value` for con…
whyvineet d4f73dd
Enhance attribute comparison in optimization tests to handle list vs …
whyvineet 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
Some comments aren't visible on the classic Files Changed page.
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,203 @@ | ||
# Copyright (c) Microsoft Corporation. | ||
|
||
# Licensed under the MIT License. | ||
"""Remove optional bias when it is all zero from Conv and related operations.""" | ||
|
||
from __future__ import annotations | ||
|
||
import numpy as np | ||
|
||
from onnxscript import ir | ||
from onnxscript.rewriter._basics import MatchResult | ||
from onnxscript.rewriter._rewrite_rule import RewriteRuleClassBase, RewriteRuleSet | ||
|
||
|
||
class _RemoveZeroBiasBase(RewriteRuleClassBase): | ||
"""Base class for removing zero bias from operations.""" | ||
|
||
def __init__(self, op_type: str): | ||
super().__init__(remove_nodes=False) | ||
self.op_type = op_type | ||
whyvineet marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def rewrite(self, op: ir.tape.Tape, x: ir.Value, w: ir.Value, b: ir.Value) -> ir.Value: | ||
"""Remove the bias input from the operation.""" | ||
return op.op( | ||
self.op_type, | ||
inputs=[x, w], # Remove bias input | ||
) | ||
justinchuby marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def check(self, context, x: ir.Value, w: ir.Value, b: ir.Value, **_) -> MatchResult: | ||
"""Check if the bias is present and is all zeros.""" | ||
del context # Unused | ||
check_result = MatchResult() | ||
|
||
# Check if bias is a constant/initializer | ||
if b.const_value is None: | ||
whyvineet marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
return check_result.fail("Bias is not a constant/initializer.") | ||
|
||
# Check if bias is all zeros | ||
bias_array = b.const_value.numpy() | ||
if not np.allclose(bias_array, 0.0, atol=1e-8): | ||
return check_result.fail("Bias is not all zeros.") | ||
|
||
return check_result | ||
|
||
|
||
class RemoveZeroBiasFromConv(_RemoveZeroBiasBase): | ||
"""Remove zero bias from Conv operations.""" | ||
|
||
def __init__(self): | ||
super().__init__("Conv") | ||
|
||
def pattern(self, op: ir.tape.Tape, x: ir.Value, w: ir.Value, b: ir.Value) -> ir.Value: | ||
return op.Conv(x, w, b, _outputs=["conv_out"]) | ||
|
||
def check(self, context, x: ir.Value, w: ir.Value, b: ir.Value, conv_out: ir.Value, **_) -> MatchResult: | ||
"""Check if the bias is present and is all zeros.""" | ||
del context # Unused | ||
check_result = MatchResult() | ||
|
||
# Check if bias is a constant/initializer | ||
if b.const_value is None: | ||
return check_result.fail("Bias is not a constant/initializer.") | ||
|
||
# Check if bias is all zeros | ||
bias_array = b.const_value.numpy() | ||
if not np.allclose(bias_array, 0.0, atol=1e-8): | ||
return check_result.fail("Bias is not all zeros.") | ||
|
||
return check_result | ||
whyvineet marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def rewrite(self, op: ir.tape.Tape, x: ir.Value, w: ir.Value, b: ir.Value, conv_out: ir.Value) -> ir.Value: | ||
|
||
"""Remove the bias input from the operation.""" | ||
# Get the Conv node that produced conv_out to access its attributes | ||
conv_node = conv_out.producer() | ||
|
||
# Create new Conv with preserved attributes but without bias | ||
return op.op( | ||
"Conv", | ||
inputs=[x, w], # Remove bias input | ||
attributes=conv_node.attributes, | ||
domain=conv_node.domain, | ||
) | ||
|
||
|
||
class RemoveZeroBiasFromConvTranspose(_RemoveZeroBiasBase): | ||
"""Remove zero bias from ConvTranspose operations.""" | ||
|
||
def __init__(self): | ||
super().__init__("ConvTranspose") | ||
|
||
def pattern(self, op: ir.tape.Tape, x: ir.Value, w: ir.Value, b: ir.Value) -> ir.Value: | ||
return op.ConvTranspose(x, w, b, _allow_other_inputs=False, _outputs=["conv_out"]) | ||
whyvineet marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def rewrite(self, op: ir.tape.Tape, x: ir.Value, w: ir.Value, b: ir.Value, conv_out: ir.Value) -> ir.Value: | ||
|
||
"""Remove the bias input from the operation.""" | ||
# Get the ConvTranspose node that produced conv_out to access its attributes | ||
conv_node = conv_out.producer() | ||
|
||
# Create new ConvTranspose with preserved attributes but without bias | ||
return op.op( | ||
"ConvTranspose", | ||
inputs=[x, w], # Remove bias input | ||
attributes=conv_node.attributes, | ||
domain=conv_node.domain, | ||
) | ||
|
||
|
||
class RemoveZeroBiasFromQLinearConv(_RemoveZeroBiasBase): | ||
"""Remove zero bias from QLinearConv operations.""" | ||
|
||
def __init__(self): | ||
super().__init__("QLinearConv") | ||
|
||
def pattern(self, op: ir.tape.Tape, x, x_scale, x_zero_point, w, w_scale, w_zero_point, | ||
y_scale, y_zero_point, b: ir.Value) -> ir.Value: | ||
return op.QLinearConv( | ||
x, x_scale, x_zero_point, w, w_scale, w_zero_point, | ||
y_scale, y_zero_point, b, _allow_other_inputs=False, _outputs=["conv_out"] | ||
) | ||
|
||
def check(self, context, x, x_scale, x_zero_point, w, w_scale, w_zero_point, | ||
y_scale, y_zero_point, b: ir.Value, conv_out: ir.Value, **_) -> MatchResult: | ||
"""Check if the bias (b) is present and is all zeros.""" | ||
del context # Unused | ||
check_result = MatchResult() | ||
|
||
# Check if bias is a constant/initializer | ||
if b.const_value is None: | ||
return check_result.fail("Bias is not a constant/initializer.") | ||
|
||
# Check if bias is all zeros | ||
bias_array = b.const_value.numpy() | ||
if not np.allclose(bias_array, 0.0, atol=1e-8): | ||
return check_result.fail("Bias is not all zeros.") | ||
|
||
return check_result | ||
|
||
def rewrite(self, op: ir.tape.Tape, x, x_scale, x_zero_point, w, w_scale, w_zero_point, | ||
y_scale, y_zero_point, b: ir.Value, conv_out: ir.Value) -> ir.Value: | ||
|
||
"""Remove the bias input from the operation.""" | ||
# Get the QLinearConv node that produced conv_out to access its attributes | ||
conv_node = conv_out.producer() | ||
|
||
# Create new QLinearConv with preserved attributes but without bias | ||
return op.op( | ||
"QLinearConv", | ||
inputs=[x, x_scale, x_zero_point, w, w_scale, w_zero_point, | ||
y_scale, y_zero_point], # Remove bias input | ||
attributes=conv_node.attributes, | ||
domain=conv_node.domain, | ||
) | ||
|
||
|
||
class RemoveZeroBiasFromGemm(_RemoveZeroBiasBase): | ||
"""Remove zero bias from Gemm operations.""" | ||
|
||
def __init__(self): | ||
super().__init__("Gemm") | ||
|
||
def pattern(self, op: ir.tape.Tape, a: ir.Value, b: ir.Value, c: ir.Value) -> ir.Value: | ||
return op.Gemm(a, b, c, _allow_other_inputs=False, _outputs=["gemm_out"]) | ||
|
||
def check(self, context, a: ir.Value, b: ir.Value, c: ir.Value, gemm_out: ir.Value, **_) -> MatchResult: | ||
"""Check if the bias (c) is present and is all zeros.""" | ||
del context # Unused | ||
check_result = MatchResult() | ||
|
||
# Check if bias is a constant/initializer | ||
if c.const_value is None: | ||
return check_result.fail("Bias is not a constant/initializer.") | ||
|
||
# Check if bias is all zeros | ||
bias_array = c.const_value.numpy() | ||
if not np.allclose(bias_array, 0.0, atol=1e-8): | ||
return check_result.fail("Bias is not all zeros.") | ||
|
||
return check_result | ||
|
||
def rewrite(self, op: ir.tape.Tape, a: ir.Value, b: ir.Value, c: ir.Value, gemm_out: ir.Value) -> ir.Value: | ||
|
||
"""Remove the bias input from the operation.""" | ||
# Get the Gemm node that produced gemm_out to access its attributes | ||
gemm_node = gemm_out.producer() | ||
|
||
# Create new Gemm with preserved attributes but without bias | ||
return op.op( | ||
"Gemm", | ||
inputs=[a, b], # Remove bias input | ||
attributes=gemm_node.attributes, | ||
domain=gemm_node.domain, | ||
) | ||
|
||
|
||
# Create rule instances | ||
remove_zero_bias_from_conv_rule = RemoveZeroBiasFromConv().rule() | ||
remove_zero_bias_from_conv_transpose_rule = RemoveZeroBiasFromConvTranspose().rule() | ||
remove_zero_bias_from_qlinear_conv_rule = RemoveZeroBiasFromQLinearConv().rule() | ||
remove_zero_bias_from_gemm_rule = RemoveZeroBiasFromGemm().rule() | ||
|
||
rules = RewriteRuleSet([ | ||
remove_zero_bias_from_conv_rule, | ||
remove_zero_bias_from_conv_transpose_rule, | ||
remove_zero_bias_from_qlinear_conv_rule, | ||
remove_zero_bias_from_gemm_rule, | ||
]) |
87 changes: 87 additions & 0 deletions
87
onnxscript/rewriter/rules/common/_remove_zero_bias_test.py
whyvineet marked this conversation as resolved.
Show resolved
Hide resolved
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. Maybe you can pass some attributes when testing to check that every info is correctly transferred (e.g. stride, transA...) |
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,87 @@ | ||
# Copyright (c) Microsoft Corporation. | ||
|
||
# Licensed under the MIT License. | ||
"""Tests for removing zero bias from Conv and related operations.""" | ||
|
||
import onnx | ||
import onnx.parser | ||
import onnx_ir as ir | ||
|
||
from onnxscript.rewriter.rules.common._remove_zero_bias import ( | ||
remove_zero_bias_from_conv_rule, | ||
) | ||
|
||
|
||
def test_remove_zero_bias_from_conv(): | ||
"""Test that zero bias is removed from Conv operations.""" | ||
# Create a simple Conv with zero bias using ONNX parser | ||
model_proto = onnx.parser.parse_model( | ||
justinchuby marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
""" | ||
<ir_version: 7, opset_import: [ "" : 17]> | ||
agraph (float[1, 2, 4, 4] x) => (float[1, 2, 2, 2] y) | ||
{ | ||
weight = Constant <value = float[2, 2, 3, 3] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36}>() | ||
bias = Constant <value = float[2] {0, 0}>() | ||
y = Conv(x, weight, bias) | ||
} | ||
""" | ||
) | ||
|
||
# Convert to IR model | ||
model = ir.serde.deserialize_model(model_proto) | ||
|
||
# Apply the rule | ||
count = remove_zero_bias_from_conv_rule.apply_to_model(model) | ||
|
||
# Check that the rule was applied | ||
assert count == 1, f"Expected 1 application, got {count}" | ||
|
||
# Check that bias input was removed | ||
conv_node = None | ||
for node in model.graph: | ||
if node.op_type == "Conv": | ||
conv_node = node | ||
break | ||
|
||
assert conv_node is not None, "Conv node not found" | ||
assert len(conv_node.inputs) == 2, f"Expected 2 inputs after optimization, got {len(conv_node.inputs)}" | ||
justinchuby marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
|
||
def test_conv_with_non_zero_bias_unchanged(): | ||
"""Test that Conv with non-zero bias is not modified.""" | ||
# Create a Conv with non-zero bias using ONNX parser | ||
model_proto = onnx.parser.parse_model( | ||
""" | ||
<ir_version: 7, opset_import: [ "" : 17]> | ||
agraph (float[1, 2, 4, 4] x) => (float[1, 2, 2, 2] y) | ||
{ | ||
weight = Constant <value = float[2, 2, 3, 3] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36}>() | ||
bias = Constant <value = float[2] {1, 1}>() | ||
y = Conv(x, weight, bias) | ||
} | ||
""" | ||
) | ||
|
||
# Convert to IR model | ||
model = ir.serde.deserialize_model(model_proto) | ||
|
||
# Apply the rule | ||
count = remove_zero_bias_from_conv_rule.apply_to_model(model) | ||
|
||
# Check that the rule was NOT applied | ||
assert count == 0, f"Expected 0 applications, got {count}" | ||
|
||
# Check that bias input is still present | ||
conv_node = None | ||
for node in model.graph: | ||
if node.op_type == "Conv": | ||
conv_node = node | ||
break | ||
|
||
assert conv_node is not None, "Conv node not found" | ||
assert len(conv_node.inputs) == 3, f"Expected 3 inputs, got {len(conv_node.inputs)}" | ||
|
||
|
||
if __name__ == "__main__": | ||
test_remove_zero_bias_from_conv() | ||
test_conv_with_non_zero_bias_unchanged() | ||
print("All tests passed!") |
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.