scale_op.cc 6.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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

http://www.apache.org/licenses/LICENSE-2.0

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"

W
wanghuancoder 已提交
17 18 19
namespace paddle {
namespace framework {
class Scope;
20

W
wanghuancoder 已提交
21 22 23 24 25 26
namespace proto {
class OpDesc;
}  // namespace proto
}  // namespace framework
}  // namespace paddle

27 28 29 30 31 32 33 34 35 36
namespace paddle {
namespace inference {
namespace tensorrt {

/*
 * ConcatOp
 */
class ScaleOpConverter : public OpConverter {
 public:
  void operator()(const framework::proto::OpDesc& op,
37 38
                  const framework::Scope& scope,
                  bool test_mode) override {
39 40 41 42 43 44 45 46 47 48
    VLOG(3) << "convert a fluid scale op to tensorrt mul layer without bias";

    framework::OpDesc op_desc(op, nullptr);
    // Declare inputs
    std::vector<nvinfer1::ITensor*> itensors;
    std::string input_name = op_desc.Input("X").front();
    std::string out_name = op_desc.Output("Out").front();

    auto input = engine_->GetITensor(input_name);
    bool bias_after_scale =
R
Ruibiao Chen 已提交
49 50 51
        PADDLE_GET_CONST(bool, op_desc.GetAttr("bias_after_scale"));
    float bias = PADDLE_GET_CONST(float, op_desc.GetAttr("bias"));
    float scale = PADDLE_GET_CONST(float, op_desc.GetAttr("scale"));
52
    auto create_weights = [&](float data, std::string type) -> float* {
53
      std::unique_ptr<phi::DenseTensor> tmp_tensor(new phi::DenseTensor());
54 55 56 57 58 59 60 61
      tmp_tensor->Resize({1});
      auto* tmp_data = tmp_tensor->mutable_data<float>(platform::CPUPlace());
      tmp_data[0] = data;
      engine_->SetWeights(out_name + "_scale_op_" + type,
                          std::move(tmp_tensor));
      return tmp_data;
    };

62 63
    int dynamic_shape_offset = engine_->with_dynamic_shape() ? 1 : 0;

64 65 66
    float* bias_ptr = create_weights(bias, "bias");
    float* scale_ptr = create_weights(scale, "scale");

67 68 69 70 71 72
    TensorRTEngine::Weight scale_weights{
        nvinfer1::DataType::kFLOAT, static_cast<void*>(scale_ptr), 1};
    TensorRTEngine::Weight shift_weights{
        nvinfer1::DataType::kFLOAT, static_cast<void*>(bias_ptr), 1};
    TensorRTEngine::Weight power_weights{
        nvinfer1::DataType::kFLOAT, nullptr, 0};
73
    nvinfer1::ILayer* layer = nullptr;
74 75 76 77 78 79

    auto input_dim = input->getDimensions();

    nvinfer1::IShuffleLayer* expand_layer = nullptr;
    nvinfer1::IShuffleLayer* squeeze_layer = nullptr;

80 81 82 83 84 85 86 87 88 89
    if (input_dim.nbDims < 3 + dynamic_shape_offset) {
      nvinfer1::Dims expand_shape;
      expand_shape.nbDims = 3 + dynamic_shape_offset;
      for (int i = 0; i < 3 + dynamic_shape_offset; 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;
        }
      }
90
      expand_layer = TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *input);
91
      expand_layer->setReshapeDimensions(expand_shape);
92
      input = expand_layer->getOutput(0);
93 94 95 96
      expand_layer->getOutput(0)->setName(
          ("before_reshape_out: " + out_name).c_str());
      expand_layer->setName(
          ("Scale: before_reshape (Output: " + out_name + ")").c_str());
97 98
    }

99
    if (bias_after_scale) {
100 101 102 103 104 105 106
      layer = TRT_ENGINE_ADD_LAYER(engine_,
                                   Scale,
                                   *input,
                                   nvinfer1::ScaleMode::kUNIFORM,
                                   shift_weights.get(),
                                   scale_weights.get(),
                                   power_weights.get());
107 108 109
      layer->getOutput(0)->setName(
          ("bias_after_scale_out: " + out_name).c_str());
      layer->setName(("Scale: scale (Output: " + out_name + ")").c_str());
110 111
    } else {
      // add bias
112 113 114 115 116 117 118
      layer = TRT_ENGINE_ADD_LAYER(engine_,
                                   Scale,
                                   *(input),
                                   nvinfer1::ScaleMode::kUNIFORM,
                                   shift_weights.get(),
                                   power_weights.get(),
                                   power_weights.get());
119 120 121
      layer->getOutput(0)->setName(
          ("bias_before_scale:bias_out: " + out_name).c_str());
      layer->setName(("Scale: scale_bias (Output: " + out_name + ")").c_str());
122
      // mul scale
123 124 125 126 127 128 129
      layer = TRT_ENGINE_ADD_LAYER(engine_,
                                   Scale,
                                   *(layer->getOutput(0)),
                                   nvinfer1::ScaleMode::kUNIFORM,
                                   power_weights.get(),
                                   scale_weights.get(),
                                   power_weights.get());
130 131 132
      layer->getOutput(0)->setName(
          ("bias_before_scale:scale_out: " + out_name).c_str());
      layer->setName(("Scale: scale_scale (Output: " + out_name + ")").c_str());
133 134
    }

135 136
    PADDLE_ENFORCE_EQ(layer != nullptr,
                      true,
137 138
                      platform::errors::Fatal("Create scale layer failed."));

139 140 141 142 143 144
    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];
      }
145 146
      squeeze_layer =
          TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *(layer->getOutput(0)));
147
      squeeze_layer->setReshapeDimensions(squeeze_shape);
148
      layer = static_cast<nvinfer1::ILayer*>(squeeze_layer);
149 150 151
      layer->getOutput(0)->setName(("after_reshape_out: " + out_name).c_str());
      layer->setName(
          ("Scale: Shuffle_reshape (Output: " + out_name + ")").c_str());
152
    }
153 154 155 156 157 158 159 160 161
    RreplenishLayerAndOutput(layer, "scale", {out_name}, test_mode);
  }
};

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

REGISTER_TRT_OP_CONVERTER(scale, ScaleOpConverter);