fc_op.cc 11.8 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 {

/*
 * FC converter convert a MUL op in Fluid to a FC layer in TRT.
 */
class FcOpConverter : public OpConverter {
 public:
  void operator()(const framework::proto::OpDesc& op,
37
                  const framework::Scope& scope, bool test_mode) override {
38
    VLOG(3) << "convert a fluid fc op to tensorrt fc layer without bias";
Y
Yan Chunwei 已提交
39
    framework::OpDesc op_desc(op, nullptr);
40 41 42 43 44 45 46 47 48

    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";
    }
49
    // Declare inputs
50
    auto* X = engine_->GetITensor(op_desc.Input(i_name).front());
51
    // Declare weights
52
    auto* Y_v = scope.FindVar(op_desc.Input(w_name).front());
53 54 55
    PADDLE_ENFORCE_NOT_NULL(
        Y_v, platform::errors::NotFound(
                 "Can not find %s presistale var of fc in scope.", w_name));
56
    auto* Y_t = Y_v->GetMutable<framework::LoDTensor>();
P
Pei Yang 已提交
57 58
    const int x_num_col_dims =
        op_desc.HasAttr("x_num_col_dims")
59
            ? BOOST_GET_CONST(int, op_desc.GetAttr("x_num_col_dims"))
P
Pei Yang 已提交
60
            : (op_desc.HasAttr("in_num_col_dims")
61
                   ? BOOST_GET_CONST(int, op_desc.GetAttr("in_num_col_dims"))
P
Pei Yang 已提交
62 63 64
                   : 1);
    const std::string activation_type =
        op_desc.HasAttr("activation_type")
65
            ? BOOST_GET_CONST(std::string, op_desc.GetAttr("activation_type"))
P
Pei Yang 已提交
66
            : "";
67
    // This may trigger a GPU->CPU copy, because TRT's weight can only be
68
    // assigned from CPU memory, which can't be avoided.
69
    float* weight_data = nullptr;
70
    bool enable_int8 = op_desc.HasAttr("enable_int8");
71
    float in_scale = 0.;
72 73
    if (enable_int8) {
#if IS_TRT_VERSION_GE(5000)
74
      CHECK(op_desc.HasAttr(i_name + "_scale"));
75
      in_scale =
76
          BOOST_GET_CONST(float, op_desc.GetAttr(i_name + "_scale")) * 127;
77
      auto weight_scale =
78
          BOOST_GET_CONST(std::vector<float>, op_desc.GetAttr("weight_scale"));
79 80 81 82 83 84 85 86
      weight_data = engine_->GetWeightCPUData(op_desc.Input(w_name).front(),
                                              Y_t, true, weight_scale);
      engine_->SetTensorDynamicRange(X, in_scale);
#endif
    } else {
      weight_data =
          engine_->GetWeightCPUData(op_desc.Input(w_name).front(), Y_t, false);
    }
N
nhzlx 已提交
87

88 89 90 91 92
    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
93
    size_t n_output = Y_t->dims()[1];
N
nhzlx 已提交
94

95 96 97 98 99 100 101 102 103 104 105 106 107 108
    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) {
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
      nvinfer1::ILayer* fc_layer = nullptr;
      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"));
        float out_scale =
            BOOST_GET_CONST(float, op_desc.GetAttr("out_threshold"));
        nvinfer1::DimsHW nv_ksize(1, 1);
        fc_layer = TRT_ENGINE_ADD_LAYER(engine_, Convolution, *inputs, n_output,
                                        nv_ksize, weight.get(), bias.get());
        engine_->SetTensorDynamicRange(fc_layer->getOutput(0), out_scale);
      } else {
        fc_layer = TRT_ENGINE_ADD_LAYER(engine_, FullyConnected, *inputs,
                                        n_output, weight.get(), bias.get());
      }
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

      auto output_name = op_desc.Output("Out").front();
      if (activation_type == "relu") {
        nvinfer1::IActivationLayer* relu_layer =
            TRT_ENGINE_ADD_LAYER(engine_, Activation, *(fc_layer->getOutput(0)),
                                 nvinfer1::ActivationType::kRELU);
        RreplenishLayerAndOutput(relu_layer, "fc", {output_name}, test_mode);
      } else {
        RreplenishLayerAndOutput(fc_layer, "fc", {output_name}, test_mode);
      }
    };

    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);
N
nhzlx 已提交
141

142 143
    TensorRTEngine::Weight weight{nvinfer1::DataType::kFLOAT,
                                  static_cast<void*>(weight_data),
N
nhzlx 已提交
144
                                  static_cast<size_t>(Y_t->numel())};
145 146
    weight.dims.assign({n, m});

147 148 149
    float* bias_data = nullptr;
    int bias_num = 0;
    if (with_bias) {
150
      auto* b_v = scope.GetVar(op_desc.Input("Bias").front());
151 152 153 154 155 156 157 158
      auto* b_t = b_v->GetMutable<framework::LoDTensor>();
      bias_data =
          engine_->GetWeightCPUData(op_desc.Input("Bias").front(), b_t, false);
      bias_num = b_t->numel();
    }
    TensorRTEngine::Weight bias{nvinfer1::DataType::kFLOAT,
                                static_cast<void*>(bias_data),
                                static_cast<size_t>(bias_num)};
159

160
    if (engine_->with_dynamic_shape()) {
161 162
      // not NCHW layout, but NLP layout with added 'x 1 x 1'
      auto x_dim = X->getDimensions();
S
Shang Zhizhou 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
      PADDLE_ENFORCE_LE(
          x_dim.nbDims - x_num_col_dims, 3,
          platform::errors::InvalidArgument(
              "Params and input dims mismatch. Paddle-TRT FC "
              "converter expects x_dim.nbDims - x_num_col_dims <= 3, but "
              "x_dim.nbDims = %d, x_num_col_dims = %d.",
              x_dim.nbDims, x_num_col_dims));
      auto output_name = op_desc.Output("Out").front();
      // add shuffle before fc
      nvinfer1::Dims reshape_before_fc_dim;
      // padding shape "x 1 x 1"
      int padding_length = 3 - (x_dim.nbDims - x_num_col_dims);
      reshape_before_fc_dim.nbDims = x_dim.nbDims + padding_length;
      int cur_dim_index = reshape_before_fc_dim.nbDims - 1;
      while (padding_length-- > 0) {
        reshape_before_fc_dim.d[cur_dim_index--] = 1;
      }
      while (cur_dim_index >= 0) {
        reshape_before_fc_dim.d[cur_dim_index--] = 0;
      }

      auto* reshape_before_fc_layer =
          TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *X);
      reshape_before_fc_layer->setReshapeDimensions(reshape_before_fc_dim);
      reshape_before_fc_layer->setName(
          ("shuffle_before_fc(Output: " + output_name + ")").c_str());

      // add fc layer
      auto* fc_layer = TRT_ENGINE_ADD_LAYER(
          engine_, FullyConnected, *reshape_before_fc_layer->getOutput(0),
          n_output, weight.get(), bias.get());
      fc_layer->setName(("fc_layer(Output: " + output_name + ")").c_str());

      // add shuffle after fc
      nvinfer1::Dims reshape_after_fc_dim;
      reshape_after_fc_dim.nbDims = x_num_col_dims + 1;
      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, *fc_layer->getOutput(0));
      reshape_after_fc_layer->setReshapeDimensions(reshape_after_fc_dim);

      if (activation_type == "relu") {
        reshape_after_fc_layer->setName(
            ("shuffle_after_fc(Output: " + output_name + ")").c_str());
        nvinfer1::IActivationLayer* relu_layer = TRT_ENGINE_ADD_LAYER(
            engine_, Activation, *(reshape_after_fc_layer->getOutput(0)),
            nvinfer1::ActivationType::kRELU);
        RreplenishLayerAndOutput(relu_layer, "relu_after_fc_shuffle",
                                 {output_name}, test_mode);
215
      } else {
S
Shang Zhizhou 已提交
216 217
        RreplenishLayerAndOutput(reshape_after_fc_layer, "shuffle_after_fc",
                                 {output_name}, test_mode);
218
      }
219 220
      return;
    }
P
Pei Yang 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    // in order to handle situations in NLP models(input dims < 3,
    // x_num_col_dims != 1, etc.), reshape input to perform FC correctly.
    auto* reshape_itensor = X;
    int input_dims = X->getDimensions().nbDims;
    auto input_d = X->getDimensions().d;
    int reshape_dim3[3] = {0};
    int reshape_dim4[4] = {0};
    PADDLE_ENFORCE_LE(x_num_col_dims, input_dims,
                      platform::errors::InvalidArgument(
                          "Params and input dims mismatch. Paddle-TRT FC "
                          "converter expects x_num_col_dims <= input dims"));
    if (x_num_col_dims == 1) {
      if (input_dims == 4) {
        PADDLE_ENFORCE_EQ(
            input_d[3], 1,
            platform::errors::InvalidArgument(
                "Invalid dimensions. When x_num_col_dims equals to 1 and input "
                "dims equals to 4, the last dim of input must be 1, but got %d",
                input_d[3]));
      }
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
      if (enable_int8) {
        reshape_dim3[0] = 1;
        for (int i = 0; i < 3; i++) {
          reshape_dim3[0] *= input_d[i];
          if (i > 0) {
            reshape_dim3[i] = 1;
          }
        }
      } else {
        for (int i = 0; i < 3; i++) {
          if (i < input_dims) {
            reshape_dim3[i] = input_d[i];
          } else {
            reshape_dim3[i] = 1;
          }
P
Pei Yang 已提交
256 257
        }
      }
258

P
Pei Yang 已提交
259 260 261 262 263
      nvinfer1::Dims3 reshape_dim(reshape_dim3[0], reshape_dim3[1],
                                  reshape_dim3[2]);
      auto* reshape_layer = TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *X);
      reshape_layer->setReshapeDimensions(reshape_dim);
      reshape_itensor = reshape_layer->getOutput(0);
264 265 266
      if (enable_int8) {
        engine_->SetTensorDynamicRange(reshape_itensor, in_scale);
      }
P
Pei Yang 已提交
267 268 269 270 271
    } else {
      PADDLE_ENFORCE_NE(input_dims, 1,
                        platform::errors::InvalidArgument(
                            "Invalid dimensions. When x_num_col_dims equals to "
                            "2, input_dims should not be 1"));
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

      if (enable_int8) {
        for (int i = 0; i < 4; i++) {
          if (i == 0) {
            reshape_dim4[i] = input_d[i];
          } else {
            reshape_dim4[i] = 1;
            if (i < input_dims) {
              reshape_dim4[1] *= input_d[i];
            }
          }
        }
      } else {
        for (int i = 0; i < 4; i++) {
          if (i < input_dims) {
            reshape_dim4[i] = input_d[i];
          } else {
            reshape_dim4[i] = 1;
          }
P
Pei Yang 已提交
291 292 293 294 295 296 297
        }
      }
      nvinfer1::Dims4 reshape_dim(reshape_dim4[0], reshape_dim4[1],
                                  reshape_dim4[2], reshape_dim4[3]);
      auto* reshape_layer = TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *X);
      reshape_layer->setReshapeDimensions(reshape_dim);
      reshape_itensor = reshape_layer->getOutput(0);
298 299 300
      if (enable_int8) {
        engine_->SetTensorDynamicRange(reshape_itensor, in_scale);
      }
P
Pei Yang 已提交
301
    }
302
    regist_fc(reshape_itensor, n_output, weight, bias);
303 304 305 306 307 308 309
  }
};

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

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