-
Notifications
You must be signed in to change notification settings - Fork 5.9k
【Hackathon 6th No.3】为 Paddle 新增 ZeroPad1D / ZeroPad3D / block_diag API -part #63728
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 15 commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
03a43c3
add api
ADream-ki 05e6050
update zeropad1 test
ADream-ki ab0762c
test
ADream-ki 5088dbe
update block_diag example
ADream-ki 7854d91
update test
ADream-ki cbf4594
test
ADream-ki edae11d
update
ADream-ki 319e0c5
add block_diag
ADream-ki e7a7625
update
ADream-ki db8fce8
Merge branch 'PaddlePaddle:develop' into task2
ADream-ki 3f3cc8b
Merge branch 'PaddlePaddle:develop' into task2
ADream-ki 28e80b7
Zeropad
ADream-ki d9fccd4
finish
ADream-ki 7bd3ffe
update test
ADream-ki 2cb256d
Merge branch 'PaddlePaddle:develop' into task2
ADream-ki cda4dca
update cpu/gpu
ADream-ki d8e24e3
Merge branch 'task2' of https://github.com/Chen-Lun-Hao/Paddle into t…
ADream-ki b382c5e
update
ADream-ki 9dddaa5
update file
ADream-ki 940d365
update
ADream-ki 832059f
update
ADream-ki 569ded4
Merge branch 'PaddlePaddle:develop' into task2
ADream-ki 333f225
update
ADream-ki 0375e5f
Merge branch 'task2' of https://github.com/Chen-Lun-Hao/Paddle into t…
ADream-ki 8fd3aeb
update
ADream-ki 97bfa5f
update
ADream-ki c8b7a84
finish
ADream-ki d05dd19
update
ADream-ki 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,142 @@ | ||
| # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from .. import functional as F | ||
| from .common import _npairs | ||
| from .layers import Layer | ||
|
|
||
|
|
||
| class ZeroPad1D(Layer): | ||
| """ | ||
| This interface is used to construct a callable object of the ``ZeroPad1D`` class. | ||
| Pads the input tensor boundaries with zero. | ||
| Parameters: | ||
| padding (Tensor | List[int] | int): The padding size with data type int. If is int, use the | ||
| same padding in all dimensions. Else [len(padding)/2] dimensions of input will be padded. | ||
| The pad has the form (pad_left, pad_right). | ||
| data_format (str): An string from: "NCL", "NCL". Specify the data format of the input data. | ||
| Default is "NCL" | ||
| name (str, optional) : The default value is None. Normally there is no need for | ||
| user to set this property. For more information, please refer to :ref:`api_guide_Name`. | ||
| Shape: | ||
| - x(Tensor): The input tensor of zeropad1d operator, which is a 3-D tensor. | ||
| The data type can be float32, float64. | ||
| - output(Tensor): The output tensor of zeropad1d operator, which is a 3-D tensor. | ||
| The data type is same as input x. | ||
| Examples: | ||
| .. code-block:: python | ||
| >>> import paddle | ||
| >>> import paddle.nn as nn | ||
| >>> input_shape = (1, 2, 3) | ||
| >>> pad = [1, 2] | ||
| >>> data = paddle.arange(paddle.prod(paddle.to_tensor(input_shape)), dtype="float32").reshape(input_shape) + 1 | ||
| >>> my_pad = nn.ZeroPad1D(padding=pad) | ||
| >>> result = my_pad(data) | ||
| >>> print(result) | ||
| Tensor(shape=[1, 2, 6], dtype=float32, place=Place(cpu), stop_gradient=True, | ||
| [[[0., 1., 2., 3., 0., 0.], | ||
| [0., 4., 5., 6., 0., 0.]]]) | ||
| """ | ||
|
|
||
| def __init__(self, padding, data_format="NCL", name=None): | ||
| super().__init__() | ||
| self._pad = _npairs(padding, 1) | ||
| self._mode = 'constant' | ||
| self._value = 0.0 | ||
| self._data_format = data_format | ||
| self._name = name | ||
|
|
||
| def forward(self, x): | ||
| return F.pad( | ||
| x, | ||
| pad=self._pad, | ||
| mode=self._mode, | ||
| value=self._value, | ||
| data_format=self._data_format, | ||
| name=self._name, | ||
| ) | ||
|
|
||
| def extra_repr(self): | ||
| name_str = f', name={self._name}' if self._name else '' | ||
| return f'padding={self._pad}, data_format={self._data_format}{name_str}' | ||
|
|
||
|
|
||
| class ZeroPad3D(Layer): | ||
| """ | ||
| This interface is used to construct a callable object of the ``ZeroPad3D`` class. | ||
| Pads the input tensor boundaries with zero. | ||
| Parameters: | ||
| padding (Tensor | List[int] | int): The padding size with data type int. If is int, use the | ||
| same padding in all dimensions. Else [len(padding)/2] dimensions of input will be padded. | ||
| The pad has the form (pad_left, pad_right, pad_top, pad_bottom, pad_front, pad_back). | ||
| data_format (str): An string from: "NCDHW", "NCDHW". Specify the data format of the input data. | ||
| Default is "NCDHW" | ||
| name (str, optional) : The default value is None. Normally there is no need for | ||
| user to set this property. For more information, please refer to :ref:`api_guide_Name`. | ||
| Shape: | ||
| - x(Tensor): The input tensor of zeropad3d operator, which is a 5-D tensor. | ||
| The data type can be float32, float64. | ||
| - output(Tensor): The output tensor of zeropad3d operator, which is a 5-D tensor. | ||
| The data type is same as input x. | ||
| Examples: | ||
| .. code-block:: python | ||
| >>> import paddle | ||
| >>> import paddle.nn as nn | ||
| >>> input_shape = (1, 1, 1, 2, 3) | ||
| >>> pad = [1, 0, 1, 2, 0, 0] | ||
| >>> data = paddle.arange(paddle.prod(paddle.to_tensor(input_shape)), dtype="float32").reshape(input_shape) + 1 | ||
| >>> my_pad = nn.ZeroPad3D(padding=pad) | ||
| >>> result = my_pad(data) | ||
| >>> print(result) | ||
| Tensor(shape=[1, 1, 1, 5, 4], dtype=float32, place=Place(cpu), stop_gradient=True, | ||
| [[[[[0., 0., 0., 0.], | ||
| [0., 1., 2., 3.], | ||
| [0., 4., 5., 6.], | ||
| [0., 0., 0., 0.], | ||
| [0., 0., 0., 0.]]]]]) | ||
| """ | ||
|
|
||
| def __init__(self, padding, data_format="NCDHW", name=None): | ||
| super().__init__() | ||
| self._pad = _npairs(padding, 3) | ||
| self._mode = 'constant' | ||
| self._value = 0.0 | ||
| self._data_format = data_format | ||
| self._name = name | ||
|
|
||
| def forward(self, x): | ||
| return F.pad( | ||
| x, | ||
| pad=self._pad, | ||
| mode=self._mode, | ||
| value=self._value, | ||
| data_format=self._data_format, | ||
| name=self._name, | ||
| ) | ||
|
|
||
| def extra_repr(self): | ||
| name_str = f', name={self._name}' if self._name else '' | ||
| return f'padding={self._pad}, data_format={self._data_format}{name_str}' | ||
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 |
|---|---|---|
|
|
@@ -6843,3 +6843,67 @@ def slice_scatter(x, value, axes, starts, ends, strides, name=None): | |
| ) | ||
|
|
||
| return output | ||
|
|
||
|
|
||
| def block_diag(*inputs, name=None): | ||
|
||
| """ | ||
| Create a block diagonal matrix from provided tensors. | ||
|
|
||
| Args: | ||
| *input (Tensor): One or more tensors with 0, 1, or 2 dimensions. | ||
| name (str, optional): Name for the operation (optional, default is None). | ||
|
|
||
| Returns: | ||
| Tensor, A ``Tensor``. The data type is same as ``input``. | ||
|
|
||
| Examples: | ||
| .. code-block:: python | ||
|
|
||
| >>> import paddle | ||
|
|
||
| >>> A = paddle.to_tensor([[4], [3], [2]]) | ||
| >>> B = paddle.to_tensor([7, 6, 5]) | ||
| >>> C = paddle.to_tensor(1) | ||
| >>> D = paddle.to_tensor([[5, 4, 3], [2, 1, 0]]) | ||
| >>> E = paddle.to_tensor([[8, 7], [7, 8]]) | ||
| >>> out = paddle.block_diag(A, B, C, D, E) | ||
| >>> print(out) | ||
| Tensor(shape=[9, 10], dtype=int64, place=Place(gpu:0), stop_gradient=True, | ||
| [[4, 0, 0, 0, 0, 0, 0, 0, 0, 0], | ||
| [3, 0, 0, 0, 0, 0, 0, 0, 0, 0], | ||
| [2, 0, 0, 0, 0, 0, 0, 0, 0, 0], | ||
| [0, 7, 6, 5, 0, 0, 0, 0, 0, 0], | ||
| [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], | ||
| [0, 0, 0, 0, 0, 5, 4, 3, 0, 0], | ||
| [0, 0, 0, 0, 0, 2, 1, 0, 0, 0], | ||
| [0, 0, 0, 0, 0, 0, 0, 0, 8, 7], | ||
| [0, 0, 0, 0, 0, 0, 0, 0, 7, 8]]) | ||
| """ | ||
|
|
||
| def to_col_block(arys, i, a): | ||
| return [ | ||
| a | ||
| if idx == i | ||
| else paddle.zeros([ary.shape[0], a.shape[1]], dtype=a.dtype) | ||
| for idx, ary in enumerate(arys) | ||
| ] | ||
|
|
||
| def to_2d(ary): | ||
| if ary.ndim == 0: | ||
| return ary.unsqueeze(axis=0).unsqueeze(axis=0) | ||
| if ary.ndim == 1: | ||
| return ary.unsqueeze(axis=0) | ||
| if ary.ndim == 2: | ||
| return ary | ||
| raise ValueError( | ||
| "For 'block_diag', the dimension of each elements in 'inputs' must be 0, 1, or 2, but got " | ||
| f"{ary.ndim}" | ||
| ) | ||
|
|
||
| arys = [to_2d(ary) for ary in inputs] | ||
|
|
||
| matrix = [ | ||
| paddle.concat(to_col_block(arys, idx, ary), axis=0) | ||
| for idx, ary in enumerate(arys) | ||
| ] | ||
| return paddle.concat(matrix, axis=1) | ||
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,85 @@ | ||
| # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import unittest | ||
|
|
||
| import numpy as np | ||
|
|
||
| from paddle import to_tensor | ||
| from paddle.nn import ZeroPad1D | ||
|
|
||
|
|
||
| class TestZeroPad1dAPI(unittest.TestCase): | ||
| def setUp(self): | ||
| self.shape = [4, 6, 6] | ||
| self.support_dtypes = ['float32', 'float64', 'int32', 'int64'] | ||
|
|
||
| def test_support_dtypes(self): | ||
| for dtype in self.support_dtypes: | ||
| pad = 2 | ||
| x = np.random.randint(-255, 255, size=self.shape).astype(dtype) | ||
| expect_res = np.pad( | ||
| x, | ||
| [[0, 0], [0, 0], [pad, pad]], | ||
| mode='constant', | ||
| constant_values=0, | ||
| ) | ||
|
|
||
| x_tensor = to_tensor(x).astype(dtype) | ||
| zeropad1d = ZeroPad1D(padding=pad) | ||
| ret_res = zeropad1d(x_tensor).numpy() | ||
| np.testing.assert_allclose(expect_res, ret_res, rtol=1e-05) | ||
|
|
||
| def test_support_pad2(self): | ||
| pad = [1, 2] | ||
| x = np.random.randint(-255, 255, size=self.shape) | ||
| expect_res = np.pad( | ||
| x, [[0, 0], [0, 0], pad], mode='constant', constant_values=0 | ||
| ) | ||
|
|
||
| x_tensor = to_tensor(x) | ||
| zeropad1d = ZeroPad1D(padding=pad) | ||
| ret_res = zeropad1d(x_tensor).numpy() | ||
| np.testing.assert_allclose(expect_res, ret_res, rtol=1e-05) | ||
|
|
||
| def test_support_pad3(self): | ||
| pad = (1, 2) | ||
| x = np.random.randint(-255, 255, size=self.shape) | ||
| expect_res = np.pad(x, [[0, 0], [0, 0], [pad[0], pad[1]]]) | ||
|
|
||
| x_tensor = to_tensor(x) | ||
| zeropad1d = ZeroPad1D(padding=pad) | ||
| ret_res = zeropad1d(x_tensor).numpy() | ||
| np.testing.assert_allclose(expect_res, ret_res, rtol=1e-05) | ||
|
|
||
| def test_support_pad4(self): | ||
| pad = [1, 2] | ||
| x = np.random.randint(-255, 255, size=self.shape) | ||
| expect_res = np.pad(x, [[0, 0], [0, 0], [pad[0], pad[1]]]) | ||
|
|
||
| x_tensor = to_tensor(x) | ||
| pad_tensor = to_tensor(pad, dtype='int32') | ||
| zeropad1d = ZeroPad1D(padding=pad_tensor) | ||
| ret_res = zeropad1d(x_tensor).numpy() | ||
| np.testing.assert_allclose(expect_res, ret_res, rtol=1e-05) | ||
|
|
||
| def test_repr(self): | ||
| pad = [1, 2] | ||
| zeropad1d = ZeroPad1D(padding=pad) | ||
| name_str = zeropad1d.extra_repr() | ||
| assert name_str == 'padding=[1, 2], data_format=NCL' | ||
|
|
||
|
|
||
| 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why not add
ZeroPad1DandZeroPad3Din python/paddle/nn/layer/common.py, together withZeroPad2Dfor easy maintenance in the future?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because according to the requirements in the task, I need to implement it in the corresponding file instead of ‘common.py’ @jeff41404
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
抱歉 这边的话还是放一起合适点。 @Chen-Lun-Hao
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
好的,那我移到common那里去