-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Feature/fc converter #11043
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
Superjomn
merged 9 commits into
PaddlePaddle:develop
from
Superjomn:feature/fc_converter
Jun 1, 2018
Merged
Feature/fc converter #11043
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
768cf55
init
Superjomn 7fdbd92
init
Superjomn 8df9096
init
Superjomn 96fe6a1
fix compile error
Superjomn 5871e04
fix ut
Superjomn 20739a8
Merge branch 'develop' of github.com:PaddlePaddle/Paddle into feature…
Superjomn 5d24919
fix compile
Superjomn d5bd249
fix follow review
Superjomn c0829e5
Merge branch 'develop' of github.com:PaddlePaddle/Paddle into feature…
Superjomn 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
/* Copyright (c) 2018 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. */ | ||
|
||
#include "paddle/fluid/framework/eigen.h" | ||
#include "paddle/fluid/framework/lod_tensor.h" | ||
#include "paddle/fluid/framework/op_registry.h" | ||
#include "paddle/fluid/inference/tensorrt/convert/op_converter.h" | ||
#include "paddle/fluid/inference/tensorrt/engine.h" | ||
#include "paddle/fluid/platform/place.h" | ||
|
||
namespace paddle { | ||
namespace inference { | ||
namespace tensorrt { | ||
|
||
// Reorder the elements from istrides to ostrides, borrowed from TRT convert in | ||
// tensorflow. | ||
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/tensorrt/convert/convert_nodes.cc#L318 | ||
template <typename T> | ||
void Reorder2(nvinfer1::DimsHW shape, const T* idata, nvinfer1::DimsHW istrides, | ||
T* odata, nvinfer1::DimsHW ostrides) { | ||
for (int h = 0; h < shape.h(); ++h) { | ||
for (int w = 0; w < shape.w(); ++w) { | ||
odata[h * ostrides.h() + w * ostrides.w()] = | ||
idata[h * ostrides.h() + w * ostrides.w()]; | ||
} | ||
} | ||
} | ||
|
||
// Reorder the data layout from CK to KC. | ||
void ReorderCKtoKC(TensorRTEngine::Weight& iweights, | ||
TensorRTEngine::Weight* oweights) { | ||
int c = iweights.dims[0]; | ||
int k = iweights.dims[1]; | ||
oweights->dims.assign({k, c}); | ||
nvinfer1::DimsHW istrides = {1, k}; | ||
nvinfer1::DimsHW ostrides = {c, 1}; | ||
Reorder2({k, c}, static_cast<float const*>(iweights.get().values), istrides, | ||
static_cast<float*>(const_cast<void*>(oweights->get().values)), | ||
ostrides); | ||
} | ||
|
||
/* | ||
* FC converter convert a MUL op in Fluid to a FC layer in TRT. | ||
*/ | ||
class FcOpConverter : public OpConverter { | ||
public: | ||
void operator()(const framework::proto::OpDesc& op, | ||
const framework::Scope& scope) override { | ||
VLOG(4) << "convert a fluid fc op to tensorrt fc layer without bias"; | ||
|
||
framework::OpDesc op_desc(op, nullptr, nullptr); | ||
PADDLE_ENFORCE_EQ(op_desc.Input("X").size(), 1); | ||
PADDLE_ENFORCE_EQ(op_desc.Input("Y").size(), 1); // Y is a weight | ||
PADDLE_ENFORCE_EQ(op_desc.Output("Out").size(), 1); | ||
|
||
// Declare inputs | ||
auto* X = engine_->GetITensor(op_desc.Input("X").front()); | ||
|
||
// Declare weights | ||
auto* Y_v = scope.FindVar(op_desc.Input("Y").front()); | ||
PADDLE_ENFORCE_NOT_NULL(Y_v); | ||
auto* Y_t = Y_v->GetMutable<framework::LoDTensor>(); | ||
// This may trigger a GPU->CPU copy, because TRT's weight can only be | ||
// assigned from CPU memory, that can't be avoided. | ||
auto* weight_data = Y_t->mutable_data<float>(platform::CPUPlace()); | ||
PADDLE_ENFORCE_EQ(Y_t->dims().size(), 2UL); // a matrix | ||
size_t n_output = Y_t->dims()[1]; | ||
|
||
framework::LoDTensor tmp; | ||
tmp.Resize(Y_t->dims()); | ||
memcpy(tmp.mutable_data<float>(platform::CPUPlace()), Y_t->data<float>(), | ||
Y_t->dims()[0] * Y_t->dims()[1]); | ||
|
||
TensorRTEngine::Weight weight{nvinfer1::DataType::kFLOAT, | ||
static_cast<void*>(weight_data), | ||
Y_t->memory_size() / sizeof(float)}; | ||
TensorRTEngine::Weight tmp_weight(nvinfer1::DataType::kFLOAT, | ||
static_cast<void*>(tmp.data<float>()), | ||
Y_t->memory_size() / sizeof(float)); | ||
weight.dims.assign({Y_t->dims()[0], Y_t->dims()[1]}); | ||
tmp_weight.dims = weight.dims; | ||
|
||
// The data layout of TRT FC layer's weight is different from fluid's FC, | ||
// need to reorder the elements. | ||
ReorderCKtoKC(tmp_weight, &weight); | ||
|
||
// Currently, the framework can only handle one fluid op -> one TRT layer, | ||
// but fc fuses `mul` and `bias` (2 fluid ops), so here is a trick, just | ||
// handle `mul`, leave `add` as another layer. | ||
// DEBUG | ||
TensorRTEngine::Weight bias{nvinfer1::DataType::kFLOAT, nullptr, 0}; | ||
|
||
auto* layer = TRT_ENGINE_ADD_LAYER(engine_, FullyConnected, | ||
*const_cast<nvinfer1::ITensor*>(X), | ||
n_output, weight.get(), bias.get()); | ||
|
||
auto output_name = op_desc.Output("Out").front(); | ||
engine_->DeclareOutput(layer, 0, output_name); | ||
} | ||
}; | ||
|
||
REGISTER_TRT_OP_CONVERTER(fc, FcOpConverter); | ||
|
||
} // namespace tensorrt | ||
} // namespace inference | ||
} // namespace paddle | ||
|
||
USE_OP(mul); |
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,46 @@ | ||
/* Copyright (c) 2018 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. */ | ||
|
||
#include <gtest/gtest.h> | ||
#include "paddle/fluid/inference/tensorrt/convert/op_converter.h" | ||
#include "paddle/fluid/inference/tensorrt/convert/ut_helper.h" | ||
|
||
namespace paddle { | ||
namespace inference { | ||
namespace tensorrt { | ||
|
||
TEST(fc_op, test) { | ||
std::unordered_set<std::string> parameters({"mul-Y"}); | ||
framework::Scope scope; | ||
TRTConvertValidation validator(20, parameters, scope, 1000); | ||
|
||
validator.DeclInputVar("mul-X", nvinfer1::Dims4(8, 3, 1, 1)); | ||
validator.DeclParamVar("mul-Y", nvinfer1::Dims2(3, 2)); | ||
validator.DeclOutputVar("mul-Out", nvinfer1::Dims2(8, 2)); | ||
|
||
// Prepare Op description | ||
framework::OpDesc desc; | ||
desc.SetType("mul"); | ||
desc.SetInput("X", {"mul-X"}); | ||
desc.SetInput("Y", {"mul-Y"}); | ||
desc.SetOutput("Out", {"mul-Out"}); | ||
|
||
validator.SetOp(*desc.Proto()); | ||
|
||
validator.Execute(10); | ||
} | ||
|
||
} // namespace tensorrt | ||
} // namespace inference | ||
} // namespace paddle |
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 |
---|---|---|
|
@@ -61,7 +61,10 @@ class TRTConvertValidation { | |
public: | ||
TRTConvertValidation() = delete; | ||
|
||
explicit TRTConvertValidation(int batch_size, int workspace_size = 1024) { | ||
TRTConvertValidation(int batch_size, | ||
const std::unordered_set<std::string>& parameters, | ||
framework::Scope& scope, int workspace_size = 1 << 10) | ||
: parameters_(parameters), scope_(scope) { | ||
// create engine. | ||
engine_.reset(new TensorRTEngine(10, 1 << 10, &stream_)); | ||
engine_->InitNetwork(); | ||
|
@@ -76,19 +79,22 @@ class TRTConvertValidation { | |
engine_->DeclareInput(name, nvinfer1::DataType::kFLOAT, dims); | ||
} | ||
|
||
// Declare a parameter varaible in the scope. | ||
void DeclParamVar(const std::string& name, const nvinfer1::Dims& dims) { | ||
DeclVar(name, dims); | ||
} | ||
|
||
void DeclOutputVar(const std::string& name, const nvinfer1::Dims& dims) { | ||
DeclVar(name, dims); | ||
} | ||
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. DeclParamVar和DeclOutputVar是一模一样的,需要封两个函数么? 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. 用的时候的确需要不同语义,这里区分下 program 和 output, 不然代码里两处都是 |
||
|
||
// Declare a variable in a fluid Scope. | ||
void DeclVar(const std::string& name, const nvinfer1::Dims& dims) { | ||
platform::CPUPlace place; | ||
platform::CPUDeviceContext ctx(place); | ||
|
||
// Init Fluid tensor. | ||
std::vector<int> dim_vec(dims.nbDims); | ||
for (int i = 0; i < dims.nbDims; i++) { | ||
dim_vec[i] = dims.d[i]; | ||
} | ||
std::vector<int> dim_vec(dims.d, dims.d + dims.nbDims); | ||
auto* x = scope_.Var(name); | ||
auto* x_tensor = x->GetMutable<framework::LoDTensor>(); | ||
x_tensor->Resize(framework::make_ddim(dim_vec)); | ||
|
@@ -99,7 +105,7 @@ class TRTConvertValidation { | |
op_ = framework::OpRegistry::CreateOp(desc); | ||
|
||
OpConverter op_converter; | ||
op_converter.ConvertOp(desc, engine_.get()); | ||
op_converter.ConvertOp(desc, parameters_, scope_, engine_.get()); | ||
|
||
engine_->FreezeNetwork(); | ||
|
||
|
@@ -108,38 +114,43 @@ class TRTConvertValidation { | |
|
||
// Set Inputs. | ||
for (const auto& input : op_desc_->InputArgumentNames()) { | ||
if (parameters_.count(input)) continue; | ||
auto* var = scope_.FindVar(input); | ||
PADDLE_ENFORCE(var); | ||
auto tensor = var->GetMutable<framework::LoDTensor>(); | ||
|
||
engine_->SetInputFromCPU( | ||
input, static_cast<void*>(tensor->data<float>()), | ||
input, static_cast<void*>(tensor->data<void>()), | ||
sizeof(float) * | ||
analysis::AccuDims(tensor->dims(), tensor->dims().size())); | ||
} | ||
} | ||
|
||
void Execute(int batch_size) { | ||
// Execute Fluid Op | ||
// Execute TRT | ||
platform::CPUPlace place; | ||
platform::CPUDeviceContext ctx(place); | ||
engine_->Execute(batch_size); | ||
|
||
op_->Run(scope_, place); | ||
// Execute TRT. | ||
engine_->Execute(batch_size); | ||
cudaStreamSynchronize(*engine_->stream()); | ||
|
||
ASSERT_FALSE(op_desc_->OutputArgumentNames().empty()); | ||
const size_t output_space_size = 200; | ||
for (const auto& output : op_desc_->OutputArgumentNames()) { | ||
std::vector<float> fluid_out; | ||
std::vector<float> trt_out(200); | ||
engine_->GetOutputInCPU(output, &trt_out[0], 200 * sizeof(float)); | ||
std::vector<float> trt_out(output_space_size); | ||
engine_->GetOutputInCPU(output, &trt_out[0], | ||
output_space_size * sizeof(float)); | ||
cudaStreamSynchronize(*engine_->stream()); | ||
|
||
auto* var = scope_.FindVar(output); | ||
auto tensor = var->GetMutable<framework::LoDTensor>(); | ||
framework::TensorToVector(*tensor, ctx, &fluid_out); | ||
// Compare two output | ||
ASSERT_FALSE(fluid_out.empty()); | ||
for (size_t i = 0; i < fluid_out.size(); i++) { | ||
EXPECT_LT(std::abs(fluid_out[i] - trt_out[i]), 0.001); | ||
EXPECT_LT(std::abs(fluid_out[i] - trt_out[i]), 1e-6); | ||
} | ||
} | ||
} | ||
|
@@ -149,9 +160,10 @@ class TRTConvertValidation { | |
private: | ||
std::unique_ptr<TensorRTEngine> engine_; | ||
cudaStream_t stream_; | ||
framework::Scope scope_; | ||
std::unique_ptr<framework::OperatorBase> op_; | ||
std::unique_ptr<framework::OpDesc> op_desc_; | ||
const std::unordered_set<std::string>& parameters_; | ||
framework::Scope& scope_; | ||
}; | ||
|
||
} // namespace tensorrt | ||
|
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.
从函数实现看,odata[i] = idata[i],所以还需要转么?
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.
从 TF 里拷贝的,试了下,很奇怪,这个函数好像必须要用。还有一个 Reorder4的函数,后面用到的时候我再仔细看下。
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.
后面写Reorder4的时候,可以这里再优化下: