elementwise_op.cc 13.4 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 23 24 25 26 27 28 29 30 31 32 33 34
static bool CheckDims(const nvinfer1::Dims& dims_x,
                      const nvinfer1::Dims& dims_y) {
  if (dims_x.nbDims != dims_y.nbDims) {
    return false;
  }
  for (int i = 0; i < dims_x.nbDims; i++) {
    if (dims_x.d[i] != dims_y.d[i]) {
      return false;
    }
  }
  return true;
}

N
nhzlx 已提交
35 36 37 38 39 40 41
class ElementwiseWeightOpConverter : public OpConverter {
 public:
  ElementwiseWeightOpConverter() {}
  void operator()(const framework::proto::OpDesc& op,
                  const framework::Scope& scope, bool test_mode) override {
    // Here the two nullptr looks strange, that's because the
    // framework::OpDesc's constructor is strange.
42
    nvinfer1::ILayer* layer = nullptr;
N
nhzlx 已提交
43
    framework::OpDesc op_desc(op, nullptr);
44
    VLOG(3) << "Convert a fluid elementwise op to TensorRT IScaleLayer";
N
nhzlx 已提交
45 46 47

    auto* X = engine_->GetITensor(op_desc.Input("X").front());
    auto* Y_v = scope.FindVar(op_desc.Input("Y").front());
S
Shang Zhizhou 已提交
48 49 50
    PADDLE_ENFORCE_NOT_NULL(
        Y_v, platform::errors::NotFound("Variable %s not found in scope.",
                                        op_desc.Input("Y").front().c_str()));
N
nhzlx 已提交
51
    auto* Y_t = Y_v->GetMutable<framework::LoDTensor>();
52 53 54
    float* weight_data = nullptr;
    weight_data =
        engine_->GetWeightCPUData(op_desc.Input("Y").front(), Y_t, false);
55 56 57 58 59 60 61 62 63 64
    nvinfer1::Dims dims_x = X->getDimensions();

    auto regist_eltwise_weight = [&](nvinfer1::ScaleMode scale_mode) {
      TensorRTEngine::Weight shift_weights{nvinfer1::DataType::kFLOAT,
                                           static_cast<void*>(weight_data),
                                           static_cast<size_t>(Y_t->numel())};
      TensorRTEngine::Weight scale_weights{nvinfer1::DataType::kFLOAT, nullptr,
                                           0};
      TensorRTEngine::Weight power_weights{nvinfer1::DataType::kFLOAT, nullptr,
                                           0};
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

      nvinfer1::IShuffleLayer* expand_layer = nullptr;
      nvinfer1::IShuffleLayer* squeeze_layer = nullptr;
      int dynamic_shape_offset = engine_->with_dynamic_shape() ? 1 : 0;
      auto input_dim = X->getDimensions();
      if (input_dim.nbDims < 3 + dynamic_shape_offset) {
        nvinfer1::Dims expand_shape;
        expand_shape.nbDims = 3 + dynamic_shape_offset;
        for (int i = 0; i < expand_shape.nbDims; i++) {
          if (i < input_dim.nbDims) {
            expand_shape.d[i] = input_dim.d[i] < 0 ? 0 : input_dim.d[i];
          } else {
            expand_shape.d[i] = 1;
          }
        }
        expand_layer = TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *X);
        expand_layer->setReshapeDimensions(expand_shape);
        X = expand_layer->getOutput(0);
      }
84 85
      if (op_type_ == "add") {
        nvinfer1::IScaleLayer* scale_layer = TRT_ENGINE_ADD_LAYER(
86 87
            engine_, ScaleNd, *X, scale_mode, shift_weights.get(),
            scale_weights.get(), power_weights.get(), dynamic_shape_offset);
88 89 90 91 92 93 94
        layer = scale_layer;
      } else if (op_type_ == "mul") {
        nvinfer1::IScaleLayer* scale_layer = TRT_ENGINE_ADD_LAYER(
            engine_, Scale, *X, scale_mode, scale_weights.get(),
            shift_weights.get(), power_weights.get());
        layer = scale_layer;
      }
95 96 97 98 99 100 101 102 103 104 105
      if (input_dim.nbDims < 3 + dynamic_shape_offset) {
        nvinfer1::Dims squeeze_shape;
        squeeze_shape.nbDims = input_dim.nbDims;
        for (int i = 0; i < squeeze_shape.nbDims; i++) {
          squeeze_shape.d[i] = input_dim.d[i] < 0 ? 0 : input_dim.d[i];
        }
        squeeze_layer =
            TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *(layer->getOutput(0)));
        squeeze_layer->setReshapeDimensions(squeeze_shape);
        layer = static_cast<nvinfer1::ILayer*>(squeeze_layer);
      }
106 107 108 109 110 111
      auto output_name = op_desc.Output("Out")[0];
      RreplenishLayerAndOutput(layer, "elementwise_" + op_type_, {output_name},
                               test_mode);
      if (op_desc.HasAttr("enable_int8")) {
#if IS_TRT_VERSION_GE(5000)
        CHECK(op_desc.HasAttr("X_scale"));
112
        float x_scale = BOOST_GET_CONST(float, op_desc.GetAttr("X_scale"));
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        engine_->SetTensorDynamicRange(X, x_scale);
#endif
      }
    };

    if (engine_->with_dynamic_shape()) {
      if (Y_t->dims().size() == 1) {
        auto scale_mode = nvinfer1::ScaleMode::kCHANNEL;
        PADDLE_ENFORCE_EQ(Y_t->dims()[0], dims_x.d[1],
                          platform::errors::InvalidArgument(
                              "The Bias's size(%d) should be equal to the "
                              "first dim(%d) of the Input.",
                              Y_t->dims()[0], dims_x.d[1]));
        regist_eltwise_weight(scale_mode);
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
129 130 131
            "The size of input bias's dims is %d, but TensorRT dynamic shape "
            "only support size = 1 for Elementwise op!",
            Y_t->dims().size()));
132 133 134 135 136 137 138 139 140
      }
      return;
    }

    std::vector<int> no_batch_dims;
    int start_index = 0;

    for (; start_index < dims_x.nbDims; start_index++)
      no_batch_dims.push_back(dims_x.d[start_index]);
N
nhzlx 已提交
141

N
nhzlx 已提交
142 143
    auto scale_mode = nvinfer1::ScaleMode::kELEMENTWISE;

144
    std::vector<int> dims_y = framework::vectorize<int>(Y_t->dims());
145
    if (dims_y.size() == no_batch_dims.size() + 1) {
N
nhzlx 已提交
146 147 148
      if (dims_y[0] == 1) dims_y.erase(dims_y.begin());
    }

149
    if (dims_y.size() == 1 && dims_y[0] == no_batch_dims[0]) {
N
nhzlx 已提交
150
      scale_mode = nvinfer1::ScaleMode::kCHANNEL;
151 152
    } else if (dims_y.size() == no_batch_dims.size() &&
               dims_y[0] == no_batch_dims[0]) {
N
nhzlx 已提交
153
      scale_mode = nvinfer1::ScaleMode::kELEMENTWISE;
154 155
      for (size_t i = 1; i < no_batch_dims.size(); i++) {
        if (dims_y[i] != no_batch_dims[i]) {
N
nhzlx 已提交
156 157 158 159 160
          scale_mode = nvinfer1::ScaleMode::kCHANNEL;
          break;
        }
      }
      if (scale_mode == nvinfer1::ScaleMode::kCHANNEL) {
161
        for (size_t i = 1; i < no_batch_dims.size(); i++) {
N
nhzlx 已提交
162
          if (dims_y[i] != 1)
163 164 165 166
            PADDLE_THROW(platform::errors::InvalidArgument(
                "The bias's %d dim is %d, but TensorRT dynamic shape only "
                "support it equals to 1 for Elementwise op!",
                i, dims_y[i]));
N
nhzlx 已提交
167 168 169
        }
      }
    } else {
170 171 172 173 174 175 176 177 178 179 180
      if (dims_y.size() >= 1) {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "The size of bias's dims is %d and bias's size is %d. TensorRT "
            "doesn't support this shape for Elementwise op!",
            dims_y.size(), dims_y[0]));
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "The size of bias's dims is %d. TensorRT doesn't support "
            "this shape for Elementwise op!",
            dims_y.size()));
      }
N
nhzlx 已提交
181
    }
182
    regist_eltwise_weight(scale_mode);
N
nhzlx 已提交
183
  }
184 185 186

 protected:
  std::string op_type_;
N
nhzlx 已提交
187 188 189 190 191 192 193
};

class ElementwiseTensorOpConverter : public OpConverter {
 public:
  ElementwiseTensorOpConverter() {}
  void operator()(const framework::proto::OpDesc& op,
                  const framework::Scope& scope, bool test_mode) override {
194
    auto op_pair = ops.find(op_type_);
195 196 197 198 199
    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_));
200

N
nhzlx 已提交
201 202 203
    // Here the two nullptr looks strange, that's because the
    // framework::OpDesc's constructor is strange.
    framework::OpDesc op_desc(op, nullptr);
204
    nvinfer1::ILayer* layer = nullptr;
N
nhzlx 已提交
205 206 207

    auto* X = engine_->GetITensor(op_desc.Input("X").front());
    auto* Y = engine_->GetITensor(op_desc.Input("Y").front());
208 209 210
    std::vector<nvinfer1::ITensor*> itensors;
    itensors.push_back(X);
    itensors.push_back(Y);
N
nhzlx 已提交
211 212 213
    nvinfer1::Dims dims_x = X->getDimensions();
    nvinfer1::Dims dims_y = Y->getDimensions();

214
    int axis = BOOST_GET_CONST(int, op_desc.GetAttr("axis"));
215
    auto output_name = op_desc.Output("Out")[0];
216 217 218 219 220 221 222

    auto common_func = [&](nvinfer1::ILayer* layer) {
      RreplenishLayerAndOutput(layer, "elementwise", {output_name}, test_mode);
      if (op_desc.HasAttr("enable_int8")) {
#if IS_TRT_VERSION_GE(5000)
        CHECK(op_desc.HasAttr("X_scale"));
        CHECK(op_desc.HasAttr("Y_scale"));
223 224
        float x_scale = BOOST_GET_CONST(float, op_desc.GetAttr("X_scale"));
        float y_scale = BOOST_GET_CONST(float, op_desc.GetAttr("Y_scale"));
225 226 227 228 229 230
        engine_->SetTensorDynamicRange(X, x_scale);
        engine_->SetTensorDynamicRange(Y, y_scale);
#endif
      }
    };

231
    if (dims_x.nbDims == dims_y.nbDims) {
232 233
      // The two input tensor should have the same dims
      VLOG(3) << "Convert a fluid elementwise op to TensorRT IElementWiseLayer";
234 235
      nvinfer1::IElementWiseLayer* elet_layer =
          TRT_ENGINE_ADD_LAYER(engine_, ElementWise, *X, *Y, op_pair->second);
N
nhzlx 已提交
236

237
      layer = elet_layer;
238 239 240
    } else {
      VLOG(3) << "Convert a fluid elementwise op to TensorRT "
                 "ElementWisePluginLayer";
241 242 243 244
      if (engine_->with_dynamic_shape()) {
#if IS_TRT_VERSION_GE(6000)
        plugin::ElementwisePluginDynamic* plugin =
            new plugin::ElementwisePluginDynamic(op_type_, axis);
245
        layer = engine_->AddDynamicPlugin(itensors.data(), 2, plugin);
246 247 248 249
#else
        PADDLE_THROW(platform::errors::Fatal(
            "You are running the TRT Dynamic Shape mode, need to confirm that "
            "your TRT version is no less than 6.0"));
250
#endif
251 252 253
      } else {
        plugin::ElementWisePlugin* plugin =
            new plugin::ElementWisePlugin(op_type_, dims_x, dims_y, axis);
254 255 256 257

        std::vector<nvinfer1::ITensor*> inputs{X, Y};
        auto* plugin_layer = engine_->AddPlugin(
            inputs.data(), inputs.size(),
258 259 260 261
            reinterpret_cast<plugin::PluginTensorRT*>(plugin));

        layer = plugin_layer;
      }
N
nhzlx 已提交
262
    }
263
    common_func(layer);
N
nhzlx 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
  }

 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},
};

283 284 285 286 287 288 289 290 291 292
class ElementwiseWeightAddOpConverter : public ElementwiseWeightOpConverter {
 public:
  ElementwiseWeightAddOpConverter() { op_type_ = "add"; }
};

class ElementwiseWeightMulOpConverter : public ElementwiseWeightOpConverter {
 public:
  ElementwiseWeightMulOpConverter() { op_type_ = "mul"; }
};

N
nhzlx 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
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

332 333 334 335
REGISTER_TRT_OP_CONVERTER(elementwise_add_weight,
                          ElementwiseWeightAddOpConverter);
REGISTER_TRT_OP_CONVERTER(elementwise_mul_weight,
                          ElementwiseWeightMulOpConverter);
N
nhzlx 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

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);