fc_op.cc 16.9 KB
Newer Older
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2

3 4 5
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
6

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

9 10 11 12 13 14 15 16
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
namespace paddle {
namespace inference {
namespace tensorrt {
30 31 32 33 34 35 36 37 38 39
namespace {
template <typename T>
void tranpose_weight(const T* src, T* 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];
    }
  }
}
}  // namespace
40 41 42 43 44 45

/*
 * FC converter convert a MUL op in Fluid to a FC layer in TRT.
 */
class FcOpConverter : public OpConverter {
 public:
46
  nvinfer1::ILayer* reshape_before_fc(nvinfer1::ITensor* before_fc,
47 48
                                      nvinfer1::Dims x_dim,
                                      int x_num_col_dims,
W
Wangzheee 已提交
49
                                      std::string output_name) {
50 51 52 53
    // 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"
54 55 56 57 58 59 60 61 62 63 64 65

    nvinfer1::ITensor* filal_reshape_before_fc_shape_tensor = nullptr;

    if (!engine_->with_dynamic_shape()) {
      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 {
          reshape_before_fc_dim.d[x_num_col_dims] *= x_dim.d[i];
66 67
        }
      }
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    } else {
      std::vector<nvinfer1::ITensor*> reshape_before_fc_shape_tensor;
      nvinfer1::ITensor* input_shape_tensor = Shape(before_fc);

      for (int i = 0; i < reshape_before_fc_dim.nbDims; i++) {
        reshape_before_fc_shape_tensor.push_back(Add1DConstantLayer(1));
      }
      for (int i = 0; i < x_dim.nbDims; i++) {
        if (i < x_num_col_dims) {
          reshape_before_fc_shape_tensor[i] =
              GetEleTensorOfShape(input_shape_tensor, i);
        } else {
          reshape_before_fc_shape_tensor[x_num_col_dims] =
              Prod(GetEleTensorOfShape(input_shape_tensor, i),
                   reshape_before_fc_shape_tensor[x_num_col_dims]);
        }
      }
      filal_reshape_before_fc_shape_tensor =
          Concat(reshape_before_fc_shape_tensor);
87
    }
88

89 90
    auto* reshape_before_fc_layer =
        TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *before_fc);
91 92 93 94 95 96 97
    if (!engine_->with_dynamic_shape()) {
      reshape_before_fc_layer->setReshapeDimensions(reshape_before_fc_dim);
    } else {
      reshape_before_fc_layer->setInput(1,
                                        *filal_reshape_before_fc_shape_tensor);
    }

W
Wangzheee 已提交
98 99 100
    reshape_before_fc_layer->setName(
        ("fc_op_reshape_before_fc: Shuffle (Output: " + output_name + ")")
            .c_str());
101 102 103 104
    return reshape_before_fc_layer;
  }

  nvinfer1::ILayer* reshape_after_fc(nvinfer1::ITensor* after_fc,
105 106
                                     nvinfer1::Dims x_dim,
                                     int x_num_col_dims) {
107 108
    // add shuffle after fc
    nvinfer1::Dims reshape_after_fc_dim;
109
    reshape_after_fc_dim.nbDims = x_num_col_dims + 1;
110 111 112 113 114 115 116 117 118 119 120 121

    nvinfer1::ITensor* filal_reshape_after_fc_shape_tensor = nullptr;

    if (!engine_->with_dynamic_shape()) {
      for (int i = 0; i < reshape_after_fc_dim.nbDims; i++) {
        reshape_after_fc_dim.d[i] = 0;
      }
    } else {
      std::vector<int> gather_indices(x_num_col_dims + 1);
      std::iota(gather_indices.begin(), gather_indices.end(), 0);
      filal_reshape_after_fc_shape_tensor =
          Gather(Shape(after_fc), gather_indices);
122
    }
123

124 125
    auto* reshape_after_fc_layer =
        TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *after_fc);
126 127 128 129 130 131
    if (!engine_->with_dynamic_shape()) {
      reshape_after_fc_layer->setReshapeDimensions(reshape_after_fc_dim);
    } else {
      reshape_after_fc_layer->setInput(1, *filal_reshape_after_fc_shape_tensor);
    }

132 133 134
    return reshape_after_fc_layer;
  }

135
  void operator()(const framework::proto::OpDesc& op,
136 137
                  const framework::Scope& scope,
                  bool test_mode) override {
138
    VLOG(3) << "convert a fluid fc op to tensorrt fc layer without bias";
Y
Yan Chunwei 已提交
139
    framework::OpDesc op_desc(op, nullptr);
140
    auto output_name = op_desc.Output("Out").front();
141 142 143 144 145 146 147 148
    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";
    }
149
    // Declare inputs
150
    auto* X = engine_->GetITensor(op_desc.Input(i_name).front());
W
Wangzheee 已提交
151
    auto x_dim = X->getDimensions();
152
    // Declare weights
153
    auto* Y_v = scope.FindVar(op_desc.Input(w_name).front());
154
    PADDLE_ENFORCE_NOT_NULL(
155 156 157
        Y_v,
        platform::errors::NotFound(
            "Can not find %s presistale var of fc in scope.", w_name));
158
    auto* Y_t = Y_v->GetMutable<framework::LoDTensor>();
159
    int x_num_col_dims =
P
Pei Yang 已提交
160
        op_desc.HasAttr("x_num_col_dims")
R
Ruibiao Chen 已提交
161
            ? PADDLE_GET_CONST(int, op_desc.GetAttr("x_num_col_dims"))
P
Pei Yang 已提交
162
            : (op_desc.HasAttr("in_num_col_dims")
R
Ruibiao Chen 已提交
163
                   ? PADDLE_GET_CONST(int, op_desc.GetAttr("in_num_col_dims"))
P
Pei Yang 已提交
164 165 166
                   : 1);
    const std::string activation_type =
        op_desc.HasAttr("activation_type")
R
Ruibiao Chen 已提交
167
            ? PADDLE_GET_CONST(std::string, op_desc.GetAttr("activation_type"))
P
Pei Yang 已提交
168
            : "";
169

170
    bool enable_int8 = op_desc.HasAttr("enable_int8");
171 172
    bool support_int8 = false;
    if (op_desc.HasAttr("support_int8")) {
R
Ruibiao Chen 已提交
173
      support_int8 = PADDLE_GET_CONST(bool, op_desc.GetAttr("support_int8"));
174 175 176 177
    }
    float in_scale = 0;
    if (enable_int8 || support_int8) {
      if (enable_int8) {
R
Ruibiao Chen 已提交
178
        in_scale = PADDLE_GET_CONST(float, op_desc.GetAttr("Input_scale"));
179
      } else {
R
Ruibiao Chen 已提交
180
        in_scale = PADDLE_GET_CONST(float, op_desc.GetAttr("X"));
181
      }
182 183
      engine_->SetTensorDynamicRange(X, in_scale);
    }
N
nhzlx 已提交
184

185 186
    PADDLE_ENFORCE_EQ(Y_t->dims().size(),
                      2UL,
187 188 189 190
                      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
191 192 193
    int m = Y_t->dims()[0];
    int n = Y_t->dims()[1];

194 195
    auto regist_fc = [&](nvinfer1::ITensor* inputs,
                         int n_output,
196 197
                         TensorRTEngine::Weight& weight,
                         TensorRTEngine::Weight& bias) {
198
      if (enable_int8 || support_int8) {
199
        // add conv layer
200 201 202
        float out_scale = 0;
        if (enable_int8) {
          PADDLE_ENFORCE_EQ(
203 204
              op_desc.HasAttr("out_threshold"),
              true,
205 206
              platform::errors::InvalidArgument(
                  "must have out threshold in fc layers in int8 mode"));
R
Ruibiao Chen 已提交
207
          out_scale = PADDLE_GET_CONST(float, op_desc.GetAttr("out_threshold"));
208
        } else {
R
Ruibiao Chen 已提交
209
          out_scale = PADDLE_GET_CONST(float, op_desc.GetAttr("Out"));
210
        }
211
        nvinfer1::DimsHW nv_ksize(1, 1);
212 213 214 215 216 217 218
        auto* fc_layer_int8 = TRT_ENGINE_ADD_LAYER(engine_,
                                                   Convolution,
                                                   *inputs,
                                                   n_output,
                                                   nv_ksize,
                                                   weight.get(),
                                                   bias.get());
W
Wangzheee 已提交
219 220 221
        fc_layer_int8->setName(
            ("fc_op_int8_conv1x1: Convolution (Output: " + output_name + ")")
                .c_str());
222
        engine_->SetTensorDynamicRange(fc_layer_int8->getOutput(0), out_scale);
223 224
        auto* fc_after_reshape_int8 = reshape_after_fc(
            fc_layer_int8->getOutput(0), x_dim, x_num_col_dims);
225
        if (activation_type == "relu") {
W
Wangzheee 已提交
226
          fc_after_reshape_int8->setName(
227
              ("int8_reshape_after_fc: Shuffle (Output: " + output_name + ")")
W
Wangzheee 已提交
228
                  .c_str());
229 230
          engine_->SetTensorDynamicRange(fc_after_reshape_int8->getOutput(0),
                                         out_scale);
231 232 233 234 235 236 237 238 239
          nvinfer1::IActivationLayer* relu_layer_int8 =
              TRT_ENGINE_ADD_LAYER(engine_,
                                   Activation,
                                   *(fc_after_reshape_int8->getOutput(0)),
                                   nvinfer1::ActivationType::kRELU);
          RreplenishLayerAndOutput(relu_layer_int8,
                                   "relu_after_fc_shuffle",
                                   {output_name},
                                   test_mode);
240
        } else {
W
Wangzheee 已提交
241 242
          RreplenishLayerAndOutput(fc_after_reshape_int8,
                                   "fc_op_int8_reshape_after_fc: Shuffle",
243 244
                                   {output_name},
                                   test_mode);
245
        }
246
      } else {
247
        // add fc layer
248 249 250 251 252 253
        auto* fc_layer_float = TRT_ENGINE_ADD_LAYER(engine_,
                                                    FullyConnected,
                                                    *inputs,
                                                    n_output,
                                                    weight.get(),
                                                    bias.get());
W
Wangzheee 已提交
254 255 256
        fc_layer_float->setName(
            ("fc_op_float: FullyConnected (Output: " + output_name + ")")
                .c_str());
257 258
        auto* fc_after_reshape_float = reshape_after_fc(
            fc_layer_float->getOutput(0), x_dim, x_num_col_dims);
259
        if (activation_type == "relu") {
W
Wangzheee 已提交
260
          fc_after_reshape_float->setName(
261
              ("float_reshape_after_fc: Shuffle (Output: " + output_name + ")")
W
Wangzheee 已提交
262
                  .c_str());
263 264 265 266 267 268 269 270 271
          nvinfer1::IActivationLayer* relu_layer_float =
              TRT_ENGINE_ADD_LAYER(engine_,
                                   Activation,
                                   *(fc_after_reshape_float->getOutput(0)),
                                   nvinfer1::ActivationType::kRELU);
          RreplenishLayerAndOutput(relu_layer_float,
                                   "relu_after_fc_shuffle",
                                   {output_name},
                                   test_mode);
272
        } else {
273 274 275 276
          RreplenishLayerAndOutput(fc_after_reshape_float,
                                   "shuffle_after_fc",
                                   {output_name},
                                   test_mode);
277
        }
278 279 280
      }
    };

281 282
    bool transpose_y = false;
    if (op_desc.HasAttr("transpose_Y")) {
R
Ruibiao Chen 已提交
283
      transpose_y = PADDLE_GET_CONST(bool, op_desc.GetAttr("transpose_Y"));
284 285
    }
    int weight_w, weight_h;
286 287
    auto weight = engine_->GetTrtWeight(op_desc.Input(w_name).front(), *Y_t);

288
    if (!transpose_y) {
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
      if (weight.get().type == nvinfer1::DataType::kFLOAT) {
        std::vector<float> weight_data_tmp;
        weight_data_tmp.reserve(Y_t->numel());
        memcpy(weight_data_tmp.data(),
               weight.get().values,
               Y_t->numel() * sizeof(float));
        tranpose_weight(
            weight_data_tmp.data(),
            const_cast<float*>(static_cast<const float*>(weight.get().values)),
            m,
            n);
      } else if (weight.get().type == nvinfer1::DataType::kHALF) {
        std::vector<float16> weight_data_tmp;
        weight_data_tmp.reserve(Y_t->numel());
        memcpy(weight_data_tmp.data(),
               weight.get().values,
               Y_t->numel() * sizeof(float16));
        tranpose_weight(weight_data_tmp.data(),
                        const_cast<float16*>(
                            static_cast<const float16*>(weight.get().values)),
                        m,
                        n);
      } else {
        PADDLE_THROW(paddle::platform::errors::InvalidArgument(
            "Paddle-TRT fc convert not supporte dtype, now only support fp32 "
            "and fp16."));
      }
316 317 318 319 320 321 322 323 324
      weight_w = n;
      weight_h = m;
    } else {
      weight_w = m;
      weight_h = n;
    }
    size_t n_output = weight_w;
    weight.dims.assign({weight_w, weight_h});

325
    TensorRTEngine::Weight bias{weight.get().type, nullptr, 0};
326
    if (with_bias) {
327
      auto* b_v = scope.GetVar(op_desc.Input("Bias").front());
328
      auto* b_t = b_v->GetMutable<framework::LoDTensor>();
329
      bias = engine_->GetTrtWeight(op_desc.Input("Bias").front(), *b_t);
330
    }
331

332 333 334
    // Running the TRT Static Shape mode: x_num_col_dims-1
    if (!engine_->with_dynamic_shape()) {
      x_num_col_dims--;
335
    }
Z
zhoutianzi666 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    // If use tensorrt'oss, the x_dim and x_num_col_dims need change, and can
    // not add Shuffle layer in ernie's multihead.
    if (x_dim.nbDims == 4 && x_num_col_dims == 1) {
      if (enable_int8 || support_int8) {
        // 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"));
          float out_scale = 0;
          if (enable_int8) {
            out_scale =
                PADDLE_GET_CONST(float, op_desc.GetAttr("out_threshold"));
          } else {
            out_scale = PADDLE_GET_CONST(float, op_desc.GetAttr("Out"));
          }
          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);
      if (enable_int8 || support_int8) {
        engine_->SetTensorDynamicRange(reshape_itensor, in_scale);
      }
      regist_fc(reshape_itensor, n_output, weight, bias);
P
Pei Yang 已提交
420
    }
421 422 423 424 425 426 427
  }
};

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

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