multihead_matmul_op.cc 27.1 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
    auto* input = engine_->GetITensor(op_desc.Input("Input").front());
F
feng_shuai 已提交
32 33 34 35
    auto input_dims = input->getDimensions();
    bool bias_qk_attr =
        (op_desc.Inputs().find("BiasQK") == op_desc.Inputs().end()) ? false
                                                                    : true;
36 37 38 39 40 41 42 43 44 45 46

    // 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>();

47
    float* weight_data = nullptr;
C
ceci3 已提交
48
    bool qkv2context_plugin_int8 = op_desc.HasAttr("qkv2context_plugin_int8");
49 50
    float in_scale = 0.;

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

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

65
    // (hidden_in, 3, hidden_out)
66
    const auto& weight_dims = weight_t->dims();
67

68 69 70 71 72
    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;
73 74 75 76 77 78 79 80
    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);
81

R
Ruibiao Chen 已提交
82
    int head_number = PADDLE_GET_CONST(int, op_desc.GetAttr("head_number"));
83 84

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

157 158 159
          auto plugin = creator->createPlugin("CustomQKVToContextPluginDynamic",
                                              plugin_collection);
          free(plugin_collection);
160

161 162
          std::vector<nvinfer1::ITensor*> plugin_inputs;
          plugin_inputs.emplace_back(fc_layer->getOutput(0));
163
          plugin_inputs.emplace_back(pos_id_tensor);
164
          plugin_inputs.emplace_back(
165
              max_seqlen_tensor);  // max_seqlen, eval_placeholder_3
166 167 168
          auto plugin_layer = engine_->network()->addPluginV2(
              plugin_inputs.data(), plugin_inputs.size(), *plugin);
          layer = plugin_layer;
169
        } else {
170 171 172 173
          int head_size = hidden_out / head_number;
          // [3, head_number, head_size, hidden_in] -> [head_number, 3,
          // head_size,
          // hidden_in]
174 175 176 177 178
          auto transpose_weight_v2 = [](const float* src,
                                        float* dst,
                                        int three,
                                        int head_number,
                                        int head_size,
179 180 181 182 183 184 185 186 187 188 189 190
                                        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]
191 192 193 194 195 196 197 198
          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];
                    }
                  }
199
                }
200 201 202
              };
          memcpy(weight_data_tmp.data(),
                 weight_data,
203
                 weight_t->numel() * sizeof(float));
204 205 206 207 208 209
          transpose_weight_v2(weight_data_tmp.data(),
                              weight_data,
                              three,
                              head_number,
                              head_size,
                              hidden_in);
210 211 212

          std::vector<float> bias_data_tmp;
          bias_data_tmp.reserve(bias_t->numel());
213 214 215 216
          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);
217 218 219

          nvinfer1::ILayer* fc_layer = nullptr;
          float dp_probs = 1.0 / 127.0;
220
          if (op_desc.HasAttr("Input_scale")) {
221
            nvinfer1::DimsHW nv_ksize(1, 1);
222 223
            fc_layer = TRT_ENGINE_ADD_LAYER(
                engine_, Convolution, *input, n, nv_ksize, weight, bias);
224
          } else {
225 226
            fc_layer = TRT_ENGINE_ADD_LAYER(
                engine_, FullyConnected, *input, n, weight, bias);
227 228
          }

229
          if (op_desc.HasAttr("fc_out_threshold")) {
230 231
            PADDLE_ENFORCE_EQ(op_desc.HasAttr("fc_out_threshold"),
                              true,
232 233 234 235
                              platform::errors::InvalidArgument(
                                  "must have out threshold in multihead layers "
                                  "in int8 mode"));
            float out_scale =
R
Ruibiao Chen 已提交
236
                PADDLE_GET_CONST(float, op_desc.GetAttr("fc_out_threshold"));
237 238 239
            engine_->SetTensorDynamicRange(fc_layer->getOutput(0), out_scale);
            if (qkv2context_plugin_int8) {
              dp_probs =
R
Ruibiao Chen 已提交
240
                  PADDLE_GET_CONST(float, op_desc.GetAttr("dp_probs")) / 127.0;
241 242 243 244 245
            }
          }
          auto creator = GetPluginRegistry()->getPluginCreator(
              "CustomQKVToContextPluginDynamic", "2");
          assert(creator != nullptr);
246 247 248 249
          int type = static_cast<int>(nvinfer1::DataType::kHALF);
          if (qkv2context_plugin_int8 &&
              (engine_->precision() == AnalysisConfig::Precision::kInt8)) {
            type = static_cast<int>(nvinfer1::DataType::kINT8);
250 251 252 253 254
          }
          bool has_mask = true;
          int var_seqlen = 1;
          std::vector<nvinfer1::PluginField> fields{
              {"type_id", &type, nvinfer1::PluginFieldType::kINT32, 1},
255 256 257
              {"hidden_size",
               &hidden_out,
               nvinfer1::PluginFieldType::kINT32,
258 259 260
               1},
              {"num_heads", &head_number, nvinfer1::PluginFieldType::kINT32, 1},
              {"has_mask", &has_mask, nvinfer1::PluginFieldType::kINT32, 1},
261 262 263
              {"var_seqlen",
               &var_seqlen,
               nvinfer1::PluginFieldType::kINT32,
264 265
               1}};
          if (qkv2context_plugin_int8) {
266 267 268 269
            fields.push_back({"dq_probs",
                              &dp_probs,
                              nvinfer1::PluginFieldType::kFLOAT32,
                              1});
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
          }
          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));
285
          plugin_inputs.emplace_back(engine_->GetITensor("qkv_plugin_mask"));
286
          plugin_inputs.emplace_back(pos_id_tensor);
287
          plugin_inputs.emplace_back(
288
              max_seqlen_tensor);  // max_seqlen, eval_placeholder_3
289 290 291 292

          auto plugin_layer = engine_->network()->addPluginV2(
              plugin_inputs.data(), plugin_inputs.size(), *plugin);
          layer = plugin_layer;
293
        }
F
feng_shuai 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
      }
      if (input_dims.d[1] <= 384 && !bias_qk_attr &&
          engine_->precision() != AnalysisConfig::Precision::kFloat32) {
        /*
           * input_dims.d[0]: batch(-1)
           * input_dims.d[1]: length:256
           * input_dims.d[2]: hidden_size:768
           input
             |[b,256,768]
             |
          shuffle                 weight   bias
             |[b,256,768,1,1]      |         |
             |_____________________|_________|
             |
            fc
             |[b,256,2304,1,1]
             |
          shuffle                 mask(fake)  pos   max_length
             |[b*256,2304,1,1]       |         |        |
             |                       |         |        |
             |_______________________|_________|________|
             |
             MHA
             |[b*256,768]
             |
          shuffle
             |[b, 256, 768]
             |
             out
        */

        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())};

        /*** transpose the weight and bias ***/
        int head_size = hidden_out / head_number;
        // [3, head_number, head_size, hidden_in] -> [head_number, 3,
        // head_size, hidden_in]
        auto transpose_weight_v2 = [](const float* src,
                                      float* dst,
                                      int three,
                                      int head_number,
                                      int head_size,
                                      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]
        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];
                  }
                }
              }
            };
        memcpy(weight_data_tmp.data(),
               weight_data,
               weight_t->numel() * sizeof(float));
        transpose_weight_v2(weight_data_tmp.data(),
                            weight_data,
                            three,
                            head_number,
                            head_size,
                            hidden_in);

        std::vector<float> bias_data_tmp;
        bias_data_tmp.reserve(bias_t->numel());
        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);

        // add shuffle for FullyConnected layer
        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);
        }
        auto* reshape_before_fc_layer =
            TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *input);
        reshape_before_fc_layer->setInput(
            1, *Concat(reshape_before_fc_shape_tensor));
        reshape_before_fc_layer->setName(
            ("shuffle_before_fc_multihead_matmul(Output: " + output_name + ")")
                .c_str());

        // add fc layer
        nvinfer1::ILayer* fc_layer = nullptr;
        fc_layer = TRT_ENGINE_ADD_LAYER(engine_,
                                        FullyConnected,
                                        *reshape_before_fc_layer->getOutput(0),
                                        n,
                                        weight,
                                        bias);

        // add shuffle for CustomQKVToContextPluginDynamic layer
        auto* reshape_after_fc_layer =
            TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *fc_layer->getOutput(0));
        std::vector<nvinfer1::ITensor*> mha_input_tensor_shape;
        mha_input_tensor_shape.push_back(Add1DConstantLayer(-1));
        mha_input_tensor_shape.push_back(
            Add1DConstantLayer(hidden_out * 3));  // Q,K,V
        mha_input_tensor_shape.push_back(Add1DConstantLayer(1));
        mha_input_tensor_shape.push_back(Add1DConstantLayer(1));
        reshape_after_fc_layer->setInput(1, *Concat(mha_input_tensor_shape));
        reshape_after_fc_layer->setName(
            ("shuffle_after_fc_multihead_matmul(Output: " + output_name + ")")
                .c_str());

        // add mha_plugin
        auto creator = GetPluginRegistry()->getPluginCreator(
            "CustomQKVToContextPluginDynamic", "2");
        assert(creator != nullptr);
        // set the attributes of mha_plugin
        int type = static_cast<int>(nvinfer1::DataType::kHALF);
        int var_seqlen = 1;
        bool has_mask = true;
        std::vector<nvinfer1::PluginField> fields{
            {"hidden_size", &hidden_out, nvinfer1::PluginFieldType::kINT32, 1},
            {"num_heads", &head_number, nvinfer1::PluginFieldType::kINT32, 1},
            {"type_id", &type, nvinfer1::PluginFieldType::kINT32, 1},
            {"has_mask", &has_mask, nvinfer1::PluginFieldType::kINT32, 1},
            {"var_seqlen", &var_seqlen, nvinfer1::PluginFieldType::kINT32, 1}};
        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);
        // set inputs
        std::vector<nvinfer1::ITensor*> plugin_inputs;
        // input_0 for plugin
        plugin_inputs.emplace_back(reshape_after_fc_layer->getOutput(0));
        // input_1(fake) for plugin
        std::vector<int> mask = {1};
        nvinfer1::ITensor* mask_tensor = Add1DConstantLayer(mask);
        plugin_inputs.emplace_back(mask_tensor);
        // input_2 for plugin
        std::vector<int> pos_id = {0};
        int max_batch = 500;
        for (int i = 1; i < max_batch; i++) {
          pos_id.push_back(i);
        }
        nvinfer1::ITensor* fake_pos_id_tensor = Add1DConstantLayer(pos_id);
        nvinfer1::ITensor* length_tensor =
            GetEleTensorOfShape(input_shape_tensor, 1);
        auto pos_id_layer =
            TRT_ENGINE_ADD_LAYER(engine_,
                                 ElementWise,
                                 *fake_pos_id_tensor,
                                 *length_tensor,
                                 nvinfer1::ElementWiseOperation::kPROD);
        // size = batch + 1;
        nvinfer1::ITensor* batch_tensor =
            GetEleTensorOfShape(input_shape_tensor, 0);
        std::vector<int> const_data = {1};
        nvinfer1::ITensor* const_tensor = Add1DConstantLayer(const_data);
        auto size_layer =
            TRT_ENGINE_ADD_LAYER(engine_,
                                 ElementWise,
                                 *batch_tensor,
                                 *const_tensor,
                                 nvinfer1::ElementWiseOperation::kSUM);
        // get size(batch + 1) data from pos_id_tensor
        nvinfer1::Dims start;
        nvinfer1::Dims stride;
        nvinfer1::Dims size;

        start.nbDims = 1;
        stride.nbDims = 1;
        size.nbDims = 1;

        start.d[0] = 0;
        stride.d[0] = 1;
        size.d[0] = 1;

        auto* slice_pos_layer = TRT_ENGINE_ADD_LAYER(
            engine_, Slice, *pos_id_layer->getOutput(0), start, size, stride);
        slice_pos_layer->setInput(2, *size_layer->getOutput(0));
        plugin_inputs.emplace_back(slice_pos_layer->getOutput(0));

        // input_3 for plugin
        std::vector<int> data(500, 1);
        nvinfer1::ITensor* fake_max_seqlen_tensor = Add1DConstantLayer(data);
        auto* slice_max_layer = TRT_ENGINE_ADD_LAYER(
            engine_, Slice, *fake_max_seqlen_tensor, start, size, stride);
        slice_max_layer->setInput(2, *length_tensor);
        plugin_inputs.emplace_back(slice_max_layer->getOutput(0));
        // plugin_layer
        auto plugin_layer = engine_->network()->addPluginV2(
            plugin_inputs.data(), plugin_inputs.size(), *plugin);

        // add shuffle
        auto* reshape_after_mha_layer =
            TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *plugin_layer->getOutput(0));
        std::vector<nvinfer1::ITensor*> reshape_tensor;
        reshape_tensor.push_back(batch_tensor);
        reshape_tensor.push_back(length_tensor);
        reshape_tensor.push_back(Add1DConstantLayer(-1));
        reshape_after_mha_layer->setInput(1, *Concat(reshape_tensor));
        reshape_after_mha_layer->setName(
            ("shuffle_last_multihead_matmul(Output: " + output_name + ")")
                .c_str());

        // return
        layer = reshape_after_mha_layer;
522
      } else {
523
        PADDLE_ENFORCE_EQ(
524 525
            input->getDimensions().nbDims,
            3,
526 527 528 529
            platform::errors::InvalidArgument(
                "The Input dim of the MultiheadMatMul should be 3, "
                "but it's (%d) now.",
                input->getDimensions().nbDims));
530 531 532 533 534 535 536 537 538 539 540 541 542
        // 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())};

543
        // add shuffle before fc
544 545 546 547 548 549 550 551 552 553
        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);
        }
554 555
        auto* reshape_before_fc_layer =
            TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *input);
556
        if (op_desc.HasAttr("Input_scale")) {
557 558 559
          engine_->SetTensorDynamicRange(reshape_before_fc_layer->getOutput(0),
                                         in_scale);
        }
560 561
        reshape_before_fc_layer->setInput(
            1, *Concat(reshape_before_fc_shape_tensor));
562 563 564 565 566
        reshape_before_fc_layer->setName(
            ("shuffle_before_multihead_mamul(Output: " + output_name + ")")
                .c_str());

        // add layer fc
567
        nvinfer1::ILayer* fc_layer = nullptr;
568
        if (op_desc.HasAttr("Input_scale")) {
569
          nvinfer1::DimsHW nv_ksize(1, 1);
570 571 572 573 574 575 576 577
          fc_layer =
              TRT_ENGINE_ADD_LAYER(engine_,
                                   Convolution,
                                   *reshape_before_fc_layer->getOutput(0),
                                   n,
                                   nv_ksize,
                                   weight.get(),
                                   bias.get());
578
        } else {
579 580 581 582 583 584 585
          fc_layer =
              TRT_ENGINE_ADD_LAYER(engine_,
                                   FullyConnected,
                                   *reshape_before_fc_layer->getOutput(0),
                                   n,
                                   weight.get(),
                                   bias.get());
586 587
        }

588
        if (op_desc.HasAttr("fc_out_threshold")) {
589
          PADDLE_ENFORCE_EQ(
590 591
              op_desc.HasAttr("fc_out_threshold"),
              true,
592 593 594
              platform::errors::InvalidArgument(
                  "must have out threshold in multihead layers in int8 mode"));
          float out_scale =
R
Ruibiao Chen 已提交
595
              PADDLE_GET_CONST(float, op_desc.GetAttr("fc_out_threshold"));
596 597
          engine_->SetTensorDynamicRange(fc_layer->getOutput(0), out_scale);
        }
598 599 600 601 602 603
        fc_layer->setName(
            ("multihead_mamul_fc(Output: " + output_name + ")").c_str());

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

604
        // add qkv to context
605
        int head_size = hidden_out / head_number;
R
Ruibiao Chen 已提交
606
        float scale = PADDLE_GET_CONST(float, op_desc.GetAttr("alpha"));
607 608

        std::vector<nvinfer1::ITensor*> plugin_inputs;
609
        plugin_inputs.push_back(fc_layer->getOutput(0));
610
        plugin_inputs.push_back(input_bias_qk);
611 612
        bool with_fp16 =
            engine_->WithFp16() && !engine_->disable_trt_plugin_fp16();
613

614 615
        if (engine_->precision() == AnalysisConfig::Precision::kInt8) {
          with_fp16 = true;
616
        }
617
        plugin::DynamicPluginTensorRT* plugin =
618 619
            new plugin::QkvToContextPluginDynamic(
                hidden_in, head_number, head_size, scale, with_fp16);
620
        layer = engine_->AddDynamicPlugin(plugin_inputs.data(), 2, plugin);
621
      }
622 623 624 625 626 627 628
    } 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."));
    }
629 630
    RreplenishLayerAndOutput(
        layer, "multihead_matmul", {output_name}, test_mode);
P
Pei Yang 已提交
631 632 633 634 635 636 637 638
  }
};

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

REGISTER_TRT_OP_CONVERTER(multihead_matmul, MultiheadMatMulOpConverter);