multihead_matmul_op.cc 10.7 KB
Newer Older
P
Pei Yang 已提交
1 2 3 4 5 6 7 8 9 10
/* 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,
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 25

namespace paddle {
namespace inference {
namespace tensorrt {

class MultiheadMatMulOpConverter : public OpConverter {
 public:
  void operator()(const framework::proto::OpDesc& op,
                  const framework::Scope& scope, bool test_mode) override {
26
#if IS_TRT_VERSION_GE(6000)
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 43 44 45 46 47 48 49 50
    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>();

    float* weight_data =
        engine_->GetWeightCPUData(weight_name, weight_t, false);
    float* bias_data = engine_->GetWeightCPUData(bias_name, bias_t, false);
    std::vector<float> weight_data_tmp;
    weight_data_tmp.reserve(weight_t->numel());
    memcpy(weight_data_tmp.data(), weight_data,
           weight_t->numel() * sizeof(float));

51
    // (hidden_in, 3, hidden_out)
52 53
    auto weight_dims = weight_t->dims();

54 55 56 57 58
    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;
59 60 61 62 63 64 65 66
    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);
S
Shang Zhizhou 已提交
67

68 69 70
    int head_number = boost::get<int>(op_desc.GetAttr("head_number"));

    nvinfer1::ILayer* layer = nullptr;
71
    auto output_name = op_desc.Output("Out")[0];
S
Shang Zhizhou 已提交
72

73
    if (engine_->with_dynamic_shape()) {
S
Shang Zhizhou 已提交
74
      if (engine_->use_oss()) {
75 76 77 78 79 80 81 82 83 84 85 86
        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];
S
Shang Zhizhou 已提交
87 88 89 90
              }
            }
          }
        };
91
        // [3, head_number, head_size] -> [head_number, 3, head_size]
S
Shang Zhizhou 已提交
92 93 94 95 96 97 98 99 100 101 102 103
        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));
104 105
        transpose_weight_v2(weight_data_tmp.data(), weight_data, three,
                            head_number, head_size, hidden_in);
S
Shang Zhizhou 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
        nvinfer1::Weights weight{nvinfer1::DataType::kFLOAT,
                                 static_cast<void*>(weight_data),
                                 static_cast<int32_t>(weight_t->numel())};

        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);
        nvinfer1::Weights bias{nvinfer1::DataType::kFLOAT,
                               static_cast<void*>(bias_data),
                               static_cast<int32_t>(bias_t->numel())};

        auto* fc_layer = TRT_ENGINE_ADD_LAYER(engine_, FullyConnected, *input,
                                              n, weight, bias);

        auto mask_tensor = engine_->GetITensor("qkv_plugin_mask");

        auto creator = GetPluginRegistry()->getPluginCreator(
            "CustomQKVToContextPluginDynamic", "2");
        assert(creator != nullptr);
        int type = static_cast<int>((engine_->WithFp16() == 1)
                                        ? nvinfer1::DataType::kHALF
                                        : nvinfer1::DataType::kFLOAT);
        bool has_mask = true;
        int var_seqlen = 1;
        const std::vector<nvinfer1::PluginField> fields{
            {"type_id", &type, nvinfer1::PluginFieldType::kINT32, 1},
135
            {"hidden_size", &hidden_out, nvinfer1::PluginFieldType::kINT32, 1},
S
Shang Zhizhou 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
            {"num_heads", &head_number, 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);

        std::vector<nvinfer1::ITensor*> plugin_inputs;
        plugin_inputs.emplace_back(fc_layer->getOutput(0));
        plugin_inputs.emplace_back(mask_tensor);
        plugin_inputs.emplace_back(engine_->GetITensor(
            engine_->network()->getInput(2)->getName()));  // cu_seqlens,
                                                           // eval_placeholder_2
        auto max_seqlen_tensor =
            engine_->GetITensor(engine_->network()->getInput(3)->getName());
        auto* shuffle_layer =
            TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *max_seqlen_tensor);
        nvinfer1::Dims shape_dim;
        shape_dim.nbDims = 1;
        shape_dim.d[0] = -1;
        shuffle_layer->setReshapeDimensions(shape_dim);
        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;
      } else {
173 174 175 176 177 178
        PADDLE_ENFORCE_EQ(
            input->getDimensions().nbDims, 3,
            platform::errors::InvalidArgument(
                "The Input dim of the MultiheadMatMul should be 3, "
                "but it's (%d) now.",
                input->getDimensions().nbDims));
S
Shang Zhizhou 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191
        // 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())};

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
        // add shuffle before fc
        nvinfer1::Dims reshape_before_fc_dim;
        reshape_before_fc_dim.nbDims = 5;
        reshape_before_fc_dim.d[0] = 0;
        reshape_before_fc_dim.d[1] = 0;
        reshape_before_fc_dim.d[2] = 0;
        reshape_before_fc_dim.d[3] = 1;
        reshape_before_fc_dim.d[4] = 1;
        auto* reshape_before_fc_layer =
            TRT_ENGINE_ADD_LAYER(engine_, Shuffle, *input);
        reshape_before_fc_layer->setReshapeDimensions(reshape_before_fc_dim);
        reshape_before_fc_layer->setName(
            ("shuffle_before_multihead_mamul(Output: " + output_name + ")")
                .c_str());

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

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

S
Shang Zhizhou 已提交
217
        // add qkv to context
218
        int head_size = hidden_out / head_number;
S
Shang Zhizhou 已提交
219 220 221
        float scale = boost::get<float>(op_desc.GetAttr("alpha"));

        std::vector<nvinfer1::ITensor*> plugin_inputs;
222
        plugin_inputs.push_back(fc_layer->getOutput(0));
S
Shang Zhizhou 已提交
223
        plugin_inputs.push_back(input_bias_qk);
S
Shang Zhizhou 已提交
224 225
        bool with_fp16 =
            engine_->WithFp16() && !engine_->disable_trt_plugin_fp16();
S
Shang Zhizhou 已提交
226
        plugin::DynamicPluginTensorRT* plugin =
227
            new plugin::QkvToContextPluginDynamic(hidden_in, head_number,
S
Shang Zhizhou 已提交
228
                                                  head_size, scale, with_fp16);
S
Shang Zhizhou 已提交
229 230
        layer = engine_->AddPluginV2(plugin_inputs.data(), 2, plugin);
      }
231 232 233 234 235 236 237 238 239 240 241 242 243 244
    } 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."));
    }
    RreplenishLayerAndOutput(layer, "multihead_matmul", {output_name},
                             test_mode);
#else
    PADDLE_THROW(platform::errors::Fatal(
        "You are running the TRT Dynamic Shape mode, need to confirm that "
        "your TRT version is no less than 6.0"));
#endif
P
Pei Yang 已提交
245 246 247 248 249 250 251 252
  }
};

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

REGISTER_TRT_OP_CONVERTER(multihead_matmul, MultiheadMatMulOpConverter);