conv2d_op.cc 7.6 KB
Newer Older
L
Luo Tao 已提交
1 2 3 4 5 6
/* 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

L
Luo Tao 已提交
7
http://www.apache.org/licenses/LICENSE-2.0
L
Luo Tao 已提交
8 9 10 11 12 13 14

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. */

L
Luo Tao 已提交
15
#include "paddle/fluid/inference/tensorrt/convert/op_converter.h"
L
Luo Tao 已提交
16

W
wanghuancoder 已提交
17 18 19
namespace paddle {
namespace framework {
class Scope;
20

W
wanghuancoder 已提交
21 22 23 24 25 26
namespace proto {
class OpDesc;
}  // namespace proto
}  // namespace framework
}  // namespace paddle

L
Luo Tao 已提交
27 28 29 30
namespace paddle {
namespace inference {
namespace tensorrt {

31 32 33 34 35 36 37 38 39 40
template <typename RegistFunc, typename SetDilationFunc>
void ConvertConv2d(TensorRTEngine* engine, const framework::proto::OpDesc& op,
                   const framework::Scope& scope, bool test_mode,
                   RegistFunc fadd_layer, SetDilationFunc fset_dilation,
                   const std::string& name) {
  VLOG(3) << "convert a fluid " << name << " op to tensorrt layer without bias";

  framework::OpDesc op_desc(op, nullptr);

  auto* X = engine->GetITensor(op_desc.Input("Input").front());
41 42 43 44 45
  std::string filter_var_name = op_desc.Input("Filter").front();
  auto* Y_v = scope.FindVar(filter_var_name);
  PADDLE_ENFORCE_NOT_NULL(
      Y_v, platform::errors::NotFound(
               "Can not find %s presistale var in scope.", filter_var_name));
46
  auto* Y_t = Y_v->GetMutable<framework::LoDTensor>();
47
  float* weight_data = nullptr;
48
  bool enable_int8 = op_desc.HasAttr("enable_int8");
49 50 51

  if (enable_int8) {
#if IS_TRT_VERSION_GE(5000)
52
    float in_scale = BOOST_GET_CONST(float, op_desc.GetAttr("Input_scale"));
53 54 55
    engine->SetTensorDynamicRange(X, in_scale);
#endif
  }
56
  weight_data = engine->GetWeightCPUData(op_desc.Input("Filter").front(), Y_t);
57

58 59 60 61 62
  PADDLE_ENFORCE_EQ(Y_t->dims().size(), 4UL,
                    platform::errors::InvalidArgument(
                        "The conv2d filter's dims size should be 4, but got %d",
                        Y_t->dims().size()));

63 64 65 66
  const int n_output = Y_t->dims()[0];
  const int n_input = Y_t->dims()[1];
  const int filter_h = Y_t->dims()[2];
  const int filter_w = Y_t->dims()[3];
67
  const int groups = BOOST_GET_CONST(int, op_desc.GetAttr("groups"));
68
  const std::vector<int> dilations =
69
      BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("dilations"));
70
  const std::vector<int> strides =
71
      BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("strides"));
72
  std::vector<int> paddings =
73
      BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("paddings"));
74 75 76 77
  std::string padding_algorithm = "EXPLICIT";
  if (op_desc.HasAttr("padding_algorithm"))
    padding_algorithm =
        BOOST_GET_CONST(std::string, op_desc.GetAttr("padding_algorithm"));
78 79 80 81 82
  if (padding_algorithm == "VALID") {
    for (size_t i = 0; i < paddings.size(); i++) {
      paddings[i] = 0;
    }
  }
83 84 85 86

  nvinfer1::DimsHW nv_ksize(filter_h, filter_w);
  nvinfer1::DimsHW nv_dilations(dilations[0], dilations[1]);
  nvinfer1::DimsHW nv_strides(strides[0], strides[1]);
87 88 89 90 91 92 93 94 95 96 97 98 99 100
  nvinfer1::DimsHW nv_paddings;
  nvinfer1::Dims nv_pre_paddings;
  nvinfer1::Dims nv_post_paddings;
  if (paddings.size() == 2) {
    nv_paddings.d[0] = paddings[0];
    nv_paddings.d[1] = paddings[1];
  } else {
    nv_pre_paddings.nbDims = 2;
    nv_post_paddings.nbDims = 2;
    nv_pre_paddings.d[0] = paddings[0];
    nv_pre_paddings.d[1] = paddings[2];
    nv_post_paddings.d[0] = paddings[1];
    nv_post_paddings.d[1] = paddings[3];
  }
101 102 103

  TensorRTEngine::Weight weight{nvinfer1::DataType::kFLOAT,
                                static_cast<void*>(weight_data),
104
                                static_cast<size_t>(Y_t->numel())};
105 106 107 108 109 110
  float* bias_data = nullptr;
  size_t bias_size = 0;
  if (op_desc.Type() == "conv2d_fusion") {
    auto* bias_tensor = scope.GetVar(op_desc.Input("Bias").front());
    auto* bias_tensor_data = bias_tensor->GetMutable<framework::LoDTensor>();
    bias_data = engine->GetWeightCPUData(op_desc.Input("Bias").front(),
111
                                         bias_tensor_data);
112 113
    bias_size = static_cast<size_t>(bias_tensor_data->numel());
  }
114

115 116
  TensorRTEngine::Weight bias{nvinfer1::DataType::kFLOAT,
                              static_cast<void*>(bias_data), bias_size};
117 118 119 120 121 122 123 124 125 126 127 128
  // In conv2d_transpose and depthwise_conv2d_transpose,
  // output channels = filter_dims[1] * groups
  auto* layer = (op_desc.Type() == "conv2d_transpose" ||
                 op_desc.Type() == "depthwise_conv2d_transpose")
                    ? fadd_layer(const_cast<nvinfer1::ITensor*>(X),
                                 n_input * groups, nv_ksize, weight, bias)
                    : fadd_layer(const_cast<nvinfer1::ITensor*>(X), n_output,
                                 nv_ksize, weight, bias);

  PADDLE_ENFORCE_NOT_NULL(
      layer, platform::errors::Fatal("TensorRT create conv2d/conv2d_transpose"
                                     " layer failed."));
129
  layer->setStride(nv_strides);
130 131 132 133 134 135 136
  if (paddings.size() == 2) {
    layer->setPadding(nv_paddings);
  } else {
    layer->setPrePadding(nv_pre_paddings);
    layer->setPostPadding(nv_post_paddings);
  }

137
  layer->setNbGroups(groups);
138 139
  if (padding_algorithm == "SAME") {
    layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER);
140 141
    nv_dilations.d[0] = 1;
    nv_dilations.d[1] = 1;
142
  }
143 144 145 146 147 148 149 150
  // set dilations
  fset_dilation(layer, nv_dilations);

  auto output_name = op_desc.Output("Output").front();
  layer->setName((name + " (Output: " + output_name + ")").c_str());
  layer->getOutput(0)->setName(output_name.c_str());
  engine->SetITensor(output_name, layer->getOutput(0));

N
nhzlx 已提交
151
  if (test_mode) {
152 153 154 155
    engine->DeclareOutput(output_name);
  }
}

L
Luo Tao 已提交
156 157
class Conv2dOpConverter : public OpConverter {
 public:
158
  void operator()(const framework::proto::OpDesc& op,
159
                  const framework::Scope& scope, bool test_mode) override {
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    ConvertConv2d(
        engine_, op, scope, test_mode,
        [&](nvinfer1::ITensor* inputs, int n_output, /* Conv output maps */
            nvinfer1::DimsHW& ksize, TensorRTEngine::Weight& weight,
            TensorRTEngine::Weight& bias) -> nvinfer1::IConvolutionLayer* {
          auto* layer =
              TRT_ENGINE_ADD_LAYER(engine_, Convolution, *inputs, n_output,
                                   ksize, weight.get(), bias.get());
          return layer;
        },
        [](nvinfer1::IConvolutionLayer* layer, nvinfer1::DimsHW& dilations) {
          layer->setDilation(dilations);
        },
        "conv2d");
  }
};

class Deconv2dOpConverter : public OpConverter {
 public:
  void operator()(const framework::proto::OpDesc& op,
                  const framework::Scope& scope, bool test_mode) override {
    ConvertConv2d(
        engine_, op, scope, test_mode,
        [&](nvinfer1::ITensor* inputs, int n_output, /* Deconv input maps */
            nvinfer1::DimsHW& ksize, TensorRTEngine::Weight& weight,
            TensorRTEngine::Weight& bias) -> nvinfer1::IDeconvolutionLayer* {
          auto* layer =
187
              TRT_ENGINE_ADD_LAYER(engine_, Deconvolution, *inputs, n_output,
188 189 190 191 192 193
                                   ksize, weight.get(), bias.get());
          return layer;
        },
        [](nvinfer1::IDeconvolutionLayer* layer, nvinfer1::DimsHW& dilations) {
        },
        "conv2d_transpose");
L
Luo Tao 已提交
194 195
  }
};
L
Luo Tao 已提交
196

L
Luo Tao 已提交
197 198 199
}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle
200 201

REGISTER_TRT_OP_CONVERTER(conv2d, Conv2dOpConverter);
202
REGISTER_TRT_OP_CONVERTER(conv2d_fusion, Conv2dOpConverter);
203
REGISTER_TRT_OP_CONVERTER(conv2d_transpose, Deconv2dOpConverter);