elementwise_op.cc 8.9 KB
Newer Older
N
nhzlx 已提交
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

7
    http://www.apache.org/licenses/LICENSE-2.0
N
nhzlx 已提交
8 9 10 11 12 13 14 15

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/inference/tensorrt/convert/op_converter.h"
16
#include "paddle/fluid/inference/tensorrt/plugin/elementwise_op_plugin.h"
N
nhzlx 已提交
17 18 19 20 21

namespace paddle {
namespace inference {
namespace tensorrt {

22
class ElementwiseTensorOpConverter : public OpConverter {
N
nhzlx 已提交
23
 public:
24
  ElementwiseTensorOpConverter() {}
N
nhzlx 已提交
25
  void operator()(const framework::proto::OpDesc& op,
26 27 28
                  const framework::Scope& scope,
                  bool test_mode) override {
    VLOG(3) << "Convert a fluid elementwise op to TensorRT IElementWiseLayer";
N
nhzlx 已提交
29 30
    framework::OpDesc op_desc(op, nullptr);
    auto* X = engine_->GetITensor(op_desc.Input("X").front());
31
    nvinfer1::ITensor* Y = nullptr;
N
nhzlx 已提交
32
    auto* Y_v = scope.FindVar(op_desc.Input("Y").front());
33 34 35 36
    if (Y_v) {
      // Y is weight
      auto* Y_t = Y_v->GetMutable<framework::LoDTensor>();
      std::vector<int> dims_y = phi::vectorize<int>(Y_t->dims());
37 38
      auto y_weight = engine_->GetTrtWeight(op_desc.Input("Y").front(), *Y_t);

39 40 41 42 43
      nvinfer1::Dims trt_dims_y;
      trt_dims_y.nbDims = dims_y.size();
      for (int i = 0; i < trt_dims_y.nbDims; i++) {
        trt_dims_y.d[i] = dims_y[i];
      }
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
      // this is the special case when dims_y includes batch dimension!
      // we need remove batch dimension!
      if (!engine_->with_dynamic_shape() &&
          trt_dims_y.nbDims == (X->getDimensions().nbDims + 1)) {
        trt_dims_y.nbDims--;
        PADDLE_ENFORCE_EQ(trt_dims_y.d[0],
                          1,
                          platform::errors::InvalidArgument(
                              "Elementwise type(%s) op's Y is a weight "
                              "including batch dimension. Please "
                              "check if the 0th dimension equals 1.",
                              op_type_));
        for (int i = 0; i < trt_dims_y.nbDims; i++) {
          trt_dims_y.d[i] = trt_dims_y.d[i + 1];
        }
      }
60 61 62 63 64
      Y = TRT_ENGINE_ADD_LAYER(engine_, Constant, trt_dims_y, y_weight.get())
              ->getOutput(0);
    } else {
      Y = engine_->GetITensor(op_desc.Input("Y").front());
    }
65 66
    bool swap_xy = false;
    // Swap X and Y
67 68 69 70
    if (X->getDimensions().nbDims < Y->getDimensions().nbDims) {
      auto* tmp = X;
      X = Y;
      Y = tmp;
71
      swap_xy = true;
72
    }
73
    nvinfer1::Dims dims_x = X->getDimensions();
74 75
    nvinfer1::Dims dims_y = Y->getDimensions();
    auto output_name = op_desc.Output("Out")[0];
76

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    // axis here is relative to explicit batch
    int axis = BOOST_GET_CONST(int, op_desc.GetAttr("axis"));
    int real_x_rank = dims_x.nbDims;
    int real_y_rank = dims_y.nbDims;
    if (!engine_->with_dynamic_shape()) {
      real_x_rank++;
      real_y_rank++;
      if (Y_v) real_y_rank--;
    }
    if (axis == -1) {
      axis = real_x_rank - real_y_rank;
    }
    if (!engine_->with_dynamic_shape() && axis > 0) {
      axis--;
    }

    // X: - -  -    - - - -
    //        axis
    // Y:      -    - -
    // we need expand Y's rank = X's rank
    int left_one_num = axis;
    int right_one_num = dims_x.nbDims - axis - dims_y.nbDims;
    nvinfer1::IShuffleLayer* reshape_layer;
    nvinfer1::ITensor* reshape_y_tensor;
    if (left_one_num > 0 || right_one_num > 0) {
      if (engine_->with_dynamic_shape()) {
        auto* y_shape_tensor = Shape(Y);
        auto* new_y_shape_tensor = y_shape_tensor;
        if (axis > 0) {
          std::vector<int32_t> left_one(left_one_num, 1);
          auto* left_one_tensor = Add1DConstantLayer(left_one);
          new_y_shape_tensor = Concat(std::vector<nvinfer1::ITensor*>{
              left_one_tensor, new_y_shape_tensor});
S
shentanyue 已提交
110
        }
111 112 113 114 115
        if (right_one_num > 0) {
          std::vector<int32_t> right_one(right_one_num, 1);
          auto* right_one_tensor = Add1DConstantLayer(right_one);
          new_y_shape_tensor = Concat(std::vector<nvinfer1::ITensor*>{
              new_y_shape_tensor, right_one_tensor});
116
        }
117 118
        reshape_layer = TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *Y);
        reshape_layer->setInput(1, *new_y_shape_tensor);
119
      } else {
120 121 122 123 124 125 126
        nvinfer1::Dims new_y_dims;
        new_y_dims.nbDims = left_one_num + dims_y.nbDims + right_one_num;
        for (int i = 0; i < new_y_dims.nbDims; i++) new_y_dims.d[i] = 1;
        for (int i = 0; i < dims_y.nbDims; i++)
          new_y_dims.d[left_one_num + i] = dims_y.d[i];
        reshape_layer = TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *Y);
        reshape_layer->setReshapeDimensions(new_y_dims);
127
      }
128
      reshape_y_tensor = reshape_layer->getOutput(0);
N
nhzlx 已提交
129
    } else {
130 131 132
      // In fact , we can remove this `else`, but -> rt_resnet50_test CI in trt
      // 6015 faling, how ridiculous!
      reshape_y_tensor = Y;
N
nhzlx 已提交
133
    }
134

135 136 137 138 139 140 141
    // We should swap X and Y back, because some operators do not have symmetry
    if (swap_xy) {
      auto* tmp = reshape_y_tensor;
      reshape_y_tensor = X;
      X = tmp;
    }

142
    auto op_pair = ops.find(op_type_);
143 144
    PADDLE_ENFORCE_NE(op_pair,
                      ops.end(),
145 146 147 148
                      platform::errors::InvalidArgument(
                          "Elementwise op's type(%s) is not supported. Please "
                          "check if the op_type is correct.",
                          op_type_));
149

150 151 152
    auto* layer = TRT_ENGINE_ADD_LAYER(
        engine_, ElementWise, *X, *reshape_y_tensor, op_pair->second);
    RreplenishLayerAndOutput(layer, "elementwise", {output_name}, test_mode);
N
nhzlx 已提交
153 154 155 156 157 158 159 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 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  }

 protected:
  static const std::unordered_map<std::string, nvinfer1::ElementWiseOperation>
      ops;
  std::string op_type_;
};

const std::unordered_map<std::string, nvinfer1::ElementWiseOperation>
    ElementwiseTensorOpConverter::ops = {
        {"add", nvinfer1::ElementWiseOperation::kSUM},
        {"mul", nvinfer1::ElementWiseOperation::kPROD},
        {"sub", nvinfer1::ElementWiseOperation::kSUB},
        {"div", nvinfer1::ElementWiseOperation::kDIV},
        {"min", nvinfer1::ElementWiseOperation::kMIN},
        {"pow", nvinfer1::ElementWiseOperation::kPOW},
        {"max", nvinfer1::ElementWiseOperation::kMAX},
};

class ElementwiseTensorAddOpConverter : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorAddOpConverter() { op_type_ = "add"; }
};

class ElementwiseTensorMulOpConverter : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorMulOpConverter() { op_type_ = "mul"; }
};

class ElementwiseTensorSubOpConverter : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorSubOpConverter() { op_type_ = "sub"; }
};

class ElementwiseTensorDivOpConverter : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorDivOpConverter() { op_type_ = "div"; }
};

class ElementwiseTensorMinOpConverter : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorMinOpConverter() { op_type_ = "min"; }
};

class ElementwiseTensorMaxOpConverter : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorMaxOpConverter() { op_type_ = "max"; }
};

class ElementwiseTensorPowOpConverter : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorPowOpConverter() { op_type_ = "pow"; }
};

}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle

211
REGISTER_TRT_OP_CONVERTER(elementwise_add_weight,
212
                          ElementwiseTensorAddOpConverter);
213
REGISTER_TRT_OP_CONVERTER(elementwise_mul_weight,
214
                          ElementwiseTensorMulOpConverter);
S
shentanyue 已提交
215
REGISTER_TRT_OP_CONVERTER(elementwise_sub_weight,
216
                          ElementwiseTensorSubOpConverter);
S
shentanyue 已提交
217
REGISTER_TRT_OP_CONVERTER(elementwise_div_weight,
218
                          ElementwiseTensorDivOpConverter);
S
shentanyue 已提交
219
REGISTER_TRT_OP_CONVERTER(elementwise_pow_weight,
220
                          ElementwiseTensorPowOpConverter);
N
nhzlx 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

REGISTER_TRT_OP_CONVERTER(elementwise_add_tensor,
                          ElementwiseTensorAddOpConverter);
REGISTER_TRT_OP_CONVERTER(elementwise_sub_tensor,
                          ElementwiseTensorSubOpConverter);
REGISTER_TRT_OP_CONVERTER(elementwise_div_tensor,
                          ElementwiseTensorDivOpConverter);
REGISTER_TRT_OP_CONVERTER(elementwise_mul_tensor,
                          ElementwiseTensorMulOpConverter);
REGISTER_TRT_OP_CONVERTER(elementwise_max_tensor,
                          ElementwiseTensorMaxOpConverter);
REGISTER_TRT_OP_CONVERTER(elementwise_min_tensor,
                          ElementwiseTensorMinOpConverter);
REGISTER_TRT_OP_CONVERTER(elementwise_pow_tensor,
                          ElementwiseTensorPowOpConverter);