-
Notifications
You must be signed in to change notification settings - Fork 5.6k
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
add the transpose op #3920
Merged
Merged
add the transpose op #3920
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
17b4b98
add the transpose op
NHZlX d6651b9
fixed bug of the gpu impl
NHZlX 828008e
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
NHZlX 5599182
modify GetAttr to Attr
NHZlX 4da89f2
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
NHZlX 61c7930
delete useless header file
NHZlX e129dcf
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
NHZlX 6b3ae01
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
NHZlX 5ede6fd
delete cuda impl, complete comments, modify variable naming
NHZlX 35967e8
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
NHZlX 9de45e1
fixed bug when dims.size == 1, modify the variable naming, add judgem…
NHZlX a9a7ba3
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
NHZlX 0cd9b8c
modify the input\output name to X\Out
NHZlX 1792e58
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
NHZlX 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 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,119 @@ | ||
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. | ||
|
||
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. */ | ||
|
||
#include "paddle/operators/transpose_op.h" | ||
|
||
namespace paddle { | ||
namespace operators { | ||
|
||
using framework::Tensor; | ||
|
||
class TransposeOp : public framework::OperatorWithKernel { | ||
public: | ||
using framework::OperatorWithKernel::OperatorWithKernel; | ||
|
||
protected: | ||
void InferShape(const framework::InferShapeContext &ctx) const override { | ||
PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("X"), "Input(X) should not be null"); | ||
PADDLE_ENFORCE_NOT_NULL(ctx.OutputVar("Out"), | ||
"Output(Out) should not be null"); | ||
auto x_dims = ctx.Input<Tensor>("X")->dims(); | ||
std::vector<int> axis = ctx.Attr<std::vector<int>>("axis"); | ||
size_t x_rank = x_dims.size(); | ||
size_t axis_size = axis.size(); | ||
|
||
PADDLE_ENFORCE_EQ(x_rank, axis_size, | ||
"the input tensor's rank(%d) " | ||
"should be equal to the axis's size(%d)", | ||
x_rank, axis_size); | ||
|
||
std::vector<int> count(axis_size, 0); | ||
for (size_t i = 0; i < axis_size; i++) { | ||
PADDLE_ENFORCE( | ||
axis[i] < static_cast<int>(axis_size) && ++count[axis[i]] == 1, | ||
"Each element of Attribute axis should be a unique value " | ||
"range from 0 to (dims - 1), " | ||
"where the dims is the axis's size"); | ||
} | ||
|
||
framework::DDim out_dims(x_dims); | ||
for (size_t i = 0; i < axis_size; i++) { | ||
out_dims[i] = x_dims[axis[i]]; | ||
} | ||
ctx.Output<framework::LoDTensor>("Out")->Resize(out_dims); | ||
} | ||
}; | ||
|
||
class TransposeOpMaker : public framework::OpProtoAndCheckerMaker { | ||
public: | ||
TransposeOpMaker(framework::OpProto *proto, | ||
framework::OpAttrChecker *op_checker) | ||
: OpProtoAndCheckerMaker(proto, op_checker) { | ||
AddInput( | ||
"X", | ||
"(Tensor)The input tensor, tensors with rank at most 6 are supported"); | ||
AddOutput("Out", "(Tensor)The output tensor"); | ||
AddAttr<std::vector<int>>( | ||
"axis", | ||
"(vector<int>)a list of values, and the size of the list should be " | ||
"the same with the input tensor rank, the tensor will " | ||
"permute the axes according the the values given"); | ||
AddComment(R"DOC( | ||
The Tensor will be permuted according to the axis values given. | ||
The op is very much like the numpy.transpose function in python | ||
For example: | ||
>> input = numpy.arange(6).reshape((2,3)) | ||
>> input | ||
array([[0, 1, 2], | ||
[3, 4, 5]]) | ||
>> axis = [1, 0] | ||
>> output = input.transpose(axis) | ||
>> output | ||
array([[0, 3], | ||
[1, 4], | ||
[2, 5]]) | ||
So, given a input tensor of shape(N, C, H, W) and the axis is {0, 2, 3, 1}, | ||
the output tensor shape will be (N, H, W, C) | ||
)DOC"); | ||
} | ||
}; | ||
|
||
class TransposeOpGrad : public framework::OperatorWithKernel { | ||
public: | ||
using framework::OperatorWithKernel::OperatorWithKernel; | ||
|
||
protected: | ||
void InferShape(const framework::InferShapeContext &ctx) const override { | ||
PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("X"), "Input(X) should not be null"); | ||
PADDLE_ENFORCE_NOT_NULL(ctx.InputVar(framework::GradVarName("Out")), | ||
"Input(Out@GRAD) should not be null"); | ||
auto x_dims = ctx.Input<Tensor>("X")->dims(); | ||
auto *x_grad = | ||
ctx.Output<framework::LoDTensor>(framework::GradVarName("X")); | ||
|
||
if (x_grad) x_grad->Resize(x_dims); | ||
} | ||
}; | ||
|
||
} // namespace operators | ||
} // namespace paddle | ||
|
||
namespace ops = paddle::operators; | ||
REGISTER_OP(transpose, ops::TransposeOp, ops::TransposeOpMaker, transpose_grad, | ||
ops::TransposeOpGrad); | ||
REGISTER_OP_CPU_KERNEL(transpose, | ||
ops::TransposeKernel<paddle::platform::CPUPlace, float>); | ||
REGISTER_OP_CPU_KERNEL( | ||
transpose_grad, | ||
ops::TransposeGradKernel<paddle::platform::CPUPlace, float>); |
This file contains 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,22 @@ | ||
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. | ||
|
||
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. */ | ||
|
||
#include "paddle/operators/transpose_op.h" | ||
|
||
namespace ops = paddle::operators; | ||
REGISTER_OP_GPU_KERNEL(transpose, | ||
ops::TransposeKernel<paddle::platform::GPUPlace, float>); | ||
REGISTER_OP_GPU_KERNEL( | ||
transpose_grad, | ||
ops::TransposeGradKernel<paddle::platform::GPUPlace, float>); |
This file contains 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,128 @@ | ||
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. | ||
|
||
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. */ | ||
|
||
#pragma once | ||
|
||
#include "paddle/framework/eigen.h" | ||
#include "paddle/framework/op_registry.h" | ||
|
||
namespace paddle { | ||
namespace operators { | ||
|
||
template <typename Place, typename T, int Rank> | ||
void EigenTranspose(const framework::ExecutionContext& context, | ||
const framework::Tensor& in, framework::Tensor& out, | ||
std::vector<int> axis) { | ||
Eigen::array<int, Rank> permute; | ||
for (int i = 0; i < Rank; i++) { | ||
permute[i] = axis[i]; | ||
} | ||
auto in_dim = in.dims(); | ||
auto out_dim = out.dims(); | ||
|
||
auto eigen_in = framework::EigenTensor<T, Rank>::From(in); | ||
auto eigen_out = framework::EigenTensor<T, Rank>::From(out); | ||
auto& dev = context.GetEigenDevice<Place>(); | ||
eigen_out.device(dev) = eigen_in.shuffle(permute); | ||
} | ||
|
||
template <typename Place, typename T> | ||
class TransposeKernel : public framework::OpKernel { | ||
public: | ||
void Compute(const framework::ExecutionContext& context) const override { | ||
auto* x = context.Input<framework::Tensor>("X"); | ||
auto* out = context.Output<framework::Tensor>("Out"); | ||
out->mutable_data<T>(context.GetPlace()); | ||
|
||
std::vector<int> axis = context.Attr<std::vector<int>>("axis"); | ||
int ndims = axis.size(); | ||
switch (ndims) { | ||
case 1: | ||
EigenTranspose<Place, T, 1>(context, *x, *out, axis); | ||
break; | ||
case 2: | ||
EigenTranspose<Place, T, 2>(context, *x, *out, axis); | ||
break; | ||
case 3: | ||
EigenTranspose<Place, T, 3>(context, *x, *out, axis); | ||
break; | ||
case 4: | ||
EigenTranspose<Place, T, 4>(context, *x, *out, axis); | ||
break; | ||
case 5: | ||
EigenTranspose<Place, T, 5>(context, *x, *out, axis); | ||
break; | ||
case 6: | ||
EigenTranspose<Place, T, 6>(context, *x, *out, axis); | ||
break; | ||
default: | ||
PADDLE_THROW("Tensors with rank at most 6 are supported"); | ||
} | ||
} | ||
}; | ||
|
||
template <typename Place, typename T> | ||
class TransposeGradKernel : public framework::OpKernel { | ||
public: | ||
void Compute(const framework::ExecutionContext& context) const override { | ||
auto* out_grad = | ||
context.Input<framework::Tensor>(framework::GradVarName("Out")); | ||
auto* x_grad = | ||
context.Output<framework::Tensor>(framework::GradVarName("X")); | ||
if (x_grad) { | ||
x_grad->mutable_data<T>(context.GetPlace()); | ||
|
||
std::vector<int> axis = context.Attr<std::vector<int>>("axis"); | ||
std::vector<int> reversed_axis(axis); | ||
|
||
for (size_t i = 0; i < axis.size(); i++) { | ||
reversed_axis[axis[i]] = i; | ||
} | ||
|
||
int ndims = axis.size(); | ||
|
||
switch (ndims) { | ||
case 1: | ||
EigenTranspose<Place, T, 1>(context, *out_grad, *x_grad, | ||
reversed_axis); | ||
break; | ||
case 2: | ||
EigenTranspose<Place, T, 2>(context, *out_grad, *x_grad, | ||
reversed_axis); | ||
break; | ||
case 3: | ||
EigenTranspose<Place, T, 3>(context, *out_grad, *x_grad, | ||
reversed_axis); | ||
break; | ||
case 4: | ||
EigenTranspose<Place, T, 4>(context, *out_grad, *x_grad, | ||
reversed_axis); | ||
break; | ||
case 5: | ||
EigenTranspose<Place, T, 5>(context, *out_grad, *x_grad, | ||
reversed_axis); | ||
break; | ||
case 6: | ||
EigenTranspose<Place, T, 6>(context, *out_grad, *x_grad, | ||
reversed_axis); | ||
break; | ||
default: | ||
PADDLE_THROW("Tensors with rank at most 6 are supported"); | ||
} | ||
} | ||
} | ||
}; | ||
|
||
} // namespace operators | ||
} // namespace paddle |
This file contains 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,56 @@ | ||
import unittest | ||
import numpy as np | ||
from op_test import OpTest | ||
|
||
|
||
class TestTransposeOp(OpTest): | ||
def setUp(self): | ||
self.initTestCase() | ||
self.op_type = "transpose" | ||
self.inputs = {'X': np.random.random(self.shape).astype("float32")} | ||
self.attrs = {'axis': list(self.axis)} | ||
self.outputs = {'Out': self.inputs['X'].transpose(self.axis)} | ||
|
||
def test_check_output(self): | ||
self.check_output() | ||
|
||
def test_check_grad(self): | ||
self.check_grad(['X'], 'Out') | ||
|
||
def initTestCase(self): | ||
self.shape = (3, 4) | ||
self.axis = (1, 0) | ||
|
||
|
||
class TestCase0(TestTransposeOp): | ||
def initTestCase(self): | ||
self.shape = (3, ) | ||
self.axis = (0, ) | ||
|
||
|
||
class TestCase1(TestTransposeOp): | ||
def initTestCase(self): | ||
self.shape = (3, 4, 5) | ||
self.axis = (0, 2, 1) | ||
|
||
|
||
class TestCase2(TestTransposeOp): | ||
def initTestCase(self): | ||
self.shape = (2, 3, 4, 5) | ||
self.axis = (0, 2, 3, 1) | ||
|
||
|
||
class TestCase3(TestTransposeOp): | ||
def initTestCase(self): | ||
self.shape = (2, 3, 4, 5, 6) | ||
self.axis = (4, 2, 3, 1, 0) | ||
|
||
|
||
class TestCase4(TestTransposeOp): | ||
def initTestCase(self): | ||
self.shape = (2, 3, 4, 5, 6, 1) | ||
self.axis = (4, 2, 3, 1, 0, 5) | ||
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. Here should be another test about whether our Op can throw an exception correctly. However, our framework can't support such a test right now. So I leave a comment here to remind us there is something TODO. I have created an issue about this: #4173 |
||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |
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 need to check
PADDLE_ENFORCE_NOT_NULL
but not in TransposeOp?