fc_op.cc 13.5 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
namespace paddle {
namespace inference {
namespace tensorrt {

/*
 * FC converter convert a MUL op in Fluid to a FC layer in TRT.
 */
class FcOpConverter : public OpConverter {
 public:
36
  nvinfer1::ILayer* reshape_before_fc(nvinfer1::ITensor* before_fc,
W
Wangzheee 已提交
37 38
                                      nvinfer1::Dims x_dim, int x_num_col_dims,
                                      std::string output_name) {
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    // add shuffle before fc
    nvinfer1::Dims reshape_before_fc_dim;
    reshape_before_fc_dim.nbDims = x_num_col_dims + 3;
    // padding shape "* x q x 1 x 1"
    for (int i = 0; i < reshape_before_fc_dim.nbDims; i++) {
      reshape_before_fc_dim.d[i] = 1;
    }
    for (int i = 0; i < x_dim.nbDims; i++) {
      if (i < x_num_col_dims) {
        reshape_before_fc_dim.d[i] = 0;
      } else {
        if (x_dim.d[i] < 0) {
          reshape_before_fc_dim.d[x_num_col_dims] = -1;
          break;
        }
        reshape_before_fc_dim.d[x_num_col_dims] *= x_dim.d[i];
      }
    }
    auto* reshape_before_fc_layer =
        TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *before_fc);
    reshape_before_fc_layer->setReshapeDimensions(reshape_before_fc_dim);
W
Wangzheee 已提交
60 61 62
    reshape_before_fc_layer->setName(
        ("fc_op_reshape_before_fc: Shuffle (Output: " + output_name + ")")
            .c_str());
63 64 65 66 67 68 69
    return reshape_before_fc_layer;
  }

  nvinfer1::ILayer* reshape_after_fc(nvinfer1::ITensor* after_fc,
                                     nvinfer1::Dims x_dim, int x_num_col_dims) {
    // add shuffle after fc
    nvinfer1::Dims reshape_after_fc_dim;
70
    reshape_after_fc_dim.nbDims = x_num_col_dims + 1;
71 72 73 74 75 76 77 78 79
    for (int i = 0; i < reshape_after_fc_dim.nbDims; i++) {
      reshape_after_fc_dim.d[i] = 0;
    }
    auto* reshape_after_fc_layer =
        TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *after_fc);
    reshape_after_fc_layer->setReshapeDimensions(reshape_after_fc_dim);
    return reshape_after_fc_layer;
  }

80
  void operator()(const framework::proto::OpDesc& op,
81
                  const framework::Scope& scope, bool test_mode) override {
82
    VLOG(3) << "convert a fluid fc op to tensorrt fc layer without bias";
Y
Yan Chunwei 已提交
83
    framework::OpDesc op_desc(op, nullptr);
84
    auto output_name = op_desc.Output("Out").front();
85 86 87 88 89 90 91 92
    auto input_names = op_desc.InputNames();
    bool with_bias = input_names.size() >= 3;
    std::string w_name = "Y";
    std::string i_name = "X";
    if (with_bias) {
      w_name = "W";
      i_name = "Input";
    }
93
    // Declare inputs
94
    auto* X = engine_->GetITensor(op_desc.Input(i_name).front());
W
Wangzheee 已提交
95
    auto x_dim = X->getDimensions();
96
    // Declare weights
97
    auto* Y_v = scope.FindVar(op_desc.Input(w_name).front());
98 99 100
    PADDLE_ENFORCE_NOT_NULL(
        Y_v, platform::errors::NotFound(
                 "Can not find %s presistale var of fc in scope.", w_name));
101
    auto* Y_t = Y_v->GetMutable<framework::LoDTensor>();
102
    int x_num_col_dims =
P
Pei Yang 已提交
103
        op_desc.HasAttr("x_num_col_dims")
104
            ? BOOST_GET_CONST(int, op_desc.GetAttr("x_num_col_dims"))
P
Pei Yang 已提交
105
            : (op_desc.HasAttr("in_num_col_dims")
106
                   ? BOOST_GET_CONST(int, op_desc.GetAttr("in_num_col_dims"))
P
Pei Yang 已提交
107 108 109
                   : 1);
    const std::string activation_type =
        op_desc.HasAttr("activation_type")
110
            ? BOOST_GET_CONST(std::string, op_desc.GetAttr("activation_type"))
P
Pei Yang 已提交
111
            : "";
112
    // This may trigger a GPU->CPU copy, because TRT's weight can only be
113
    // assigned from CPU memory, which can't be avoided.
114
    float* weight_data = nullptr;
115
    bool enable_int8 = op_desc.HasAttr("enable_int8");
116 117 118 119 120 121 122 123 124 125 126
    bool support_int8 = false;
    if (op_desc.HasAttr("support_int8")) {
      support_int8 = BOOST_GET_CONST(bool, op_desc.GetAttr("support_int8"));
    }
    float in_scale = 0;
    if (enable_int8 || support_int8) {
      if (enable_int8) {
        in_scale = BOOST_GET_CONST(float, op_desc.GetAttr("Input_scale"));
      } else {
        in_scale = BOOST_GET_CONST(float, op_desc.GetAttr("X"));
      }
127 128
      engine_->SetTensorDynamicRange(X, in_scale);
    }
129
    weight_data = engine_->GetWeightCPUData(op_desc.Input(w_name).front(), Y_t);
N
nhzlx 已提交
130

131 132 133 134 135
    PADDLE_ENFORCE_EQ(Y_t->dims().size(), 2UL,
                      platform::errors::InvalidArgument(
                          "The fc's weight should be a matrix with 2 dims, but "
                          "it's %d-dimensional.",
                          Y_t->dims().size()));  // a matrix
136 137 138 139 140 141 142 143 144 145 146 147 148
    int m = Y_t->dims()[0];
    int n = Y_t->dims()[1];
    auto tranpose_weight = [](const float* src, float* dst, int m, int n) {
      for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
          dst[j * m + i] = src[i * n + j];
        }
      }
    };

    auto regist_fc = [&](nvinfer1::ITensor* inputs, int n_output,
                         TensorRTEngine::Weight& weight,
                         TensorRTEngine::Weight& bias) {
149
      if (enable_int8 || support_int8) {
150
        // add conv layer
151 152 153 154 155 156 157 158 159 160
        float out_scale = 0;
        if (enable_int8) {
          PADDLE_ENFORCE_EQ(
              op_desc.HasAttr("out_threshold"), true,
              platform::errors::InvalidArgument(
                  "must have out threshold in fc layers in int8 mode"));
          out_scale = BOOST_GET_CONST(float, op_desc.GetAttr("out_threshold"));
        } else {
          out_scale = BOOST_GET_CONST(float, op_desc.GetAttr("Out"));
        }
161
        nvinfer1::DimsHW nv_ksize(1, 1);
162 163 164
        auto* fc_layer_int8 =
            TRT_ENGINE_ADD_LAYER(engine_, Convolution, *inputs, n_output,
                                 nv_ksize, weight.get(), bias.get());
W
Wangzheee 已提交
165 166 167
        fc_layer_int8->setName(
            ("fc_op_int8_conv1x1: Convolution (Output: " + output_name + ")")
                .c_str());
168
        engine_->SetTensorDynamicRange(fc_layer_int8->getOutput(0), out_scale);
169 170
        auto* fc_after_reshape_int8 = reshape_after_fc(
            fc_layer_int8->getOutput(0), x_dim, x_num_col_dims);
171
        if (activation_type == "relu") {
W
Wangzheee 已提交
172
          fc_after_reshape_int8->setName(
173
              ("int8_reshape_after_fc: Shuffle (Output: " + output_name + ")")
W
Wangzheee 已提交
174
                  .c_str());
175 176
          engine_->SetTensorDynamicRange(fc_after_reshape_int8->getOutput(0),
                                         out_scale);
177
          nvinfer1::IActivationLayer* relu_layer_int8 = TRT_ENGINE_ADD_LAYER(
178
              engine_, Activation, *(fc_after_reshape_int8->getOutput(0)),
179 180 181 182
              nvinfer1::ActivationType::kRELU);
          RreplenishLayerAndOutput(relu_layer_int8, "relu_after_fc_shuffle",
                                   {output_name}, test_mode);
        } else {
W
Wangzheee 已提交
183 184
          RreplenishLayerAndOutput(fc_after_reshape_int8,
                                   "fc_op_int8_reshape_after_fc: Shuffle",
185 186
                                   {output_name}, test_mode);
        }
187
      } else {
188
        // add fc layer
189
        auto* fc_layer_float =
190 191
            TRT_ENGINE_ADD_LAYER(engine_, FullyConnected, *inputs, n_output,
                                 weight.get(), bias.get());
W
Wangzheee 已提交
192 193 194
        fc_layer_float->setName(
            ("fc_op_float: FullyConnected (Output: " + output_name + ")")
                .c_str());
195 196
        auto* fc_after_reshape_float = reshape_after_fc(
            fc_layer_float->getOutput(0), x_dim, x_num_col_dims);
197
        if (activation_type == "relu") {
W
Wangzheee 已提交
198
          fc_after_reshape_float->setName(
199
              ("float_reshape_after_fc: Shuffle (Output: " + output_name + ")")
W
Wangzheee 已提交
200
                  .c_str());
201
          nvinfer1::IActivationLayer* relu_layer_float = TRT_ENGINE_ADD_LAYER(
202
              engine_, Activation, *(fc_after_reshape_float->getOutput(0)),
203 204 205 206
              nvinfer1::ActivationType::kRELU);
          RreplenishLayerAndOutput(relu_layer_float, "relu_after_fc_shuffle",
                                   {output_name}, test_mode);
        } else {
207
          RreplenishLayerAndOutput(fc_after_reshape_float, "shuffle_after_fc",
208 209
                                   {output_name}, test_mode);
        }
210 211 212
      }
    };

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    bool transpose_y = false;
    if (op_desc.HasAttr("transpose_Y")) {
      transpose_y = BOOST_GET_CONST(bool, op_desc.GetAttr("transpose_Y"));
    }
    int weight_w, weight_h;
    if (!transpose_y) {
      std::vector<float> weight_data_tmp;
      weight_data_tmp.reserve(Y_t->numel());
      memcpy(weight_data_tmp.data(), weight_data, Y_t->numel() * sizeof(float));
      tranpose_weight(weight_data_tmp.data(), weight_data, m, n);
      weight_w = n;
      weight_h = m;
    } else {
      weight_w = m;
      weight_h = n;
    }
    size_t n_output = weight_w;
230 231
    TensorRTEngine::Weight weight{nvinfer1::DataType::kFLOAT,
                                  static_cast<void*>(weight_data),
N
nhzlx 已提交
232
                                  static_cast<size_t>(Y_t->numel())};
233 234
    weight.dims.assign({weight_w, weight_h});

235 236 237
    float* bias_data = nullptr;
    int bias_num = 0;
    if (with_bias) {
238
      auto* b_v = scope.GetVar(op_desc.Input("Bias").front());
239
      auto* b_t = b_v->GetMutable<framework::LoDTensor>();
240
      bias_data = engine_->GetWeightCPUData(op_desc.Input("Bias").front(), b_t);
241 242 243 244 245
      bias_num = b_t->numel();
    }
    TensorRTEngine::Weight bias{nvinfer1::DataType::kFLOAT,
                                static_cast<void*>(bias_data),
                                static_cast<size_t>(bias_num)};
246

247 248 249
    // Running the TRT Static Shape mode: x_num_col_dims-1
    if (!engine_->with_dynamic_shape()) {
      x_num_col_dims--;
250
    }
251 252
    // If use tensorrt'oss, the x_dim and x_num_col_dims need change, and can
    // not add Shuffle layer in ernie's multihead.
W
Wangzheee 已提交
253
    if (engine_->use_oss() && engine_->with_ernie() && x_dim.nbDims == 4 &&
254
        x_dim.d[3] == 1 && x_num_col_dims == 2) {
255
      if (enable_int8 || support_int8) {
256 257 258 259 260 261 262 263 264 265 266 267 268
        // add conv1x1 layer
        nvinfer1::DimsHW nv_ksize(1, 1);
        auto* fc_layer_int8 =
            TRT_ENGINE_ADD_LAYER(engine_, Convolution, *X, n_output, nv_ksize,
                                 weight.get(), bias.get());
        if (activation_type == "relu") {
          fc_layer_int8->setName(
              ("ernie_fc_op_int8: Convolution (Output: " + output_name + ")")
                  .c_str());
          PADDLE_ENFORCE_EQ(
              op_desc.HasAttr("out_threshold"), true,
              platform::errors::InvalidArgument(
                  "must have out threshold in fc layers in int8 mode"));
269 270 271 272 273 274 275
          float out_scale = 0;
          if (enable_int8) {
            out_scale =
                BOOST_GET_CONST(float, op_desc.GetAttr("out_threshold"));
          } else {
            out_scale = BOOST_GET_CONST(float, op_desc.GetAttr("Out"));
          }
276 277 278 279 280 281 282 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 313 314 315 316
          engine_->SetTensorDynamicRange(fc_layer_int8->getOutput(0),
                                         out_scale);
          nvinfer1::IActivationLayer* relu_layer_int8 = TRT_ENGINE_ADD_LAYER(
              engine_, Activation, *(fc_layer_int8->getOutput(0)),
              nvinfer1::ActivationType::kRELU);
          RreplenishLayerAndOutput(relu_layer_int8, "relu_after_ernie_fc_int8",
                                   {output_name}, test_mode);
        } else {
          RreplenishLayerAndOutput(fc_layer_int8,
                                   "ernie_fc_op_int8: Convolution",
                                   {output_name}, test_mode);
        }
      } else {
        // add fc layer
        auto* fc_layer_float = TRT_ENGINE_ADD_LAYER(
            engine_, FullyConnected, *X, n_output, weight.get(), bias.get());
        if (activation_type == "relu") {
          fc_layer_float->setName(
              ("ernie_fc_op_float: (Output: " + output_name + ")").c_str());
          nvinfer1::IActivationLayer* relu_layer_float = TRT_ENGINE_ADD_LAYER(
              engine_, Activation, *(fc_layer_float->getOutput(0)),
              nvinfer1::ActivationType::kRELU);
          RreplenishLayerAndOutput(relu_layer_float,
                                   "relu_after_ernie_fc_float", {output_name},
                                   test_mode);
        } else {
          RreplenishLayerAndOutput(fc_layer_float, "ernie_fc_op_float",
                                   {output_name}, test_mode);
        }
      }
    } else {  // need reshape input before and after fc
      PADDLE_ENFORCE_GT(
          x_dim.nbDims, x_num_col_dims,
          platform::errors::InvalidArgument(
              "Params and input dims mismatch. Paddle-TRT FC "
              "converter expects x_dim.nbDims > x_num_col_dims, but "
              "x_dim.nbDims : %d, x_num_col_dims : %d.",
              x_dim.nbDims, x_num_col_dims));
      auto* reshape_before_fc_layer =
          reshape_before_fc(X, x_dim, x_num_col_dims, output_name);
      auto* reshape_itensor = reshape_before_fc_layer->getOutput(0);
317
      if (enable_int8 || support_int8) {
318 319 320
        engine_->SetTensorDynamicRange(reshape_itensor, in_scale);
      }
      regist_fc(reshape_itensor, n_output, weight, bias);
P
Pei Yang 已提交
321
    }
322 323 324 325 326 327 328
  }
};

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

N
nhzlx 已提交
329
REGISTER_TRT_OP_CONVERTER(fc, FcOpConverter);