conv2d_op.cc 7.7 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 20 21 22 23 24 25
namespace paddle {
namespace framework {
class Scope;
namespace proto {
class OpDesc;
}  // namespace proto
}  // namespace framework
}  // namespace paddle

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

30 31 32 33 34 35 36 37
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);
38 39 40 41 42 43 44 45 46 47 48 49
  PADDLE_ENFORCE_EQ(op_desc.Input("Input").size(), 1UL,
                    platform::errors::InvalidArgument(
                        "TRT Conv2d expect 1 input, but got %d input.",
                        op_desc.Input("Input").size()));
  PADDLE_ENFORCE_EQ(op_desc.Input("Filter").size(), 1UL,
                    platform::errors::InvalidArgument(
                        "TRT Conv2d expect 1 filter, but got %d filter.",
                        op_desc.Input("Filter").size()));
  PADDLE_ENFORCE_EQ(op_desc.Output("Output").size(), 1UL,
                    platform::errors::InvalidArgument(
                        "TRT Conv2d expect 1 output, but got %d output.",
                        op_desc.Output("Output").size()));
50 51

  auto* X = engine->GetITensor(op_desc.Input("Input").front());
52 53 54 55 56
  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));
57
  auto* Y_t = Y_v->GetMutable<framework::LoDTensor>();
58
  float* weight_data = nullptr;
59
  bool enable_int8 = op_desc.HasAttr("enable_int8");
60 61 62

  if (enable_int8) {
#if IS_TRT_VERSION_GE(5000)
63 64 65 66 67 68 69
    if (op_desc.Type() != "conv2d_transpose") {
      PADDLE_ENFORCE_EQ(
          op_desc.HasAttr("Input_scale"), true,
          platform::errors::InvalidArgument("Input scale not found. TRT int8"
                                            " requires conv/deconv to have "
                                            "input quantization scales."));
    }
70 71
    float in_scale =
        BOOST_GET_CONST(float, op_desc.GetAttr("Input_scale")) * 127;
72
    auto weight_scale =
73
        BOOST_GET_CONST(std::vector<float>, op_desc.GetAttr("weight_scale"));
74 75 76 77 78 79 80 81
    weight_data = engine->GetWeightCPUData(op_desc.Input("Filter").front(), Y_t,
                                           true, weight_scale);
    engine->SetTensorDynamicRange(X, in_scale);
#endif
  } else {
    weight_data =
        engine->GetWeightCPUData(op_desc.Input("Filter").front(), Y_t, false);
  }
82

83 84 85 86 87
  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()));

88 89 90 91
  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];
92
  const int groups = BOOST_GET_CONST(int, op_desc.GetAttr("groups"));
93
  const std::vector<int> dilations =
94
      BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("dilations"));
95
  const std::vector<int> strides =
96
      BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("strides"));
97
  const std::vector<int> paddings =
98
      BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("paddings"));
99 100 101 102 103 104 105 106

  nvinfer1::DimsHW nv_ksize(filter_h, filter_w);
  nvinfer1::DimsHW nv_dilations(dilations[0], dilations[1]);
  nvinfer1::DimsHW nv_strides(strides[0], strides[1]);
  nvinfer1::DimsHW nv_paddings(paddings[0], paddings[1]);

  TensorRTEngine::Weight weight{nvinfer1::DataType::kFLOAT,
                                static_cast<void*>(weight_data),
107
                                static_cast<size_t>(Y_t->numel())};
108 109 110 111

  TensorRTEngine::Weight bias{nvinfer1::DataType::kFLOAT, nullptr, 0};
  auto* layer = fadd_layer(const_cast<nvinfer1::ITensor*>(X), n_output, n_input,
                           nv_ksize, weight, bias);
S
Shang Zhizhou 已提交
112 113 114
  PADDLE_ENFORCE_NOT_NULL(layer,
                          platform::errors::Fatal("TensorRT create conv2d"
                                                  " layer error."));
115 116 117 118 119 120 121 122 123 124 125
  layer->setStride(nv_strides);
  layer->setPadding(nv_paddings);
  layer->setNbGroups(groups);
  // 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 已提交
126
  if (test_mode) {
127 128 129 130
    engine->DeclareOutput(output_name);
  }
}

L
Luo Tao 已提交
131 132
class Conv2dOpConverter : public OpConverter {
 public:
133
  void operator()(const framework::proto::OpDesc& op,
134
                  const framework::Scope& scope, bool test_mode) override {
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    ConvertConv2d(
        engine_, op, scope, test_mode,
        [&](nvinfer1::ITensor* inputs, int n_output, /* Conv output maps */
            int n_input,                             /* Conv input 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 */
            int n_input,                             /* Deconv output maps */
            nvinfer1::DimsHW& ksize, TensorRTEngine::Weight& weight,
            TensorRTEngine::Weight& bias) -> nvinfer1::IDeconvolutionLayer* {
          auto* layer =
              TRT_ENGINE_ADD_LAYER(engine_, Deconvolution, *inputs, n_input,
                                   ksize, weight.get(), bias.get());
          return layer;
        },
        [](nvinfer1::IDeconvolutionLayer* layer, nvinfer1::DimsHW& dilations) {
169 170 171 172 173 174 175 176
          // In trt Deconv, dilation should be 1, ohter values are not
          // supported.
          bool condition = (dilations.d[0] == 1 && dilations.d[1] == 1);
          PADDLE_ENFORCE_EQ(condition, true,
                            platform::errors::InvalidArgument(
                                "In Deconv, Dilations must be (1, 1) for "
                                "tensorRT, but given (%d, %d)",
                                dilations.d[0], dilations.d[1]));
177 178
        },
        "conv2d_transpose");
L
Luo Tao 已提交
179 180
  }
};
L
Luo Tao 已提交
181

L
Luo Tao 已提交
182 183 184
}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle
185 186

REGISTER_TRT_OP_CONVERTER(conv2d, Conv2dOpConverter);
187
REGISTER_TRT_OP_CONVERTER(conv2d_transpose, Deconv2dOpConverter);