conv2d_op.cc 8.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"
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<phi::DenseTensor>();
53

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

  if (enable_int8) {
#if IS_TRT_VERSION_GE(5000)
R
Ruibiao Chen 已提交
58
    float in_scale = PADDLE_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];
R
Ruibiao Chen 已提交
73
  const int groups = PADDLE_GET_CONST(int, op_desc.GetAttr("groups"));
74
  const std::vector<int> dilations =
R
Ruibiao Chen 已提交
75
      PADDLE_GET_CONST(std::vector<int>, op_desc.GetAttr("dilations"));
76
  const std::vector<int> strides =
R
Ruibiao Chen 已提交
77
      PADDLE_GET_CONST(std::vector<int>, op_desc.GetAttr("strides"));
78
  std::vector<int> paddings =
R
Ruibiao Chen 已提交
79
      PADDLE_GET_CONST(std::vector<int>, op_desc.GetAttr("paddings"));
80 81 82 83 84 85
  // for conv2d_transpose
  std::vector<int> output_padding;
  if (op_desc.HasAttr("output_padding")) {
    output_padding =
        PADDLE_GET_CONST(std::vector<int>, op_desc.GetAttr("output_padding"));
  }
86 87 88
  std::string padding_algorithm = "EXPLICIT";
  if (op_desc.HasAttr("padding_algorithm"))
    padding_algorithm =
R
Ruibiao Chen 已提交
89
        PADDLE_GET_CONST(std::string, op_desc.GetAttr("padding_algorithm"));
90 91 92 93 94
  if (padding_algorithm == "VALID") {
    for (size_t i = 0; i < paddings.size(); i++) {
      paddings[i] = 0;
    }
  }
95 96 97 98

  nvinfer1::DimsHW nv_ksize(filter_h, filter_w);
  nvinfer1::DimsHW nv_dilations(dilations[0], dilations[1]);
  nvinfer1::DimsHW nv_strides(strides[0], strides[1]);
99 100
  nvinfer1::DimsHW nv_pre_paddings;
  nvinfer1::DimsHW nv_post_paddings;
101
  if (paddings.size() == 2) {
102 103 104 105
    nv_pre_paddings.d[0] = paddings[0];
    nv_pre_paddings.d[1] = paddings[1];
    nv_post_paddings.d[0] = paddings[0];
    nv_post_paddings.d[1] = paddings[1];
106 107 108 109 110 111
  } else {
    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];
  }
112

113 114 115 116 117 118
  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);
119 120
  if (op_desc.Type() == "conv2d_fusion") {
    auto* bias_tensor = scope.GetVar(op_desc.Input("Bias").front());
121
    auto* bias_tensor_data = bias_tensor->GetMutable<phi::DenseTensor>();
122 123
    bias =
        engine->GetTrtWeight(op_desc.Input("Bias").front(), *bias_tensor_data);
124
  }
125

126 127 128 129 130
  // 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),
131 132 133 134 135 136 137 138 139
                                 n_input * groups,
                                 nv_ksize,
                                 weight,
                                 bias)
                    : fadd_layer(const_cast<nvinfer1::ITensor*>(X),
                                 n_output,
                                 nv_ksize,
                                 weight,
                                 bias);
140 141

  PADDLE_ENFORCE_NOT_NULL(
142 143 144
      layer,
      platform::errors::Fatal("TensorRT create conv2d/conv2d_transpose"
                              " layer failed."));
145 146
  layer->setStrideNd(nv_strides);

147 148 149 150 151 152 153 154
  layer->setPrePadding(nv_pre_paddings);
  if (output_padding.size() > 0) {
    nv_post_paddings.d[0] -= output_padding[0];
    nv_post_paddings.d[1] -= output_padding[1];
  }
  if (nv_post_paddings.d[0] < 0 || nv_post_paddings.d[1] < 0) {
    PADDLE_THROW(platform::errors::Fatal(
        "The value in conv2d_transpose's PostPadding should be >= 0."));
155
  }
156
  layer->setPostPadding(nv_post_paddings);
157

158
  layer->setNbGroups(groups);
159 160
  if (padding_algorithm == "SAME") {
    layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER);
161 162
    nv_dilations.d[0] = 1;
    nv_dilations.d[1] = 1;
163
  }
164 165 166 167 168 169 170 171
  // 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 已提交
172
  if (test_mode) {
173 174 175 176
    engine->DeclareOutput(output_name);
  }
}

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

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

L
Luo Tao 已提交
238 239 240
}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle
241 242

REGISTER_TRT_OP_CONVERTER(conv2d, Conv2dOpConverter);
243
REGISTER_TRT_OP_CONVERTER(conv2d_fusion, Conv2dOpConverter);
244
REGISTER_TRT_OP_CONVERTER(conv2d_transpose, Deconv2dOpConverter);