elementwise_op.cc 16.1 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
                  const framework::Scope& scope,
                  bool test_mode) override {
28
    VLOG(3) << "Convert a 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
    if (Y_v) {
      // Y is weight
35
      auto* Y_t = Y_v->GetMutable<phi::DenseTensor>();
36
      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
    int axis = -1;
78
    // axis here is relative to explicit batch
79 80 81 82
    if (op_type_ != "logical_or" && op_type_ != "logical_xor" &&
        op_type_ != "logical_and") {
      axis = PADDLE_GET_CONST(int, op_desc.GetAttr("axis"));
    }
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 110 111 112 113
    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 已提交
114
        }
115 116 117 118 119
        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});
120
        }
121 122
        reshape_layer = TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *Y);
        reshape_layer->setInput(1, *new_y_shape_tensor);
123
      } else {
124 125 126 127 128 129 130
        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);
131
      }
132
      reshape_y_tensor = reshape_layer->getOutput(0);
N
nhzlx 已提交
133
    } else {
134 135 136
      // In fact , we can remove this `else`, but -> rt_resnet50_test CI in trt
      // 6015 faling, how ridiculous!
      reshape_y_tensor = Y;
N
nhzlx 已提交
137
    }
138

139 140 141 142 143 144 145
    // 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;
    }

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    if (op_type_ == "less_equal") {
      auto* less_layer =
          TRT_ENGINE_ADD_LAYER(engine_,
                               ElementWise,
                               *X,
                               *reshape_y_tensor,
                               nvinfer1::ElementWiseOperation::kLESS);
      auto* equal_layer =
          TRT_ENGINE_ADD_LAYER(engine_,
                               ElementWise,
                               *X,
                               *reshape_y_tensor,
                               nvinfer1::ElementWiseOperation::kEQUAL);
      auto* layer = TRT_ENGINE_ADD_LAYER(engine_,
                                         ElementWise,
                                         *(less_layer->getOutput(0)),
                                         *(equal_layer->getOutput(0)),
                                         nvinfer1::ElementWiseOperation::kOR);

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
      RreplenishLayerAndOutput(layer, "elementwise", {output_name}, test_mode);
    } else if (op_type_ == "greater_equal") {
      auto* greater_layer =
          TRT_ENGINE_ADD_LAYER(engine_,
                               ElementWise,
                               *X,
                               *reshape_y_tensor,
                               nvinfer1::ElementWiseOperation::kGREATER);
      auto* equal_layer =
          TRT_ENGINE_ADD_LAYER(engine_,
                               ElementWise,
                               *X,
                               *reshape_y_tensor,
                               nvinfer1::ElementWiseOperation::kEQUAL);
      auto* layer = TRT_ENGINE_ADD_LAYER(engine_,
                                         ElementWise,
                                         *(greater_layer->getOutput(0)),
                                         *(equal_layer->getOutput(0)),
                                         nvinfer1::ElementWiseOperation::kOR);

185
      RreplenishLayerAndOutput(layer, "elementwise", {output_name}, test_mode);
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    } else if (op_type_ == "mod") {
      auto* div_layer =
          TRT_ENGINE_ADD_LAYER(engine_,
                               ElementWise,
                               *X,
                               *reshape_y_tensor,
                               nvinfer1::ElementWiseOperation::kFLOOR_DIV);
      auto* mul_layer =
          TRT_ENGINE_ADD_LAYER(engine_,
                               ElementWise,
                               *(div_layer->getOutput(0)),
                               *reshape_y_tensor,
                               nvinfer1::ElementWiseOperation::kPROD);
      auto* layer = TRT_ENGINE_ADD_LAYER(engine_,
                                         ElementWise,
                                         *X,
                                         *(mul_layer->getOutput(0)),
                                         nvinfer1::ElementWiseOperation::kSUB);
      RreplenishLayerAndOutput(layer, "elementwise", {output_name}, test_mode);
205 206 207 208 209 210 211 212 213 214 215 216 217 218
    } else {
      auto op_pair = ops.find(op_type_);
      PADDLE_ENFORCE_NE(
          op_pair,
          ops.end(),
          platform::errors::InvalidArgument(
              "Elementwise op's type(%s) is not supported. Please "
              "check if the op_type is correct.",
              op_type_));

      auto* layer = TRT_ENGINE_ADD_LAYER(
          engine_, ElementWise, *X, *reshape_y_tensor, op_pair->second);
      RreplenishLayerAndOutput(layer, "elementwise", {output_name}, test_mode);
    }
N
nhzlx 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
  }

 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},
W
wenbin 已提交
236
        {"floordiv", nvinfer1::ElementWiseOperation::kFLOOR_DIV},
237 238 239 240 241
        {"less_than", nvinfer1::ElementWiseOperation::kLESS},
        {"greater_than", nvinfer1::ElementWiseOperation::kGREATER},
        {"logical_or", nvinfer1::ElementWiseOperation::kOR},
        {"logical_xor", nvinfer1::ElementWiseOperation::kXOR},
        {"logical_and", nvinfer1::ElementWiseOperation::kAND},
N
nhzlx 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
};

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"; }
};
W
wenbin 已提交
278 279 280 281 282
class ElementwiseTensorFloorDivOpConverter
    : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorFloorDivOpConverter() { op_type_ = "floordiv"; }
};
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
class ElementwiseTensorLessThanOpConverter
    : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorLessThanOpConverter() { op_type_ = "less_than"; }
};
class ElementwiseTensorGreaterThanOpConverter
    : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorGreaterThanOpConverter() { op_type_ = "greater_than"; }
};
class ElementwiseTensorLogicalOrOpConverter
    : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorLogicalOrOpConverter() { op_type_ = "logical_or"; }
};
class ElementwiseTensorLogicalXorOpConverter
    : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorLogicalXorOpConverter() { op_type_ = "logical_xor"; }
};
class ElementwiseTensorLogicalAndOpConverter
    : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorLogicalAndOpConverter() { op_type_ = "logical_and"; }
};
class ElementwiseTensorLessEqualOpConverter
    : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorLessEqualOpConverter() { op_type_ = "less_equal"; }
};
313 314 315 316 317
class ElementwiseTensorGreaterEqualOpConverter
    : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorGreaterEqualOpConverter() { op_type_ = "greater_equal"; }
};
318 319 320 321
class ElementwiseTensorModOpConverter : public ElementwiseTensorOpConverter {
 public:
  ElementwiseTensorModOpConverter() { op_type_ = "mod"; }
};
W
Wilber 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

// The diff between `pow` and `elementwise_pow` is in:
// https://github.com/PaddlePaddle/Paddle/blob/release/2.4/python/paddle/tensor/math.py#L420
class PowOpConverter : public OpConverter {
 public:
  PowOpConverter() {}
  void operator()(const framework::proto::OpDesc& op,
                  const framework::Scope& scope,
                  bool test_mode) override {
    VLOG(3) << "Convert a pow op to TensorRT IElementWiseLayer";
    framework::OpDesc op_desc(op, nullptr);
    auto* X = engine_->GetITensor(op_desc.Input("X").front());
    float factor = PADDLE_GET_CONST(float, op_desc.GetAttr("factor"));
    nvinfer1::Dims dims_x = X->getDimensions();
    auto output_name = op_desc.Output("Out")[0];

    nvinfer1::Dims trt_dims_y;
    trt_dims_y.nbDims = dims_x.nbDims;
    for (int i = 0; i < trt_dims_y.nbDims; i++) {
      trt_dims_y.d[i] = 1;
    }

    std::vector<float> w_data{factor};
    auto* Y = AddConstantLayer(w_data.data(), trt_dims_y);

    auto* layer = TRT_ENGINE_ADD_LAYER(
        engine_, ElementWise, *X, *Y, nvinfer1::ElementWiseOperation::kPOW);
    RreplenishLayerAndOutput(layer, "elementwise", {output_name}, test_mode);
  }
};

N
nhzlx 已提交
353 354 355 356
}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle

357
REGISTER_TRT_OP_CONVERTER(elementwise_add_weight,
358
                          ElementwiseTensorAddOpConverter);
359
REGISTER_TRT_OP_CONVERTER(elementwise_mul_weight,
360
                          ElementwiseTensorMulOpConverter);
S
shentanyue 已提交
361
REGISTER_TRT_OP_CONVERTER(elementwise_sub_weight,
362
                          ElementwiseTensorSubOpConverter);
S
shentanyue 已提交
363
REGISTER_TRT_OP_CONVERTER(elementwise_div_weight,
364
                          ElementwiseTensorDivOpConverter);
365 366 367 368
REGISTER_TRT_OP_CONVERTER(elementwise_max_weight,
                          ElementwiseTensorMaxOpConverter);
REGISTER_TRT_OP_CONVERTER(elementwise_min_weight,
                          ElementwiseTensorMinOpConverter);
S
shentanyue 已提交
369
REGISTER_TRT_OP_CONVERTER(elementwise_pow_weight,
370
                          ElementwiseTensorPowOpConverter);
W
wenbin 已提交
371 372
REGISTER_TRT_OP_CONVERTER(elementwise_floordiv_weight,
                          ElementwiseTensorFloorDivOpConverter);
373 374
REGISTER_TRT_OP_CONVERTER(elementwise_mod_weight,
                          ElementwiseTensorModOpConverter);
N
nhzlx 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389

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);
W
wenbin 已提交
390 391
REGISTER_TRT_OP_CONVERTER(elementwise_floordiv_tensor,
                          ElementwiseTensorFloorDivOpConverter);
392 393
REGISTER_TRT_OP_CONVERTER(elementwise_mod_tensor,
                          ElementwiseTensorModOpConverter);
394 395 396 397 398 399 400
REGISTER_TRT_OP_CONVERTER(less_than, ElementwiseTensorLessThanOpConverter);
REGISTER_TRT_OP_CONVERTER(greater_than,
                          ElementwiseTensorGreaterThanOpConverter);
REGISTER_TRT_OP_CONVERTER(logical_or, ElementwiseTensorLogicalOrOpConverter);
REGISTER_TRT_OP_CONVERTER(logical_xor, ElementwiseTensorLogicalXorOpConverter);
REGISTER_TRT_OP_CONVERTER(logical_and, ElementwiseTensorLogicalAndOpConverter);
REGISTER_TRT_OP_CONVERTER(less_equal, ElementwiseTensorLessEqualOpConverter);
401 402
REGISTER_TRT_OP_CONVERTER(greater_equal,
                          ElementwiseTensorGreaterEqualOpConverter);
W
Wilber 已提交
403 404

REGISTER_TRT_OP_CONVERTER(pow, PowOpConverter);