multihead_matmul_op.cc 18.5 KB
Newer Older
P
Pei Yang 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2

P
Pei Yang 已提交
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

P
Pei Yang 已提交
7
http://www.apache.org/licenses/LICENSE-2.0
8

P
Pei Yang 已提交
9 10
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
11 12
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See
the License for the specific language governing permissions and
P
Pei Yang 已提交
13 14 15
limitations under the License. */

#include "paddle/fluid/inference/tensorrt/convert/op_converter.h"
16
#include "paddle/fluid/inference/tensorrt/plugin/qkv_to_context_plugin.h"
P
Pei Yang 已提交
17 18 19 20 21 22 23 24

namespace paddle {
namespace inference {
namespace tensorrt {

class MultiheadMatMulOpConverter : public OpConverter {
 public:
  void operator()(const framework::proto::OpDesc& op,
25 26
                  const framework::Scope& scope,
                  bool test_mode) override {
P
Pei Yang 已提交
27 28 29 30
    VLOG(3) << "convert a fluid multihead_mamul op to a corresponding tensorrt "
               "network structure";
    framework::OpDesc op_desc(op, nullptr);
    // Declare inputs
31 32 33 34 35 36 37 38 39 40 41 42
    auto* input = engine_->GetITensor(op_desc.Input("Input").front());

    // fc weights and fc bias
    auto weight_name = op_desc.Input("W").front();
    auto bias_name = op_desc.Input("Bias").front();

    auto* weight_v = scope.FindVar(weight_name);
    auto* weight_t = weight_v->GetMutable<framework::LoDTensor>();

    auto* bias_v = scope.FindVar(bias_name);
    auto* bias_t = bias_v->GetMutable<framework::LoDTensor>();

43
    float* weight_data = nullptr;
C
ceci3 已提交
44
    bool qkv2context_plugin_int8 = op_desc.HasAttr("qkv2context_plugin_int8");
45 46
    float in_scale = 0.;

47
    if (op_desc.HasAttr("Input_scale")) {
R
Ruibiao Chen 已提交
48
      in_scale = PADDLE_GET_CONST(float, op_desc.GetAttr("Input_scale"));
49 50
      engine_->SetTensorDynamicRange(input, in_scale);
    }
51 52
    weight_data = const_cast<float*>(static_cast<const float*>(
        engine_->GetFp32TrtWeight(weight_name, *weight_t).get().values));
53

54 55
    float* bias_data = const_cast<float*>(static_cast<const float*>(
        engine_->GetFp32TrtWeight(bias_name, *bias_t).get().values));
56 57
    std::vector<float> weight_data_tmp;
    weight_data_tmp.reserve(weight_t->numel());
58 59
    memcpy(
        weight_data_tmp.data(), weight_data, weight_t->numel() * sizeof(float));
60

61
    // (hidden_in, 3, hidden_out)
62
    const auto& weight_dims = weight_t->dims();
63

64 65 66 67 68
    int hidden_in = weight_dims[0];   // channels_in
    int three = weight_dims[1];       // channels_out
    int hidden_out = weight_dims[2];  // channels_out
    int m = hidden_in;
    int n = three * hidden_out;
69 70 71 72 73 74 75 76
    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];
        }
      }
    };
    tranpose_weight(weight_data_tmp.data(), weight_data, m, n);
77

R
Ruibiao Chen 已提交
78
    int head_number = PADDLE_GET_CONST(int, op_desc.GetAttr("head_number"));
79 80

    nvinfer1::ILayer* layer = nullptr;
81
    auto output_name = op_desc.Output("Out")[0];
82 83 84
    bool flag_varseqlen = engine_->use_varseqlen() &&
                          engine_->tensorrt_transformer_posid() != "" &&
                          engine_->tensorrt_transformer_maskid() != "";
85
    if (engine_->with_dynamic_shape()) {
86
      if (flag_varseqlen) {
87 88
        if (engine_->precision() == AnalysisConfig::Precision::kFloat32) {
          PADDLE_THROW(platform::errors::Fatal(
89
              "use use_varseqlen must be int8 or half, not float32."));
90
        }
91 92 93 94 95 96
        nvinfer1::Weights weight{nvinfer1::DataType::kFLOAT,
                                 static_cast<void*>(weight_data),
                                 static_cast<int32_t>(weight_t->numel())};
        nvinfer1::Weights bias{nvinfer1::DataType::kFLOAT,
                               static_cast<void*>(bias_data),
                               static_cast<int32_t>(bias_t->numel())};
97
        if (engine_->with_interleaved()) {
98 99
          VLOG(4) << "fused multihead_matmul op: use_varseqlen and "
                     "with_interleaved";
100
          if (!op_desc.HasAttr("Input_scale")) {
101 102 103 104 105
            PADDLE_THROW(
                platform::errors::Fatal("use with_interleaved must be int8."));
          }
          nvinfer1::ILayer* fc_layer = nullptr;
          float dp_probs = 1.0 / 127.0;
106
          nvinfer1::DimsHW nv_ksize(1, 1);
107 108
          fc_layer = TRT_ENGINE_ADD_LAYER(
              engine_, Convolution, *input, n, nv_ksize, weight, bias);
109 110 111 112
          fc_layer->setName(
              ("Multihead: Convolution/FullyConnected: (Output: " +
               output_name + ")")
                  .c_str());
113
          PADDLE_ENFORCE_EQ(
114 115
              op_desc.HasAttr("fc_out_threshold"),
              true,
116
              platform::errors::InvalidArgument(
117
                  "must have out_threshold in multihead layers in int8 mode"));
118
          float out_scale =
R
Ruibiao Chen 已提交
119
              PADDLE_GET_CONST(float, op_desc.GetAttr("fc_out_threshold"));
120
          engine_->SetTensorDynamicRange(fc_layer->getOutput(0), out_scale);
121 122
          if (qkv2context_plugin_int8) {
            dp_probs =
R
Ruibiao Chen 已提交
123
                PADDLE_GET_CONST(float, op_desc.GetAttr("dp_probs")) / 127.0;
124
          }
125 126 127 128
          auto creator = GetPluginRegistry()->getPluginCreator(
              "CustomQKVToContextPluginDynamic", "3");
          assert(creator != nullptr);
          std::vector<nvinfer1::PluginField> fields{
129 130 131
              {"hidden_size",
               &hidden_out,
               nvinfer1::PluginFieldType::kINT32,
132
               1},
133 134 135
              {"num_heads",
               &head_number,
               nvinfer1::PluginFieldType::kINT32,
136 137
               1}};
          if (qkv2context_plugin_int8) {
138 139 140 141
            fields.push_back({"dq_probs",
                              &dp_probs,
                              nvinfer1::PluginFieldType::kFLOAT32,
                              1});
142 143 144 145 146 147 148 149
          }
          nvinfer1::PluginFieldCollection* plugin_collection =
              static_cast<nvinfer1::PluginFieldCollection*>(malloc(
                  sizeof(*plugin_collection) +
                  fields.size() *
                      sizeof(nvinfer1::PluginField)));  // remember to free
          plugin_collection->nbFields = static_cast<int>(fields.size());
          plugin_collection->fields = fields.data();
150

151 152 153
          auto plugin = creator->createPlugin("CustomQKVToContextPluginDynamic",
                                              plugin_collection);
          free(plugin_collection);
154

155 156 157 158 159 160 161 162 163 164
          std::vector<nvinfer1::ITensor*> plugin_inputs;
          plugin_inputs.emplace_back(fc_layer->getOutput(0));
          if (engine_->Has("ernie_pos_name")) {
            plugin_inputs.emplace_back(engine_->GetITensor(
                engine_->Get<std::string>("ernie_pos_name")));
          } else {
            plugin_inputs.emplace_back(engine_->GetITensor(
                engine_->network()
                    ->getInput(2)
                    ->getName()));  // cu_seqlens, eval_placeholder_2
165
          }
166 167 168 169
          auto max_seqlen_tensor =
              engine_->GetITensor(engine_->network()->getInput(3)->getName());
          engine_->SetTensorDynamicRange(max_seqlen_tensor, 1.0f);
          auto* shuffle_layer = TRT_ENGINE_ADD_LAYER(
170 171
              engine_,
              Shuffle,
172 173 174 175 176 177
              *const_cast<nvinfer1::ITensor*>(max_seqlen_tensor));
          nvinfer1::Dims shape_dim;
          shape_dim.nbDims = 1;
          shape_dim.d[0] = -1;
          shuffle_layer->setReshapeDimensions(shape_dim);
          engine_->SetTensorDynamicRange(shuffle_layer->getOutput(0), 1.0f);
178
          plugin_inputs.emplace_back(
179 180 181 182 183 184
              shuffle_layer->getOutput(0));  // max_seqlen, eval_placeholder_3
          shuffle_layer->setName(
              ("Multihead: Shuffle: (Output: " + output_name + ")").c_str());
          auto plugin_layer = engine_->network()->addPluginV2(
              plugin_inputs.data(), plugin_inputs.size(), *plugin);
          layer = plugin_layer;
185
        } else {
186 187 188 189
          int head_size = hidden_out / head_number;
          // [3, head_number, head_size, hidden_in] -> [head_number, 3,
          // head_size,
          // hidden_in]
190 191 192 193 194
          auto transpose_weight_v2 = [](const float* src,
                                        float* dst,
                                        int three,
                                        int head_number,
                                        int head_size,
195 196 197 198 199 200 201 202 203 204 205 206
                                        int hidden_in) {
            const int HH = head_size * hidden_in;
            for (int i = 0; i < three; ++i) {
              for (int n = 0; n < head_number; ++n) {
                for (int hh = 0; hh < HH; ++hh) {
                  dst[n * three * HH + i * HH + hh] =
                      src[i * head_number * HH + n * HH + hh];
                }
              }
            }
          };
          // [3, head_number, head_size] -> [head_number, 3, head_size]
207 208 209 210 211 212 213 214
          auto transpose_bias_v2 =
              [](const float* src, float* dst, int N, int H) {
                for (int i = 0; i < 3; ++i) {
                  for (int n = 0; n < N; ++n) {
                    for (int h = 0; h < H; ++h) {
                      dst[n * 3 * H + i * H + h] = src[i * N * H + n * H + h];
                    }
                  }
215
                }
216 217 218
              };
          memcpy(weight_data_tmp.data(),
                 weight_data,
219
                 weight_t->numel() * sizeof(float));
220 221 222 223 224 225
          transpose_weight_v2(weight_data_tmp.data(),
                              weight_data,
                              three,
                              head_number,
                              head_size,
                              hidden_in);
226 227 228

          std::vector<float> bias_data_tmp;
          bias_data_tmp.reserve(bias_t->numel());
229 230 231 232
          memcpy(
              bias_data_tmp.data(), bias_data, bias_t->numel() * sizeof(float));
          transpose_bias_v2(
              bias_data_tmp.data(), bias_data, head_number, head_size);
233 234 235

          nvinfer1::ILayer* fc_layer = nullptr;
          float dp_probs = 1.0 / 127.0;
236
          if (op_desc.HasAttr("Input_scale")) {
237
            nvinfer1::DimsHW nv_ksize(1, 1);
238 239
            fc_layer = TRT_ENGINE_ADD_LAYER(
                engine_, Convolution, *input, n, nv_ksize, weight, bias);
240
          } else {
241 242
            fc_layer = TRT_ENGINE_ADD_LAYER(
                engine_, FullyConnected, *input, n, weight, bias);
243 244
          }

245
          if (op_desc.HasAttr("fc_out_threshold")) {
246 247
            PADDLE_ENFORCE_EQ(op_desc.HasAttr("fc_out_threshold"),
                              true,
248 249 250 251
                              platform::errors::InvalidArgument(
                                  "must have out threshold in multihead layers "
                                  "in int8 mode"));
            float out_scale =
R
Ruibiao Chen 已提交
252
                PADDLE_GET_CONST(float, op_desc.GetAttr("fc_out_threshold"));
253 254 255
            engine_->SetTensorDynamicRange(fc_layer->getOutput(0), out_scale);
            if (qkv2context_plugin_int8) {
              dp_probs =
R
Ruibiao Chen 已提交
256
                  PADDLE_GET_CONST(float, op_desc.GetAttr("dp_probs")) / 127.0;
257 258 259 260 261
            }
          }
          auto creator = GetPluginRegistry()->getPluginCreator(
              "CustomQKVToContextPluginDynamic", "2");
          assert(creator != nullptr);
262 263 264 265
          int type = static_cast<int>(nvinfer1::DataType::kHALF);
          if (qkv2context_plugin_int8 &&
              (engine_->precision() == AnalysisConfig::Precision::kInt8)) {
            type = static_cast<int>(nvinfer1::DataType::kINT8);
266 267 268 269 270
          }
          bool has_mask = true;
          int var_seqlen = 1;
          std::vector<nvinfer1::PluginField> fields{
              {"type_id", &type, nvinfer1::PluginFieldType::kINT32, 1},
271 272 273
              {"hidden_size",
               &hidden_out,
               nvinfer1::PluginFieldType::kINT32,
274 275 276
               1},
              {"num_heads", &head_number, nvinfer1::PluginFieldType::kINT32, 1},
              {"has_mask", &has_mask, nvinfer1::PluginFieldType::kINT32, 1},
277 278 279
              {"var_seqlen",
               &var_seqlen,
               nvinfer1::PluginFieldType::kINT32,
280 281
               1}};
          if (qkv2context_plugin_int8) {
282 283 284 285
            fields.push_back({"dq_probs",
                              &dp_probs,
                              nvinfer1::PluginFieldType::kFLOAT32,
                              1});
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
          }
          nvinfer1::PluginFieldCollection* plugin_collection =
              static_cast<nvinfer1::PluginFieldCollection*>(malloc(
                  sizeof(*plugin_collection) +
                  fields.size() *
                      sizeof(nvinfer1::PluginField)));  // remember to free
          plugin_collection->nbFields = static_cast<int>(fields.size());
          plugin_collection->fields = fields.data();

          auto plugin = creator->createPlugin("CustomQKVToContextPluginDynamic",
                                              plugin_collection);
          free(plugin_collection);

          std::vector<nvinfer1::ITensor*> plugin_inputs;
          plugin_inputs.emplace_back(fc_layer->getOutput(0));
301 302 303 304
          plugin_inputs.emplace_back(engine_->GetITensor("qkv_plugin_mask"));
          plugin_inputs.emplace_back(engine_->GetITensor("pos_id"));

          auto max_seqlen_tensor = engine_->GetITensor("mask_id");
305
          auto* shuffle_layer = TRT_ENGINE_ADD_LAYER(
306 307
              engine_,
              Shuffle,
308 309 310 311 312 313 314 315 316 317 318 319
              *const_cast<nvinfer1::ITensor*>(max_seqlen_tensor));
          nvinfer1::Dims shape_dim;
          shape_dim.nbDims = 1;
          shape_dim.d[0] = -1;
          shuffle_layer->setReshapeDimensions(shape_dim);
          engine_->SetTensorDynamicRange(shuffle_layer->getOutput(0), 1.0f);
          plugin_inputs.emplace_back(
              shuffle_layer->getOutput(0));  // max_seqlen, eval_placeholder_3

          auto plugin_layer = engine_->network()->addPluginV2(
              plugin_inputs.data(), plugin_inputs.size(), *plugin);
          layer = plugin_layer;
320
        }
321
      } else {
322
        PADDLE_ENFORCE_EQ(
323 324
            input->getDimensions().nbDims,
            3,
325 326 327 328
            platform::errors::InvalidArgument(
                "The Input dim of the MultiheadMatMul should be 3, "
                "but it's (%d) now.",
                input->getDimensions().nbDims));
329 330 331 332 333 334 335 336 337 338 339 340 341
        // transpose weight_data from m * n to  n * m
        auto* input_bias_qk =
            engine_->GetITensor(op_desc.Input("BiasQK").front());

        TensorRTEngine::Weight weight{nvinfer1::DataType::kFLOAT,
                                      static_cast<void*>(weight_data),
                                      static_cast<size_t>(weight_t->numel())};
        weight.dims.assign({n, m});

        TensorRTEngine::Weight bias{nvinfer1::DataType::kFLOAT,
                                    static_cast<void*>(bias_data),
                                    static_cast<size_t>(bias_t->numel())};

342
        // add shuffle before fc
343 344 345 346 347 348 349 350 351 352
        std::vector<nvinfer1::ITensor*> reshape_before_fc_shape_tensor;
        nvinfer1::ITensor* input_shape_tensor = Shape(input);

        for (int i = 0; i < 5; i++) {
          reshape_before_fc_shape_tensor.push_back(Add1DConstantLayer(1));
        }
        for (int i = 0; i < 3; i++) {
          reshape_before_fc_shape_tensor[i] =
              GetEleTensorOfShape(input_shape_tensor, i);
        }
353 354
        auto* reshape_before_fc_layer =
            TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *input);
355
        if (op_desc.HasAttr("Input_scale")) {
356 357 358
          engine_->SetTensorDynamicRange(reshape_before_fc_layer->getOutput(0),
                                         in_scale);
        }
359 360
        reshape_before_fc_layer->setInput(
            1, *Concat(reshape_before_fc_shape_tensor));
361 362 363 364 365
        reshape_before_fc_layer->setName(
            ("shuffle_before_multihead_mamul(Output: " + output_name + ")")
                .c_str());

        // add layer fc
366
        nvinfer1::ILayer* fc_layer = nullptr;
367
        if (op_desc.HasAttr("Input_scale")) {
368
          nvinfer1::DimsHW nv_ksize(1, 1);
369 370 371 372 373 374 375 376
          fc_layer =
              TRT_ENGINE_ADD_LAYER(engine_,
                                   Convolution,
                                   *reshape_before_fc_layer->getOutput(0),
                                   n,
                                   nv_ksize,
                                   weight.get(),
                                   bias.get());
377
        } else {
378 379 380 381 382 383 384
          fc_layer =
              TRT_ENGINE_ADD_LAYER(engine_,
                                   FullyConnected,
                                   *reshape_before_fc_layer->getOutput(0),
                                   n,
                                   weight.get(),
                                   bias.get());
385 386
        }

387
        if (op_desc.HasAttr("fc_out_threshold")) {
388
          PADDLE_ENFORCE_EQ(
389 390
              op_desc.HasAttr("fc_out_threshold"),
              true,
391 392 393
              platform::errors::InvalidArgument(
                  "must have out threshold in multihead layers in int8 mode"));
          float out_scale =
R
Ruibiao Chen 已提交
394
              PADDLE_GET_CONST(float, op_desc.GetAttr("fc_out_threshold"));
395 396
          engine_->SetTensorDynamicRange(fc_layer->getOutput(0), out_scale);
        }
397 398 399 400 401 402
        fc_layer->setName(
            ("multihead_mamul_fc(Output: " + output_name + ")").c_str());

        // no need to add shuffle after fc, just change it in
        // QkvToContextPluginDynamic

403
        // add qkv to context
404
        int head_size = hidden_out / head_number;
R
Ruibiao Chen 已提交
405
        float scale = PADDLE_GET_CONST(float, op_desc.GetAttr("alpha"));
406 407

        std::vector<nvinfer1::ITensor*> plugin_inputs;
408
        plugin_inputs.push_back(fc_layer->getOutput(0));
409
        plugin_inputs.push_back(input_bias_qk);
410 411
        bool with_fp16 =
            engine_->WithFp16() && !engine_->disable_trt_plugin_fp16();
412

413 414
        if (engine_->precision() == AnalysisConfig::Precision::kInt8) {
          with_fp16 = true;
415
        }
416
        plugin::DynamicPluginTensorRT* plugin =
417 418
            new plugin::QkvToContextPluginDynamic(
                hidden_in, head_number, head_size, scale, with_fp16);
419
        layer = engine_->AddDynamicPlugin(plugin_inputs.data(), 2, plugin);
420
      }
421 422 423 424 425 426 427
    } else {
      PADDLE_THROW(platform::errors::Fatal(
          "You are running the Ernie(Bert) model in static shape mode, which "
          "is not supported for the time being.\n"
          "You can use the config.SetTRTDynamicShapeInfo(...) interface to set "
          "the shape information to run the dynamic shape mode."));
    }
428 429
    RreplenishLayerAndOutput(
        layer, "multihead_matmul", {output_name}, test_mode);
P
Pei Yang 已提交
430 431 432 433 434 435 436 437
  }
};

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

REGISTER_TRT_OP_CONVERTER(multihead_matmul, MultiheadMatMulOpConverter);