Elffuss BraidHub

kikocis/ncnn public

master · 7.6 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
4//
5// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
6// in compliance with the License. You may obtain a copy of the License at
7//
8// https://opensource.org/licenses/BSD-3-Clause
9//
10// Unless required by applicable law or agreed to in writing, software distributed
11// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12// CONDITIONS OF ANY KIND, either express or implied. See the License for the
13// specific language governing permissions and limitations under the License.
14
15#include "pass_level1.h"
16
17#include <torch/csrc/api/include/torch/torch.h>
18
19#include "../utils.h"
20
21namespace pnnx {
22
23class MultiheadAttention : public FuseModulePass
24{
25public:
26 const char* match_type_str() const
27 {
28 return "__torch__.torch.nn.modules.activation.MultiheadAttention";
29 }
30
31 const char* type_str() const
32 {
33 return "nn.MultiheadAttention";
34 }
35
36 void write(Operator* op, const std::shared_ptr<torch::jit::Graph>& graph, const torch::jit::Module& mod) const
37 {
38 // mod.dump(false, false, false);
39 // graph->dump();
40
41 const torch::jit::Node* multi_head_attention = find_node_by_kind(graph, "aten::_native_multi_head_attention");
42 if (multi_head_attention)
43 {
44 op->params["num_heads"] = multi_head_attention->namedInput("num_head");
45 op->params["batch_first"] = true;
46 op->params["add_zero_attn"] = false;
47
48 if (multi_head_attention->hasNamedInput("mask") && multi_head_attention->namedInput("mask") == graph->inputs()[graph->inputs().size() - 1])
49 {
50 size_t input_count = op->inputs.size();
51 op->inputnames.resize(input_count);
52 op->inputnames[input_count - 1] = "attn_mask";
53 }
54 }
55 else
56 {
57 const torch::jit::Node* div_num_heads = find_node_by_kind(graph, "aten::div");
58 const torch::jit::Node* div_num_heads_18 = find_node_by_kind(graph, "aten::floor_divide");
59 if (div_num_heads_18)
60 {
61 div_num_heads = div_num_heads_18;
62 }
63
64 op->params["num_heads"] = (int)div_num_heads->input(1)->node()->t(torch::jit::attr::value).item<int64_t>();
65
66 const torch::jit::Node* transpose_batch_seq = find_node_by_kind(graph, "aten::transpose");
67
68 int transpose_dim0 = transpose_batch_seq->input(1)->node()->i(torch::jit::attr::value);
69 int transpose_dim1 = transpose_batch_seq->input(2)->node()->i(torch::jit::attr::value);
70 if (transpose_dim0 == 1 && transpose_dim1 == 0)
71 {
72 op->params["batch_first"] = true;
73 }
74
75 const torch::jit::Node* add_zero_attn = find_node_by_kind(graph, "aten::zeros");
76 if (add_zero_attn)
77 {
78 op->params["add_zero_attn"] = true;
79 }
80 else
81 {
82 op->params["add_zero_attn"] = false;
83 }
84
85 const torch::jit::Node* scaled_dot_product_attention = find_node_by_kind(graph, "aten::scaled_dot_product_attention");
86 if (scaled_dot_product_attention)
87 {
88 if (scaled_dot_product_attention->input(3)->type()->kind() != c10::TypeKind::NoneType)
89 {
90 size_t input_count = op->inputs.size();
91 op->inputnames.resize(input_count);
92 op->inputnames[input_count - 1] = "attn_mask";
93 }
94 }
95
96 // find attention mask addition pattern pre torch-2.1
97 const torch::jit::Node* has_attn_mask = find_node_by_kind(graph, "aten::baddbmm");
98 if (has_attn_mask)
99 {
100 size_t input_count = op->inputs.size();
101 op->inputnames.resize(input_count);
102 op->inputnames[input_count - 1] = "attn_mask";
103 }
104
105 // find attention mask addition pattern pre torch-1.12
106 // attn = torch.bmm(Q, K)
107 // input0 = torch.add_(attn, attn_mask)
108 // attn0 = torch.softmax(input0, -1)
109 const torch::jit::Node* softmax = find_node_by_kind(graph, "aten::softmax");
110 if (softmax)
111 {
112 const torch::jit::Node* add_ = softmax->input(0)->node();
113 if (add_ && add_->kind().toDisplayString() == std::string("aten::add_"))
114 {
115 const torch::jit::Node* bmm = add_->input(0)->node();
116 if (bmm && bmm->kind().toDisplayString() == std::string("aten::bmm"))
117 {
118 size_t input_count = op->inputs.size();
119 op->inputnames.resize(input_count);
120 op->inputnames[input_count - 1] = "attn_mask";
121 }
122 }
123 }
124 }
125
126 if (mod.hasattr("in_proj_weight"))
127 {
128 const auto& in_proj_weight = mod.attr("in_proj_weight").toTensor();
129
130 op->params["embed_dim"] = in_proj_weight.size(1);
131 op->params["kdim"] = in_proj_weight.size(1);
132 op->params["vdim"] = in_proj_weight.size(1);
133 op->attrs["in_proj_weight"] = in_proj_weight;
134 }
135 else
136 {
137 const auto& q_proj_weight = mod.attr("q_proj_weight").toTensor();
138 const auto& k_proj_weight = mod.attr("k_proj_weight").toTensor();
139 const auto& v_proj_weight = mod.attr("v_proj_weight").toTensor();
140
141 op->params["embed_dim"] = q_proj_weight.size(1);
142 op->params["kdim"] = k_proj_weight.size(1);
143 op->params["vdim"] = v_proj_weight.size(1);
144 op->attrs["q_proj_weight"] = q_proj_weight;
145 op->attrs["k_proj_weight"] = k_proj_weight;
146 op->attrs["v_proj_weight"] = v_proj_weight;
147 }
148
149 const auto& out_proj_weight = mod.attr("out_proj").toModule().attr("weight").toTensor();
150
151 op->attrs["out_proj.weight"] = out_proj_weight;
152
153 if (mod.hasattr("in_proj_bias") && mod.attr("out_proj").toModule().hasattr("bias"))
154 {
155 // bias=True
156 const auto& in_proj_bias = mod.attr("in_proj_bias").toTensor();
157 const auto& out_proj_bias = mod.attr("out_proj").toModule().attr("bias").toTensor();
158
159 op->params["bias"] = true;
160 op->attrs["in_proj_bias"] = in_proj_bias;
161 op->attrs["out_proj.bias"] = out_proj_bias;
162 }
163 else
164 {
165 op->params["bias"] = false;
166
167 // the output projection bias always there no matter bias is False in pytorch 1.8
168 // this behavior changes since https://github.com/pytorch/pytorch/commit/58d1b3639bc07f9519de18e5a18e575f260c7eeb
169 if (mod.attr("out_proj").toModule().hasattr("bias"))
170 {
171 const auto& out_proj_bias = mod.attr("out_proj").toModule().attr("bias").toTensor();
172 op->attrs["out_proj.bias"] = out_proj_bias;
173 }
174 }
175
176 if (mod.hasattr("bias_k") && mod.hasattr("bias_v"))
177 {
178 // add_bias_kv=True
179 const auto& bias_k = mod.attr("bias_k").toTensor();
180 const auto& bias_v = mod.attr("bias_v").toTensor();
181
182 op->params["add_bias_kv"] = true;
183 op->attrs["bias_k"] = bias_k;
184 op->attrs["bias_v"] = bias_v;
185 }
186 else
187 {
188 op->params["add_bias_kv"] = false;
189 }
190 }
191};
192
193REGISTER_GLOBAL_PNNX_FUSE_MODULE_PASS(MultiheadAttention)
194
195} // namespace pnnx