conv2d_op.cc 8.2 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"
16 17
#include "paddle/fluid/inference/tensorrt/engine.h"
#include "paddle/phi/common/data_type.h"
L
Luo Tao 已提交
18

W
wanghuancoder 已提交
19 20 21
namespace paddle {
namespace framework {
class Scope;
22

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

L
Luo Tao 已提交
29 30 31 32
namespace paddle {
namespace inference {
namespace tensorrt {

33
template <typename RegistFunc, typename SetDilationFunc>
34 35 36 37 38 39
void ConvertConv2d(TensorRTEngine* engine,
                   const framework::proto::OpDesc& op,
                   const framework::Scope& scope,
                   bool test_mode,
                   RegistFunc fadd_layer,
                   SetDilationFunc fset_dilation,
40 41 42 43 44 45
                   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());
46 47 48
  std::string filter_var_name = op_desc.Input("Filter").front();
  auto* Y_v = scope.FindVar(filter_var_name);
  PADDLE_ENFORCE_NOT_NULL(
49 50 51
      Y_v,
      platform::errors::NotFound("Can not find %s presistale var in scope.",
                                 filter_var_name));
52
  auto* Y_t = Y_v->GetMutable<framework::LoDTensor>();
53

54
  bool enable_int8 = op_desc.HasAttr("enable_int8");
55 56 57

  if (enable_int8) {
#if IS_TRT_VERSION_GE(5000)
58
    float in_scale = BOOST_GET_CONST(float, op_desc.GetAttr("Input_scale"));
59 60 61
    engine->SetTensorDynamicRange(X, in_scale);
#endif
  }
62

63 64
  PADDLE_ENFORCE_EQ(Y_t->dims().size(),
                    4UL,
65 66 67 68
                    platform::errors::InvalidArgument(
                        "The conv2d filter's dims size should be 4, but got %d",
                        Y_t->dims().size()));

69 70 71 72
  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];
73
  const int groups = BOOST_GET_CONST(int, op_desc.GetAttr("groups"));
74
  const std::vector<int> dilations =
75
      BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("dilations"));
76
  const std::vector<int> strides =
77
      BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("strides"));
78
  std::vector<int> paddings =
79
      BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("paddings"));
80 81 82 83
  std::string padding_algorithm = "EXPLICIT";
  if (op_desc.HasAttr("padding_algorithm"))
    padding_algorithm =
        BOOST_GET_CONST(std::string, op_desc.GetAttr("padding_algorithm"));
84 85 86 87 88
  if (padding_algorithm == "VALID") {
    for (size_t i = 0; i < paddings.size(); i++) {
      paddings[i] = 0;
    }
  }
89 90 91 92

  nvinfer1::DimsHW nv_ksize(filter_h, filter_w);
  nvinfer1::DimsHW nv_dilations(dilations[0], dilations[1]);
  nvinfer1::DimsHW nv_strides(strides[0], strides[1]);
93 94 95 96 97 98 99 100 101 102 103 104 105 106
  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];
  }
107

108 109 110 111 112 113
  auto weight = engine->GetTrtWeight(op_desc.Input("Filter").front(), *Y_t);

  TensorRTEngine::Weight bias;
  bias.SetDataType(weight.get().type);
  bias.SetCount(0);
  bias.SetValues(nullptr);
114 115 116
  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>();
117 118
    bias =
        engine->GetTrtWeight(op_desc.Input("Bias").front(), *bias_tensor_data);
119
  }
120

121 122 123 124 125
  // 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),
126 127 128 129 130 131 132 133 134
                                 n_input * groups,
                                 nv_ksize,
                                 weight,
                                 bias)
                    : fadd_layer(const_cast<nvinfer1::ITensor*>(X),
                                 n_output,
                                 nv_ksize,
                                 weight,
                                 bias);
135 136

  PADDLE_ENFORCE_NOT_NULL(
137 138 139
      layer,
      platform::errors::Fatal("TensorRT create conv2d/conv2d_transpose"
                              " layer failed."));
140
  layer->setStride(nv_strides);
141 142 143 144 145 146 147
  if (paddings.size() == 2) {
    layer->setPadding(nv_paddings);
  } else {
    layer->setPrePadding(nv_pre_paddings);
    layer->setPostPadding(nv_post_paddings);
  }

148
  layer->setNbGroups(groups);
149 150
  if (padding_algorithm == "SAME") {
    layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER);
151 152
    nv_dilations.d[0] = 1;
    nv_dilations.d[1] = 1;
153
  }
154 155 156 157 158 159 160 161
  // 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 已提交
162
  if (test_mode) {
163 164 165 166
    engine->DeclareOutput(output_name);
  }
}

L
Luo Tao 已提交
167 168
class Conv2dOpConverter : public OpConverter {
 public:
169
  void operator()(const framework::proto::OpDesc& op,
170 171
                  const framework::Scope& scope,
                  bool test_mode) override {
172
    ConvertConv2d(
173 174 175 176 177 178 179 180
        engine_,
        op,
        scope,
        test_mode,
        [&](nvinfer1::ITensor* inputs,
            int n_output, /* Conv output maps */
            nvinfer1::DimsHW& ksize,
            TensorRTEngine::Weight& weight,
181
            TensorRTEngine::Weight& bias) -> nvinfer1::IConvolutionLayer* {
182 183 184 185 186 187 188
          auto* layer = TRT_ENGINE_ADD_LAYER(engine_,
                                             Convolution,
                                             *inputs,
                                             n_output,
                                             ksize,
                                             weight.get(),
                                             bias.get());
189 190 191 192 193 194 195 196 197 198 199 200
          return layer;
        },
        [](nvinfer1::IConvolutionLayer* layer, nvinfer1::DimsHW& dilations) {
          layer->setDilation(dilations);
        },
        "conv2d");
  }
};

class Deconv2dOpConverter : public OpConverter {
 public:
  void operator()(const framework::proto::OpDesc& op,
201 202
                  const framework::Scope& scope,
                  bool test_mode) override {
203
    ConvertConv2d(
204 205 206 207 208 209 210 211
        engine_,
        op,
        scope,
        test_mode,
        [&](nvinfer1::ITensor* inputs,
            int n_output, /* Deconv input maps */
            nvinfer1::DimsHW& ksize,
            TensorRTEngine::Weight& weight,
212
            TensorRTEngine::Weight& bias) -> nvinfer1::IDeconvolutionLayer* {
213 214 215 216 217 218 219
          auto* layer = TRT_ENGINE_ADD_LAYER(engine_,
                                             Deconvolution,
                                             *inputs,
                                             n_output,
                                             ksize,
                                             weight.get(),
                                             bias.get());
220 221 222 223 224
          return layer;
        },
        [](nvinfer1::IDeconvolutionLayer* layer, nvinfer1::DimsHW& dilations) {
        },
        "conv2d_transpose");
L
Luo Tao 已提交
225 226
  }
};
L
Luo Tao 已提交
227

L
Luo Tao 已提交
228 229 230
}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle
231 232

REGISTER_TRT_OP_CONVERTER(conv2d, Conv2dOpConverter);
233
REGISTER_TRT_OP_CONVERTER(conv2d_fusion, Conv2dOpConverter);
234
REGISTER_TRT_OP_CONVERTER(conv2d_transpose, Deconv2dOpConverter);