-
Notifications
You must be signed in to change notification settings - Fork 790
[BREAKING] Add asymmetric padding support for conv and pool operations #4263
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
antimora
wants to merge
12
commits into
tracel-ai:main
Choose a base branch
from
antimora:fix/onnx/padding
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.
Open
Changes from 3 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
919e9c5
Add support for asymmetric padding in conv and pool ops
antimora 0700942
Add asymmetric padding tests for pool and conv ops
antimora b75d84c
Fix PaddingConfig2d::Explicit usage in burn-store tests
antimora 0952dd8
Move asymmetric padding handling to functional layer
antimora 8a58490
Fix formatting
antimora e846bd3
Fix build
antimora fbd1872
Add TODOs for moving asymmetric padding in pooling layers
antimora f31710a
Support Same padding with even kernel sizes
antimora 4ecd44b
Merge remote-tracking branch 'upstream/main' into fix/onnx/padding
antimora 40857f5
Fix PaddingConfig2d::Explicit usage in safetensors-tests
antimora 8837c97
Improve padding comments for clarity
antimora 622d51e
Merge upstream/main into fix/onnx/padding
antimora 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
Binary file added
BIN
+191 Bytes
crates/burn-import/onnx-tests/tests/avg_pool/avg_pool1d_asymmetric_padding.onnx
Binary file not shown.
60 changes: 60 additions & 0 deletions
60
crates/burn-import/onnx-tests/tests/avg_pool/avg_pool1d_asymmetric_padding.py
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,60 @@ | ||
| #!/usr/bin/env python3 | ||
|
|
||
| # used to generate model: avg_pool1d_asymmetric_padding.onnx | ||
|
|
||
| import numpy as np | ||
| import onnx | ||
| from onnx import helper, TensorProto | ||
| from onnx.reference import ReferenceEvaluator | ||
|
|
||
|
|
||
| def main(): | ||
| # Input: [batch=2, channels=4, width=10] | ||
| # Asymmetric padding: left=1, right=2 | ||
| # kernel=3, stride=1 | ||
| # Output width = (10 + 1 + 2 - 3) / 1 + 1 = 11 | ||
|
|
||
| X = helper.make_tensor_value_info("x", TensorProto.FLOAT, [2, 4, 10]) | ||
| Y = helper.make_tensor_value_info("y", TensorProto.FLOAT, [2, 4, 11]) | ||
|
|
||
| # Create AveragePool node with asymmetric padding (left=1, right=2) | ||
| # ONNX pads format for 1D: [start, end] = [left, right] | ||
| avg_pool_node = helper.make_node( | ||
| "AveragePool", | ||
| inputs=["x"], | ||
| outputs=["y"], | ||
| kernel_shape=[3], | ||
| strides=[1], | ||
| pads=[1, 2], # [left, right] asymmetric padding | ||
| count_include_pad=1, # Include padding in average calculation | ||
| ) | ||
|
|
||
| graph = helper.make_graph( | ||
| [avg_pool_node], | ||
| "avg_pool1d_asymmetric_padding", | ||
| [X], | ||
| [Y], | ||
| ) | ||
|
|
||
| model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 18)]) | ||
| model.ir_version = 8 | ||
|
|
||
| onnx.checker.check_model(model) | ||
| file_name = "avg_pool1d_asymmetric_padding.onnx" | ||
| onnx.save(model, file_name) | ||
|
|
||
| print("Finished exporting model to {}".format(file_name)) | ||
| print("Ops in graph: {}".format([n.op_type for n in model.graph.node])) | ||
|
|
||
| # Verify with ReferenceEvaluator | ||
| test_input = np.ones((2, 4, 10), dtype=np.float32) | ||
| ref = ReferenceEvaluator(file_name) | ||
| ref_output = ref.run(None, {"x": test_input})[0] | ||
|
|
||
| print("Test input shape: {}".format(test_input.shape)) | ||
| print("Test output shape: {}".format(ref_output.shape)) | ||
| print("ReferenceEvaluator output sum: {}".format(ref_output.sum())) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Binary file added
BIN
+207 Bytes
crates/burn-import/onnx-tests/tests/avg_pool/avg_pool2d_asymmetric_padding.onnx
Binary file not shown.
61 changes: 61 additions & 0 deletions
61
crates/burn-import/onnx-tests/tests/avg_pool/avg_pool2d_asymmetric_padding.py
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,61 @@ | ||
| #!/usr/bin/env python3 | ||
|
|
||
| # used to generate model: avg_pool2d_asymmetric_padding.onnx | ||
|
|
||
| import numpy as np | ||
| import onnx | ||
| from onnx import helper, TensorProto | ||
| from onnx.reference import ReferenceEvaluator | ||
|
|
||
|
|
||
| def main(): | ||
| # Input: [batch=2, channels=4, height=10, width=15] | ||
| # Asymmetric padding: top=1, left=1, bottom=2, right=2 | ||
| # kernel=[3,3], stride=[1,1] | ||
| # Output height = (10 + 1 + 2 - 3) / 1 + 1 = 11 | ||
| # Output width = (15 + 1 + 2 - 3) / 1 + 1 = 16 | ||
|
|
||
| X = helper.make_tensor_value_info("x", TensorProto.FLOAT, [2, 4, 10, 15]) | ||
| Y = helper.make_tensor_value_info("y", TensorProto.FLOAT, [2, 4, 11, 16]) | ||
|
|
||
| # Create AveragePool node with asymmetric padding | ||
| # ONNX pads format for 2D: [top, left, bottom, right] | ||
| avg_pool_node = helper.make_node( | ||
| "AveragePool", | ||
| inputs=["x"], | ||
| outputs=["y"], | ||
| kernel_shape=[3, 3], | ||
| strides=[1, 1], | ||
| pads=[1, 1, 2, 2], # [top, left, bottom, right] asymmetric padding | ||
| count_include_pad=1, # Include padding in average calculation | ||
| ) | ||
|
|
||
| graph = helper.make_graph( | ||
| [avg_pool_node], | ||
| "avg_pool2d_asymmetric_padding", | ||
| [X], | ||
| [Y], | ||
| ) | ||
|
|
||
| model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 18)]) | ||
| model.ir_version = 8 | ||
|
|
||
| onnx.checker.check_model(model) | ||
| file_name = "avg_pool2d_asymmetric_padding.onnx" | ||
| onnx.save(model, file_name) | ||
|
|
||
| print("Finished exporting model to {}".format(file_name)) | ||
| print("Ops in graph: {}".format([n.op_type for n in model.graph.node])) | ||
|
|
||
| # Verify with ReferenceEvaluator | ||
| test_input = np.ones((2, 4, 10, 15), dtype=np.float32) | ||
| ref = ReferenceEvaluator(file_name) | ||
| ref_output = ref.run(None, {"x": test_input})[0] | ||
|
|
||
| print("Test input shape: {}".format(test_input.shape)) | ||
| print("Test output shape: {}".format(ref_output.shape)) | ||
| print("ReferenceEvaluator output sum: {}".format(ref_output.sum())) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
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
Binary file added
BIN
+2.25 KB
crates/burn-import/onnx-tests/tests/conv/conv1d_asymmetric_padding.onnx
Binary file not shown.
68 changes: 68 additions & 0 deletions
68
crates/burn-import/onnx-tests/tests/conv/conv1d_asymmetric_padding.py
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,68 @@ | ||
| #!/usr/bin/env python3 | ||
|
|
||
| # used to generate model: conv1d_asymmetric_padding.onnx | ||
|
|
||
| import torch | ||
| import torch.nn as nn | ||
| import torch.nn.functional as F | ||
| import onnx | ||
| from onnx.reference import ReferenceEvaluator | ||
|
|
||
| # must set for testing against crate | ||
| torch.manual_seed(0) | ||
|
|
||
|
|
||
| class Model(nn.Module): | ||
| def __init__(self): | ||
| super(Model, self).__init__() | ||
| # Create a Conv1d without padding - we'll apply asymmetric padding manually | ||
| self.conv1 = nn.Conv1d(4, 6, kernel_size=3, stride=1, padding=0) | ||
|
|
||
| def forward(self, x): | ||
| # Apply asymmetric padding: (left=1, right=2) | ||
| # PyTorch F.pad takes (left, right) for 1D | ||
| x = F.pad(x, (1, 2), mode='constant', value=0) | ||
| x = self.conv1(x) | ||
| return x | ||
|
|
||
|
|
||
| def main(): | ||
| # Set random seed for reproducibility | ||
| torch.manual_seed(0) | ||
|
|
||
| # Export to onnx | ||
| model = Model() | ||
| model.eval() | ||
| device = torch.device("cpu") | ||
|
|
||
| file_name = "conv1d_asymmetric_padding.onnx" | ||
| test_input = torch.ones(2, 4, 10, device=device) | ||
|
|
||
| # Export with dynamo exporter (opset 18) | ||
| torch.onnx.export(model, test_input, file_name, verbose=False, opset_version=18) | ||
|
|
||
| # Load model and convert external data to embedded | ||
| onnx_model = onnx.load(file_name, load_external_data=True) | ||
| # Save with all data embedded | ||
| onnx.save(onnx_model, file_name, save_as_external_data=False) | ||
|
|
||
| print("Finished exporting model to {}".format(file_name)) | ||
|
|
||
| # Output some test data for use in the test | ||
| print("Test input data shape of ones: {}".format(test_input.shape)) | ||
| output = model.forward(test_input) | ||
| print("Test output data shape: {}".format(output.shape)) | ||
|
|
||
| # Verify with ONNX ReferenceEvaluator | ||
| ref = ReferenceEvaluator(file_name) | ||
| ref_output = ref.run(None, {"x": test_input.numpy()})[0] | ||
|
|
||
| output_sum = output.sum().item() | ||
| ref_sum = ref_output.sum() | ||
|
|
||
| print("PyTorch output sum: {}".format(output_sum)) | ||
| print("ReferenceEvaluator output sum: {}".format(ref_sum)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Binary file added
BIN
+2.83 KB
crates/burn-import/onnx-tests/tests/conv/conv2d_asymmetric_padding.onnx
Binary file not shown.
68 changes: 68 additions & 0 deletions
68
crates/burn-import/onnx-tests/tests/conv/conv2d_asymmetric_padding.py
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,68 @@ | ||
| #!/usr/bin/env python3 | ||
|
|
||
| # used to generate model: conv2d_asymmetric_padding.onnx | ||
|
|
||
| import torch | ||
| import torch.nn as nn | ||
| import torch.nn.functional as F | ||
| import onnx | ||
| from onnx.reference import ReferenceEvaluator | ||
|
|
||
| # must set for testing against crate | ||
| torch.manual_seed(0) | ||
|
|
||
|
|
||
| class Model(nn.Module): | ||
| def __init__(self): | ||
| super(Model, self).__init__() | ||
| # Create a Conv2d without padding - we'll apply asymmetric padding manually | ||
| self.conv1 = nn.Conv2d(4, 6, kernel_size=3, stride=1, padding=0) | ||
|
|
||
| def forward(self, x): | ||
| # Apply asymmetric padding: (left=1, right=2, top=1, bottom=3) | ||
| # PyTorch F.pad takes (left, right, top, bottom) for 2D | ||
| x = F.pad(x, (1, 2, 1, 3), mode='constant', value=0) | ||
| x = self.conv1(x) | ||
| return x | ||
|
|
||
|
|
||
| def main(): | ||
| # Set random seed for reproducibility | ||
| torch.manual_seed(0) | ||
|
|
||
| # Export to onnx | ||
| model = Model() | ||
| model.eval() | ||
| device = torch.device("cpu") | ||
|
|
||
| file_name = "conv2d_asymmetric_padding.onnx" | ||
| test_input = torch.ones(2, 4, 10, 15, device=device) | ||
|
|
||
| # Export with dynamo exporter (opset 18) | ||
| torch.onnx.export(model, test_input, file_name, verbose=False, opset_version=18) | ||
|
|
||
| # Load model and convert external data to embedded | ||
| onnx_model = onnx.load(file_name, load_external_data=True) | ||
| # Save with all data embedded | ||
| onnx.save(onnx_model, file_name, save_as_external_data=False) | ||
|
|
||
| print("Finished exporting model to {}".format(file_name)) | ||
|
|
||
| # Output some test data for use in the test | ||
| print("Test input data shape of ones: {}".format(test_input.shape)) | ||
| output = model.forward(test_input) | ||
| print("Test output data shape: {}".format(output.shape)) | ||
|
|
||
| # Verify with ONNX ReferenceEvaluator | ||
| ref = ReferenceEvaluator(file_name) | ||
| ref_output = ref.run(None, {"x": test_input.numpy()})[0] | ||
|
|
||
| output_sum = output.sum().item() | ||
| ref_sum = ref_output.sum() | ||
|
|
||
| print("PyTorch output sum: {}".format(output_sum)) | ||
| print("ReferenceEvaluator output sum: {}".format(ref_sum)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
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.