Elffuss BraidHub

kikocis/ncnn public

master · 12.0 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 "solve_batch_index.h"
16
17#include <algorithm>
18
19namespace pnnx {
20
21namespace ncnn {
22
23static bool is_known_operator_with_batch_index_0(const Operator* op)
24{
25 static const char* operator_with_batch_index_0[] = {
26 "F.adaptive_avg_pool1d",
27 "F.adaptive_avg_pool2d",
28 "F.adaptive_avg_pool3d",
29 "F.adaptive_max_pool1d",
30 "F.adaptive_max_pool2d",
31 "F.adaptive_max_pool3d",
32 "F.affine_grid",
33 "F.avg_pool1d",
34 "F.avg_pool2d",
35 "F.avg_pool3d",
36 "F.batch_norm",
37 "F.conv_transpose1d",
38 "F.conv_transpose2d",
39 "F.conv_transpose3d",
40 "F.conv1d",
41 "F.conv2d",
42 "F.conv3d",
43 "F.embedding",
44 "F.fold",
45 "F.grid_sample",
46 "F.group_norm",
47 "F.instance_norm",
48 "F.interpolate",
49 "F.layer_norm",
50 "F.linear",
51 "F.local_response_norm",
52 "F.lp_pool1d",
53 "F.lp_pool2d",
54 "F.max_pool1d",
55 "F.max_pool2d",
56 "F.max_pool3d",
57 "F.pixel_shuffle",
58 "F.pixel_unshuffle",
59 "F.prelu",
60 "F.rms_norm",
61 "F.scaled_dot_product_attention",
62 "F.unfold",
63 "F.upsample_bilinear",
64 "F.upsample_nearest",
65 "F.upsample",
66
67 "nn.AdaptiveAvgPool1d",
68 "nn.AdaptiveAvgPool2d",
69 "nn.AdaptiveAvgPool3d",
70 "nn.AdaptiveMaxPool1d",
71 "nn.AdaptiveMaxPool2d",
72 "nn.AdaptiveMaxPool3d",
73 "nn.AvgPool1d",
74 "nn.AvgPool2d",
75 "nn.AvgPool3d",
76 "nn.BatchNorm1d",
77 "nn.BatchNorm2d",
78 "nn.BatchNorm3d",
79 "nn.ChannelShuffle",
80 "nn.ConstantPad1d",
81 "nn.ConstantPad2d",
82 "nn.ConstantPad3d",
83 "nn.Conv1d",
84 "nn.Conv2d",
85 "nn.Conv3d",
86 "nn.ConvTranspose1d",
87 "nn.ConvTranspose2d",
88 "nn.ConvTranspose3d",
89 "nn.Embedding",
90 "nn.Fold",
91 "nn.GroupNorm",
92 "nn.InstanceNorm1d",
93 "nn.InstanceNorm2d",
94 "nn.InstanceNorm3d",
95 "nn.LocalResponseNorm",
96 "nn.LayerNorm",
97 "nn.LPPool1d",
98 "nn.LPPool2d",
99 "nn.MaxPool1d",
100 "nn.MaxPool2d",
101 "nn.MaxPool3d",
102 "nn.PixelShuffle",
103 "nn.PixelUnshuffle",
104 "nn.PReLU",
105 "nn.ReflectionPad1d",
106 "nn.ReflectionPad2d",
107 "nn.ReplicationPad1d",
108 "nn.ReplicationPad2d",
109 "nn.ReplicationPad3d",
110 "nn.RMSNorm",
111 "nn.Softmax2d",
112 "nn.Unfold",
113 "nn.Upsample",
114 "nn.UpsamplingBilinear2d",
115 "nn.UpsamplingNearest2d",
116 "nn.ZeroPad2d",
117 };
118
119 const size_t operator_with_batch_index_0_count = sizeof(operator_with_batch_index_0) / sizeof(const char*);
120 for (size_t i = 0; i < operator_with_batch_index_0_count; i++)
121 {
122 if (op->type == operator_with_batch_index_0[i])
123 return true;
124 }
125
126 return false;
127}
128
129static bool is_known_operator_with_batch_first_param(const Operator* op)
130{
131 return op->type == "nn.RNN" || op->type == "nn.LSTM" || op->type == "nn.GRU" || op->type == "nn.MultiheadAttention";
132}
133
134static void solve_batch_index_backward(Operand* operand);
135static void solve_batch_index_forward(Operand* operand)
136{
137 if (operand->params.find("__batch_index") == operand->params.end())
138 return;
139
140 int batch_index = operand->params["__batch_index"].i;
141
142 for (Operator* op : operand->consumers)
143 {
144 if (is_known_operator_with_batch_index_0(op))
145 continue;
146
147 if (is_known_operator_with_batch_first_param(op))
148 continue;
149
150 if (op->type == "Tensor.permute")
151 {
152 const std::vector<int>& dims = op->params.at("dims").ai;
153
154 int batch_index_permuted = -1;
155 for (int i = 0; i < (int)dims.size(); i++)
156 {
157 if (dims[i] == batch_index)
158 {
159 batch_index_permuted = i;
160 break;
161 }
162 }
163
164 for (Operand* r : op->outputs)
165 {
166 if (r->params.find("__batch_index") != r->params.end())
167 continue;
168
169 r->params["__batch_index"] = batch_index_permuted;
170
171 solve_batch_index_forward(r);
172 solve_batch_index_backward(r);
173 }
174 }
175 else if (op->type == "torch.transpose")
176 {
177 const int dim0 = op->params.at("dim0").i;
178 const int dim1 = op->params.at("dim1").i;
179
180 int batch_index_transposed = batch_index;
181 if (dim0 == batch_index)
182 {
183 batch_index_transposed = dim1;
184 }
185 else if (dim1 == batch_index)
186 {
187 batch_index_transposed = dim0;
188 }
189
190 for (Operand* r : op->outputs)
191 {
192 if (r->params.find("__batch_index") != r->params.end())
193 continue;
194
195 r->params["__batch_index"] = batch_index_transposed;
196
197 solve_batch_index_forward(r);
198 solve_batch_index_backward(r);
199 }
200 }
201 else if (op->type == "Tensor.reshape" || op->type == "Tensor.view")
202 {
203 if (op->params.find("shape") == op->params.end())
204 {
205 continue;
206 }
207
208 const std::vector<int>& shape = op->params.at("shape").ai;
209
210 if (shape[batch_index] == 1)
211 {
212 for (Operand* r : op->outputs)
213 {
214 if (r->params.find("__batch_index") != r->params.end())
215 continue;
216
217 r->params["__batch_index"] = batch_index;
218
219 solve_batch_index_forward(r);
220 solve_batch_index_backward(r);
221 }
222 }
223 else
224 {
225 // give up reshape across batch index
226 }
227 }
228 else
229 {
230 for (Operand* r : op->outputs)
231 {
232 if (r->params.find("__batch_index") != r->params.end())
233 continue;
234
235 r->params["__batch_index"] = batch_index;
236
237 solve_batch_index_forward(r);
238 solve_batch_index_backward(r);
239 }
240 }
241 }
242}
243
244static void solve_batch_index_backward(Operand* operand)
245{
246 if (operand->params.find("__batch_index") == operand->params.end())
247 return;
248
249 int batch_index = operand->params["__batch_index"].i;
250
251 Operator* op = operand->producer;
252 if (is_known_operator_with_batch_index_0(op))
253 return;
254
255 if (is_known_operator_with_batch_first_param(op))
256 return;
257
258 if (op->type == "Tensor.permute")
259 {
260 const std::vector<int>& dims = op->params.at("dims").ai;
261
262 int batch_index_permuted = dims[batch_index];
263
264 for (Operand* r : op->inputs)
265 {
266 if (r->params.find("__batch_index") != r->params.end())
267 continue;
268
269 r->params["__batch_index"] = batch_index_permuted;
270
271 solve_batch_index_backward(r);
272 solve_batch_index_forward(r);
273 }
274 }
275 else if (op->type == "torch.transpose")
276 {
277 const int dim0 = op->params.at("dim0").i;
278 const int dim1 = op->params.at("dim1").i;
279
280 int batch_index_transposed = batch_index;
281 if (dim0 == batch_index)
282 {
283 batch_index_transposed = dim1;
284 }
285 else if (dim1 == batch_index)
286 {
287 batch_index_transposed = dim0;
288 }
289
290 for (Operand* r : op->inputs)
291 {
292 if (r->params.find("__batch_index") != r->params.end())
293 continue;
294
295 r->params["__batch_index"] = batch_index_transposed;
296
297 solve_batch_index_backward(r);
298 solve_batch_index_forward(r);
299 }
300 }
301 else if (op->type == "Tensor.reshape" || op->type == "Tensor.view")
302 {
303 if (op->params.find("shape") == op->params.end())
304 {
305 return;
306 }
307
308 const std::vector<int>& shape = op->params.at("shape").ai;
309
310 if (shape[batch_index] == 1)
311 {
312 for (Operand* r : op->inputs)
313 {
314 if (r->params.find("__batch_index") != r->params.end())
315 continue;
316
317 r->params["__batch_index"] = batch_index;
318
319 solve_batch_index_backward(r);
320 solve_batch_index_forward(r);
321 }
322 }
323 else
324 {
325 // give up reshape across batch index
326 }
327 }
328 else
329 {
330 for (Operand* r : op->inputs)
331 {
332 if (r->params.find("__batch_index") != r->params.end())
333 continue;
334
335 r->params["__batch_index"] = batch_index;
336
337 solve_batch_index_backward(r);
338 solve_batch_index_forward(r);
339 }
340 }
341}
342
343void solve_batch_index(Graph& graph)
344{
345 // assign known operator
346 for (Operator* op : graph.ops)
347 {
348 if (is_known_operator_with_batch_index_0(op))
349 {
350 if (op->type == std::string("F.grid_sample"))
351 {
352 op->inputs[1]->params["__batch_index"] = 0;
353 }
354
355 op->inputs[0]->params["__batch_index"] = 0;
356 op->outputs[0]->params["__batch_index"] = 0;
357 }
358
359 if (is_known_operator_with_batch_first_param(op))
360 {
361 bool batch_first = false;
362 if (op->params.find("batch_first") != op->params.end())
363 {
364 batch_first = op->params["batch_first"].b;
365 }
366
367 op->inputs[0]->params["__batch_index"] = batch_first ? 0 : 1;
368 op->outputs[0]->params["__batch_index"] = batch_first ? 0 : 1;
369
370 for (size_t j = 1; j < op->inputs.size(); j++)
371 {
372 if (op->type == "nn.MultiheadAttention")
373 {
374 if (op->inputnames.size() == op->inputs.size() && op->inputnames[j] == "attn_mask")
375 {
376 // no batch for mha attn_mask
377 op->inputs[j]->params["__batch_index"] = 233;
378 }
379 else
380 {
381 op->inputs[j]->params["__batch_index"] = batch_first ? 0 : 1;
382 }
383
384 continue;
385 }
386
387 op->inputs[j]->params["__batch_index"] = 1;
388 }
389
390 for (size_t j = 1; j < op->outputs.size(); j++)
391 {
392 op->outputs[j]->params["__batch_index"] = 1;
393 }
394 }
395 }
396
397 // batch index propagate
398 for (Operator* op : graph.ops)
399 {
400 for (Operand* r : op->inputs)
401 {
402 solve_batch_index_backward(r);
403 }
404
405 for (Operand* r : op->outputs)
406 {
407 solve_batch_index_forward(r);
408 }
409 }
410
411 // always treat 1-dim tensor as no batch axis
412 for (Operand* r : graph.operands)
413 {
414 if (r->shape.size() == 1)
415 {
416 fprintf(stderr, "force batch axis 233 for operand %s\n", r->name.c_str());
417 r->params["__batch_index"] = 233;
418 }
419 }
420
421 // fallback axis 233 for unknown
422 for (Operand* r : graph.operands)
423 {
424 if (r->params.find("__batch_index") == r->params.end())
425 {
426 fprintf(stderr, "fallback batch axis 233 for operand %s\n", r->name.c_str());
427 r->params["__batch_index"] = 233;
428 }
429 }
430}
431
432} // namespace ncnn
433
434} // namespace pnnx