Elffuss BraidHub

kikocis/ncnn public

master · 85.8 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2017 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 "net.h"
16
17#include "cpu.h"
18#include "datareader.h"
19#include "layer_type.h"
20#include "modelbin.h"
21#include "paramdict.h"
22
23#include <stdarg.h>
24#include <stdint.h>
25#include <string.h>
26
27#if NCNN_BENCHMARK
28#include "benchmark.h"
29#endif // NCNN_BENCHMARK
30
31#if NCNN_VULKAN
32#include "command.h"
33#include "pipelinecache.h"
34#endif // NCNN_VULKAN
35
36namespace ncnn {
37
38class NetPrivate
39{
40public:
41 NetPrivate(Option& _opt);
42
43 Option& opt;
44
45#if NCNN_VULKAN
46
47 int upload_model();
48
49#endif // NCNN_VULKAN
50
51 friend class Extractor;
52 int forward_layer(int layer_index, std::vector<Mat>& blob_mats, const Option& opt) const;
53
54#if NCNN_VULKAN
55 int forward_layer(int layer_index, std::vector<Mat>& blob_mats, std::vector<VkMat>& blob_mats_gpu, VkCompute& cmd, const Option& opt) const;
56 int forward_layer(int layer_index, std::vector<Mat>& blob_mats, std::vector<VkMat>& blob_mats_gpu, std::vector<VkImageMat>& blob_mats_gpu_image, VkCompute& cmd, const Option& opt) const;
57#endif // NCNN_VULKAN
58
59 int convert_layout(Mat& bottom_blob, const Layer* layer, const Option& opt) const;
60
61 int do_forward_layer(const Layer* layer, std::vector<Mat>& blob_mats, const Option& opt) const;
62#if NCNN_VULKAN
63 int do_forward_layer(const Layer* layer, std::vector<VkMat>& blob_mats_gpu, VkCompute& cmd, const Option& opt) const;
64 int do_forward_layer(const Layer* layer, std::vector<VkImageMat>& blob_mats_gpu_image, VkCompute& cmd, const Option& opt) const;
65#endif // NCNN_VULKAN
66
67 void update_input_output_indexes();
68#if NCNN_STRING
69 void update_input_output_names();
70#endif // NCNN_STRING
71
72 std::vector<Blob> blobs;
73 std::vector<Layer*> layers;
74
75 std::vector<int> input_blob_indexes;
76 std::vector<int> output_blob_indexes;
77#if NCNN_STRING
78 std::vector<const char*> input_blob_names;
79 std::vector<const char*> output_blob_names;
80#endif // NCNN_STRING
81
82 std::vector<custom_layer_registry_entry> custom_layer_registry;
83 std::vector<overwrite_builtin_layer_registry_entry> overwrite_builtin_layer_registry;
84
85 PoolAllocator* local_blob_allocator;
86 PoolAllocator* local_workspace_allocator;
87
88#if NCNN_VULKAN
89 const VulkanDevice* vkdev;
90
91 VkAllocator* weight_vkallocator;
92 VkAllocator* weight_staging_vkallocator;
93
94 PipelineCache* pipeline_cache;
95#endif // NCNN_VULKAN
96};
97
98NetPrivate::NetPrivate(Option& _opt)
99 : opt(_opt)
100{
101 local_blob_allocator = 0;
102 local_workspace_allocator = 0;
103
104#if NCNN_VULKAN
105 vkdev = 0;
106 weight_vkallocator = 0;
107 weight_staging_vkallocator = 0;
108 pipeline_cache = 0;
109#endif // NCNN_VULKAN
110}
111
112static Option get_masked_option(const Option& opt, int featmask)
113{
114 // mask option usage as layer specific featmask
115 Option opt1 = opt;
116 opt1.use_fp16_arithmetic = opt1.use_fp16_arithmetic && !(featmask & (1 << 0));
117 opt1.use_fp16_storage = opt1.use_fp16_storage && !(featmask & (1 << 1));
118 opt1.use_fp16_packed = opt1.use_fp16_packed && !(featmask & (1 << 1));
119 opt1.use_bf16_storage = opt1.use_bf16_storage && !(featmask & (1 << 2));
120 opt1.use_int8_packed = opt1.use_int8_packed && !(featmask & (1 << 3));
121 opt1.use_int8_storage = opt1.use_int8_storage && !(featmask & (1 << 3));
122 opt1.use_int8_arithmetic = opt1.use_int8_arithmetic && !(featmask & (1 << 3));
123 opt1.use_vulkan_compute = opt1.use_vulkan_compute && !(featmask & (1 << 4));
124 opt1.use_image_storage = opt1.use_image_storage && !(featmask & (1 << 4));
125 opt1.use_tensor_storage = opt1.use_tensor_storage && !(featmask & (1 << 4));
126 opt1.use_sgemm_convolution = opt1.use_sgemm_convolution && !(featmask & (1 << 5));
127 opt1.use_winograd_convolution = opt1.use_winograd_convolution && !(featmask & (1 << 6));
128
129 if (featmask & (1 << 7))
130 opt1.num_threads = 1;
131
132 return opt1;
133}
134
135#if NCNN_VULKAN
136int NetPrivate::upload_model()
137{
138 ncnn::VkTransfer cmd(vkdev);
139
140 // create gpu device allocator if null
141 if (!weight_vkallocator)
142 {
143 weight_vkallocator = new VkWeightAllocator(vkdev);
144 }
145 if (!weight_staging_vkallocator)
146 {
147 weight_staging_vkallocator = new VkWeightStagingAllocator(vkdev);
148 }
149
150 Option opt_upload = opt;
151 opt_upload.blob_allocator = 0;
152 opt_upload.workspace_allocator = 0;
153 opt_upload.blob_vkallocator = weight_vkallocator;
154 opt_upload.workspace_vkallocator = weight_vkallocator;
155 opt_upload.staging_vkallocator = weight_staging_vkallocator;
156
157 for (size_t i = 0; i < layers.size(); i++)
158 {
159 if (layers[i]->support_vulkan)
160 {
161 int uret = layers[i]->upload_model(cmd, get_masked_option(opt_upload, layers[i]->featmask));
162 if (uret != 0)
163 {
164 NCNN_LOGE("layer upload_model %d failed", (int)i);
165 return -1;
166 }
167 }
168 }
169
170 return cmd.submit_and_wait();
171}
172#endif // NCNN_VULKAN
173
174int NetPrivate::forward_layer(int layer_index, std::vector<Mat>& blob_mats, const Option& opt) const
175{
176 const Layer* layer = layers[layer_index];
177
178 // NCNN_LOGE("forward_layer %d %s", layer_index, layer->name.c_str());
179
180 // load bottom blobs
181 for (size_t i = 0; i < layer->bottoms.size(); i++)
182 {
183 int bottom_blob_index = layer->bottoms[i];
184
185 if (blob_mats[bottom_blob_index].dims == 0)
186 {
187 int ret = forward_layer(blobs[bottom_blob_index].producer, blob_mats, opt);
188 if (ret != 0)
189 return ret;
190 }
191 }
192
193#if NCNN_BENCHMARK
194 double start = get_current_time();
195 Mat bottom_blob;
196 if (layer->one_blob_only)
197 {
198 int bottom_blob_index = layer->bottoms[0];
199 bottom_blob.dims = blob_mats[bottom_blob_index].dims;
200 bottom_blob.w = blob_mats[bottom_blob_index].w;
201 bottom_blob.h = blob_mats[bottom_blob_index].h;
202 bottom_blob.d = blob_mats[bottom_blob_index].d;
203 bottom_blob.c = blob_mats[bottom_blob_index].c;
204 bottom_blob.elempack = blob_mats[bottom_blob_index].elempack;
205 bottom_blob.elemsize = blob_mats[bottom_blob_index].elemsize;
206 }
207#endif
208 int ret = 0;
209 if (layer->featmask)
210 {
211 ret = do_forward_layer(layer, blob_mats, get_masked_option(opt, layer->featmask));
212 }
213 else
214 {
215 ret = do_forward_layer(layer, blob_mats, opt);
216 }
217#if NCNN_BENCHMARK
218 double end = get_current_time();
219 if (layer->one_blob_only)
220 {
221 int top_blob_index = layer->tops[0];
222 benchmark(layer, bottom_blob, blob_mats[top_blob_index], start, end);
223 }
224 else
225 {
226 benchmark(layer, start, end);
227 }
228#endif
229 if (ret != 0)
230 return ret;
231
232 // NCNN_LOGE("forward_layer %d %s done", layer_index, layer->name.c_str());
233 // const Mat& blob = blob_mats[layer->tops[0]];
234 // NCNN_LOGE("[%-2d %-16s %-16s] %d blobs count = %-3d size = %-3d x %-3d", layer_index, layer->type.c_str(), layer->name.c_str(), layer->tops[0], blob.c, blob.h, blob.w);
235
236 return 0;
237}
238
239#if NCNN_VULKAN
240int NetPrivate::forward_layer(int layer_index, std::vector<Mat>& blob_mats, std::vector<VkMat>& blob_mats_gpu, VkCompute& cmd, const Option& opt) const
241{
242 const Layer* layer = layers[layer_index];
243
244 // NCNN_LOGE("forward_layer %d %d %s", layer->support_vulkan, layer_index, layer->name.c_str());
245
246 bool cmd_submit_and_wait = false;
247
248 // load bottom blobs
249 for (size_t i = 0; i < layer->bottoms.size(); i++)
250 {
251 int bottom_blob_index = layer->bottoms[i];
252
253 if (blob_mats_gpu[bottom_blob_index].dims == 0 && blob_mats[bottom_blob_index].dims == 0)
254 {
255 int ret = forward_layer(blobs[bottom_blob_index].producer, blob_mats, blob_mats_gpu, cmd, opt);
256 if (ret != 0)
257 return ret;
258 }
259
260 if (layer->support_vulkan)
261 {
262 if (blob_mats_gpu[bottom_blob_index].dims == 0)
263 {
264 // host to buffer
265 cmd.record_upload(blob_mats[bottom_blob_index], blob_mats_gpu[bottom_blob_index], opt);
266
267 if (opt.lightmode)
268 {
269 // delete after taken in light mode
270 blob_mats[bottom_blob_index].release();
271 }
272 }
273 }
274 else
275 {
276 if (blob_mats[bottom_blob_index].dims == 0)
277 {
278 Option opt_download = opt;
279 opt_download.use_packing_layout = layer->support_packing;
280
281 // buffer to host
282 cmd.record_download(blob_mats_gpu[bottom_blob_index], blob_mats[bottom_blob_index], opt_download);
283
284 if (opt.lightmode)
285 {
286 // delete after taken in light mode
287 blob_mats_gpu[bottom_blob_index].release();
288 }
289
290 cmd_submit_and_wait = true;
291 }
292 }
293 }
294
295 int ret;
296 if (cmd_submit_and_wait)
297 {
298 ret = cmd.submit_and_wait();
299
300#if NCNN_BENCHMARK
301 std::vector<uint64_t> results(layer_index * 2);
302 cmd.get_query_pool_results(0, layer_index * 2, results);
303 for (int i = 0; i < layer_index; i++)
304 {
305 uint64_t start = results[i * 2];
306 uint64_t end = results[i * 2 + 1];
307 if (start == 0 || end == 0)
308 continue;
309
310 double duration_us = (end - start) * vkdev->info.timestamp_period() / 1000;
311 NCNN_LOGE("%-24s %-30s %8.2lfus |", layers[i]->type.c_str(), layers[i]->name.c_str(), duration_us);
312 }
313#endif // NCNN_BENCHMARK
314
315 cmd.reset();
316 if (ret != 0)
317 return ret;
318 }
319
320 if (layer->support_vulkan)
321 {
322#if NCNN_BENCHMARK
323 cmd.record_write_timestamp(layer_index * 2);
324#endif
325 if (layer->featmask)
326 {
327 ret = do_forward_layer(layer, blob_mats_gpu, cmd, get_masked_option(opt, layer->featmask));
328 }
329 else
330 {
331 ret = do_forward_layer(layer, blob_mats_gpu, cmd, opt);
332 }
333#if NCNN_BENCHMARK
334 cmd.record_write_timestamp(layer_index * 2 + 1);
335#endif
336 }
337 else
338 {
339#if NCNN_BENCHMARK
340 double start = get_current_time();
341 Mat bottom_blob;
342 if (layer->one_blob_only)
343 {
344 int bottom_blob_index = layer->bottoms[0];
345 bottom_blob = blob_mats[bottom_blob_index].shape();
346 }
347#endif
348 if (layer->featmask)
349 {
350 ret = do_forward_layer(layer, blob_mats, get_masked_option(opt, layer->featmask));
351 }
352 else
353 {
354 ret = do_forward_layer(layer, blob_mats, opt);
355 }
356#if NCNN_BENCHMARK
357 double end = get_current_time();
358 if (layer->one_blob_only)
359 {
360 int top_blob_index = layer->tops[0];
361 benchmark(layer, bottom_blob, blob_mats[top_blob_index], start, end);
362 }
363 else
364 {
365 benchmark(layer, start, end);
366 }
367#endif
368 }
369 if (ret != 0)
370 return ret;
371
372 // NCNN_LOGE("forward_layer %d %d %s done", layer->support_vulkan, layer_index, layer->name.c_str());
373
374 return 0;
375}
376
377int NetPrivate::forward_layer(int layer_index, std::vector<Mat>& blob_mats, std::vector<VkMat>& blob_mats_gpu, std::vector<VkImageMat>& blob_mats_gpu_image, VkCompute& cmd, const Option& opt) const
378{
379 const Layer* layer = layers[layer_index];
380
381 // NCNN_LOGE("forward_layer %d %d %s", layer->support_vulkan, layer_index, layer->name.c_str());
382
383 bool cmd_submit_and_wait = false;
384 bool image_allocation_failed = false;
385
386IMAGE_ALLOCATION_FAILED:
387
388 if (image_allocation_failed)
389 {
390#if NCNN_STRING
391 NCNN_LOGE("forward_layer %d %s image allocation failed, fallback to cpu", layer_index, layer->name.c_str());
392#else
393 NCNN_LOGE("forward_layer %d image allocation failed, fallback to cpu", layer_index);
394#endif
395 }
396
397 // load bottom blobs
398 for (size_t i = 0; i < layer->bottoms.size(); i++)
399 {
400 int bottom_blob_index = layer->bottoms[i];
401
402 if (blob_mats_gpu_image[bottom_blob_index].dims == 0 && blob_mats_gpu[bottom_blob_index].dims == 0 && blob_mats[bottom_blob_index].dims == 0)
403 {
404 int ret = forward_layer(blobs[bottom_blob_index].producer, blob_mats, blob_mats_gpu, blob_mats_gpu_image, cmd, opt);
405 if (ret != 0)
406 return ret;
407 }
408
409 if (layer->support_vulkan && !image_allocation_failed)
410 {
411 if (layer->support_image_storage)
412 {
413 if (blob_mats_gpu_image[bottom_blob_index].dims == 0)
414 {
415 if (blob_mats_gpu[bottom_blob_index].dims == 0)
416 {
417 // host to image
418 cmd.record_upload(blob_mats[bottom_blob_index], blob_mats_gpu_image[bottom_blob_index], opt);
419
420 if (blob_mats_gpu_image[bottom_blob_index].empty())
421 {
422 image_allocation_failed = true;
423 goto IMAGE_ALLOCATION_FAILED;
424 }
425
426 if (opt.lightmode)
427 {
428 // delete after taken in light mode
429 blob_mats[bottom_blob_index].release();
430 }
431 }
432 else
433 {
434 // buffer to image
435 cmd.record_buffer_to_image(blob_mats_gpu[bottom_blob_index], blob_mats_gpu_image[bottom_blob_index], opt);
436
437 if (blob_mats_gpu_image[bottom_blob_index].empty())
438 {
439 image_allocation_failed = true;
440 goto IMAGE_ALLOCATION_FAILED;
441 }
442
443 if (opt.lightmode)
444 {
445 // delete after taken in light mode
446 blob_mats_gpu[bottom_blob_index].release();
447 }
448 }
449 }
450 }
451 else
452 {
453 if (blob_mats_gpu[bottom_blob_index].dims == 0)
454 {
455 if (blob_mats_gpu_image[bottom_blob_index].dims == 0)
456 {
457 // host to buffer
458 cmd.record_upload(blob_mats[bottom_blob_index], blob_mats_gpu[bottom_blob_index], opt);
459
460 if (opt.lightmode)
461 {
462 // delete after taken in light mode
463 blob_mats[bottom_blob_index].release();
464 }
465 }
466 else
467 {
468 // image to buffer
469 cmd.record_image_to_buffer(blob_mats_gpu_image[bottom_blob_index], blob_mats_gpu[bottom_blob_index], opt);
470
471 if (opt.lightmode)
472 {
473 // delete after taken in light mode
474 blob_mats_gpu_image[bottom_blob_index].release();
475 }
476 }
477 }
478 }
479 }
480 else
481 {
482 if (blob_mats[bottom_blob_index].dims == 0)
483 {
484 if (blob_mats_gpu_image[bottom_blob_index].dims == 0)
485 {
486 // buffer to host
487 cmd.record_download(blob_mats_gpu[bottom_blob_index], blob_mats[bottom_blob_index], opt);
488
489 if (opt.lightmode)
490 {
491 // delete after taken in light mode
492 blob_mats_gpu[bottom_blob_index].release();
493 }
494
495 cmd_submit_and_wait = true;
496 }
497 else
498 {
499 // image to host
500 cmd.record_download(blob_mats_gpu_image[bottom_blob_index], blob_mats[bottom_blob_index], opt);
501
502 if (opt.lightmode)
503 {
504 // delete after taken in light mode
505 blob_mats_gpu_image[bottom_blob_index].release();
506 }
507
508 cmd_submit_and_wait = true;
509 }
510 }
511 }
512 }
513
514 int ret;
515 if (cmd_submit_and_wait)
516 {
517 ret = cmd.submit_and_wait();
518
519#if NCNN_BENCHMARK
520 std::vector<uint64_t> results(layer_index * 2);
521 cmd.get_query_pool_results(0, layer_index * 2, results);
522 for (int i = 0; i < layer_index; i++)
523 {
524 uint64_t start = results[i * 2];
525 uint64_t end = results[i * 2 + 1];
526 if (start == 0 || end == 0)
527 continue;
528
529 double duration_us = (end - start) * vkdev->info.timestamp_period() / 1000;
530 NCNN_LOGE("%-24s %-30s %8.2lfus |", layers[i]->type.c_str(), layers[i]->name.c_str(), duration_us);
531 }
532#endif // NCNN_BENCHMARK
533
534 cmd.reset();
535
536 if (ret != 0)
537 return ret;
538 }
539
540 if (layer->support_vulkan && !image_allocation_failed)
541 {
542#if NCNN_BENCHMARK
543 cmd.record_write_timestamp(layer_index * 2);
544#endif
545 if (layer->support_image_storage)
546 {
547 if (layer->featmask)
548 {
549 ret = do_forward_layer(layer, blob_mats_gpu_image, cmd, get_masked_option(opt, layer->featmask));
550 }
551 else
552 {
553 ret = do_forward_layer(layer, blob_mats_gpu_image, cmd, opt);
554 }
555 if (ret == -100)
556 {
557 image_allocation_failed = true;
558 goto IMAGE_ALLOCATION_FAILED;
559 }
560 }
561 else
562 {
563 if (layer->featmask)
564 {
565 ret = do_forward_layer(layer, blob_mats_gpu, cmd, get_masked_option(opt, layer->featmask));
566 }
567 else
568 {
569 ret = do_forward_layer(layer, blob_mats_gpu, cmd, opt);
570 }
571 }
572#if NCNN_BENCHMARK
573 cmd.record_write_timestamp(layer_index * 2 + 1);
574#endif
575 }
576 else
577 {
578#if NCNN_BENCHMARK
579 double start = get_current_time();
580 Mat bottom_blob;
581 if (layer->one_blob_only)
582 {
583 int bottom_blob_index = layer->bottoms[0];
584 bottom_blob = blob_mats[bottom_blob_index].shape();
585 }
586#endif
587 if (layer->featmask)
588 {
589 ret = do_forward_layer(layer, blob_mats, get_masked_option(opt, layer->featmask));
590 }
591 else
592 {
593 ret = do_forward_layer(layer, blob_mats, opt);
594 }
595#if NCNN_BENCHMARK
596 double end = get_current_time();
597 if (layer->one_blob_only)
598 {
599 int top_blob_index = layer->tops[0];
600 benchmark(layer, bottom_blob, blob_mats[top_blob_index], start, end);
601 }
602 else
603 {
604 benchmark(layer, start, end);
605 }
606#endif
607 }
608 if (ret != 0)
609 return ret;
610
611 // NCNN_LOGE("forward_layer %d %d %s done", layer->support_vulkan, layer_index, layer->name.c_str());
612
613 return 0;
614}
615#endif // NCNN_VULKAN
616
617int NetPrivate::convert_layout(Mat& bottom_blob, const Layer* layer, const Option& opt) const
618{
619 if (bottom_blob.elembits() == 32)
620 {
621 // clang-format off
622 // *INDENT-OFF*
623
624#if NCNN_ARM82
625 if (opt.use_fp16_storage && cpu_support_arm_asimdhp() && layer->support_fp16_storage)
626 {
627 Mat bottom_blob_fp16;
628 cast_float32_to_float16(bottom_blob, bottom_blob_fp16, opt);
629 bottom_blob = bottom_blob_fp16;
630 }
631 else
632#endif // NCNN_ARM82
633#if NCNN_VFPV4
634 if (opt.use_fp16_storage && !opt.use_bf16_storage && cpu_support_arm_vfpv4() && layer->support_fp16_storage)
635 {
636 Mat bottom_blob_fp16;
637 cast_float32_to_float16(bottom_blob, bottom_blob_fp16, opt);
638 bottom_blob = bottom_blob_fp16;
639 }
640 else
641#endif // NCNN_VFPV4
642#if NCNN_RVV
643 if (opt.use_fp16_storage && cpu_support_riscv_v() && cpu_support_riscv_zfh() && layer->support_fp16_storage)
644 {
645 Mat bottom_blob_fp16;
646 cast_float32_to_float16(bottom_blob, bottom_blob_fp16, opt);
647 bottom_blob = bottom_blob_fp16;
648 }
649 else
650#endif // NCNN_RVV
651#if NCNN_BF16
652 if (opt.use_bf16_storage && layer->support_bf16_storage)
653 {
654 Mat bottom_blob_bf16;
655 cast_float32_to_bfloat16(bottom_blob, bottom_blob_bf16, opt);
656 bottom_blob = bottom_blob_bf16;
657 }
658 else
659#endif // NCNN_BF16
660 {
661 }
662
663 // *INDENT-ON*
664 // clang-format on
665
666 if (bottom_blob.empty())
667 return -100;
668 }
669
670 int dst_elempack = 1;
671 if (opt.use_packing_layout)
672 {
673 // resolve dst_elempack
674 int dims = bottom_blob.dims;
675 int elemcount = 0;
676 if (dims == 1) elemcount = bottom_blob.elempack * bottom_blob.w;
677 if (dims == 2) elemcount = bottom_blob.elempack * bottom_blob.h;
678 if (dims == 3 || dims == 4) elemcount = bottom_blob.elempack * bottom_blob.c;
679
680 int elembits = bottom_blob.elembits();
681
682 if (layer->support_packing)
683 {
684 if (elembits == 32)
685 {
686#if NCNN_AVX512
687 if (elemcount % 16 == 0 && ncnn::cpu_support_x86_avx512())
688 dst_elempack = 16;
689 else if (elemcount % 8 == 0 && ncnn::cpu_support_x86_avx())
690 dst_elempack = 8;
691 else if (elemcount % 4 == 0)
692 dst_elempack = 4;
693#elif NCNN_AVX
694 if (elemcount % 8 == 0 && ncnn::cpu_support_x86_avx())
695 dst_elempack = 8;
696 else if (elemcount % 4 == 0)
697 dst_elempack = 4;
698#elif NCNN_RVV
699 const int packn = ncnn::cpu_riscv_vlenb() / 4;
700 if (elemcount % packn == 0)
701 dst_elempack = packn;
702#else
703 if (elemcount % 4 == 0)
704 dst_elempack = 4;
705#endif
706 }
707 if (elembits == 16)
708 {
709#if NCNN_ARM82
710 if (elemcount % 8 == 0 && ncnn::cpu_support_arm_asimdhp() && opt.use_fp16_arithmetic)
711 dst_elempack = 8;
712 else if (elemcount % 4 == 0)
713 dst_elempack = 4;
714#elif NCNN_RVV
715 const int packn = ncnn::cpu_riscv_vlenb() / 2;
716 if (elemcount % packn == 0)
717 dst_elempack = packn;
718#else
719 if (elemcount % 4 == 0)
720 dst_elempack = 4;
721#endif
722 }
723 if (elembits == 8)
724 {
725#if NCNN_RVV
726 const int packn = ncnn::cpu_riscv_vlenb() / 1;
727 if (elemcount % packn == 0)
728 dst_elempack = packn;
729#else
730 if (elemcount % 8 == 0)
731 dst_elempack = 8;
732#endif
733 }
734 }
735 }
736
737 if (bottom_blob.elempack != dst_elempack)
738 {
739 Mat bottom_blob_packed;
740 convert_packing(bottom_blob, bottom_blob_packed, dst_elempack, opt);
741 bottom_blob = bottom_blob_packed;
742
743 if (bottom_blob.empty())
744 return -100;
745 }
746
747 if (bottom_blob.elembits() == 16)
748 {
749 // clang-format off
750 // *INDENT-OFF*
751
752#if NCNN_ARM82
753 if (opt.use_fp16_storage && cpu_support_arm_asimdhp() && !layer->support_fp16_storage)
754 {
755 Mat bottom_blob_fp32;
756 cast_float16_to_float32(bottom_blob, bottom_blob_fp32, opt);
757 bottom_blob = bottom_blob_fp32;
758 }
759 else
760#endif // NCNN_ARM82
761#if NCNN_VFPV4
762 if (opt.use_fp16_storage && !opt.use_bf16_storage && cpu_support_arm_vfpv4() && !layer->support_fp16_storage)
763 {
764 Mat bottom_blob_fp32;
765 cast_float16_to_float32(bottom_blob, bottom_blob_fp32, opt);
766 bottom_blob = bottom_blob_fp32;
767 }
768 else
769#endif // NCNN_VFPV4
770#if NCNN_RVV
771 if (opt.use_fp16_storage && cpu_support_riscv_v() && cpu_support_riscv_zfh() && !layer->support_fp16_storage)
772 {
773 Mat bottom_blob_fp32;
774 cast_float16_to_float32(bottom_blob, bottom_blob_fp32, opt);
775 bottom_blob = bottom_blob_fp32;
776 }
777 else
778#endif // NCNN_RVV
779#if NCNN_BF16
780 if (opt.use_bf16_storage && !layer->support_bf16_storage)
781 {
782 Mat bottom_blob_fp32;
783 cast_bfloat16_to_float32(bottom_blob, bottom_blob_fp32, opt);
784 bottom_blob = bottom_blob_fp32;
785 }
786 else
787#endif // NCNN_BF16
788 {
789 }
790
791 // *INDENT-ON*
792 // clang-format on
793
794 if (bottom_blob.empty())
795 return -100;
796 }
797
798 return 0;
799}
800
801int NetPrivate::do_forward_layer(const Layer* layer, std::vector<Mat>& blob_mats, const Option& opt) const
802{
803 if (layer->one_blob_only)
804 {
805 int bottom_blob_index = layer->bottoms[0];
806 int top_blob_index = layer->tops[0];
807
808 Mat& bottom_blob_ref = blob_mats[bottom_blob_index];
809 Mat bottom_blob;
810
811 if (opt.lightmode)
812 {
813 // deep copy for inplace forward if data is shared
814 if (layer->support_inplace && *bottom_blob_ref.refcount != 1)
815 {
816 bottom_blob = bottom_blob_ref.clone(opt.blob_allocator);
817 if (bottom_blob.empty())
818 return -100;
819 }
820 }
821 if (bottom_blob.dims == 0)
822 {
823 bottom_blob = bottom_blob_ref;
824 }
825
826 int ret = convert_layout(bottom_blob, layer, opt);
827 if (ret != 0)
828 return ret;
829
830 // forward
831 if (opt.lightmode && layer->support_inplace)
832 {
833 Mat& bottom_top_blob = bottom_blob;
834 int ret = layer->forward_inplace(bottom_top_blob, opt);
835 if (ret != 0)
836 return ret;
837
838 // store top blob
839 blob_mats[top_blob_index] = bottom_top_blob;
840 }
841 else
842 {
843 Mat top_blob;
844 int ret = layer->forward(bottom_blob, top_blob, opt);
845 if (ret != 0)
846 return ret;
847
848 // store top blob
849 blob_mats[top_blob_index] = top_blob;
850 }
851
852 if (opt.lightmode)
853 {
854 // delete after taken in light mode
855 blob_mats[bottom_blob_index].release();
856 }
857 }
858 else
859 {
860 std::vector<Mat> bottom_blobs(layer->bottoms.size());
861 for (size_t i = 0; i < layer->bottoms.size(); i++)
862 {
863 int bottom_blob_index = layer->bottoms[i];
864
865 Mat& bottom_blob_ref = blob_mats[bottom_blob_index];
866 bottom_blobs[i].release();
867
868 if (opt.lightmode)
869 {
870 // deep copy for inplace forward if data is shared
871 if (layer->support_inplace && *bottom_blob_ref.refcount != 1)
872 {
873 bottom_blobs[i] = bottom_blob_ref.clone(opt.blob_allocator);
874 if (bottom_blobs[i].empty())
875 return -100;
876 }
877 }
878 if (bottom_blobs[i].dims == 0)
879 {
880 bottom_blobs[i] = bottom_blob_ref;
881 }
882
883 int ret = convert_layout(bottom_blobs[i], layer, opt);
884 if (ret != 0)
885 return ret;
886 }
887
888 // forward
889 if (opt.lightmode && layer->support_inplace)
890 {
891 std::vector<Mat>& bottom_top_blobs = bottom_blobs;
892 int ret = layer->forward_inplace(bottom_top_blobs, opt);
893 if (ret != 0)
894 return ret;
895
896 // store top blobs
897 for (size_t i = 0; i < layer->tops.size(); i++)
898 {
899 int top_blob_index = layer->tops[i];
900
901 blob_mats[top_blob_index] = bottom_top_blobs[i];
902 }
903 }
904 else
905 {
906 std::vector<Mat> top_blobs(layer->tops.size());
907 int ret = layer->forward(bottom_blobs, top_blobs, opt);
908 if (ret != 0)
909 return ret;
910
911 // store top blobs
912 for (size_t i = 0; i < layer->tops.size(); i++)
913 {
914 int top_blob_index = layer->tops[i];
915
916 blob_mats[top_blob_index] = top_blobs[i];
917 }
918 }
919
920 if (opt.lightmode)
921 {
922 for (size_t i = 0; i < layer->bottoms.size(); i++)
923 {
924 int bottom_blob_index = layer->bottoms[i];
925
926 // delete after taken in light mode
927 blob_mats[bottom_blob_index].release();
928 }
929 }
930 }
931
932 return 0;
933}
934
935#if NCNN_VULKAN
936int NetPrivate::do_forward_layer(const Layer* layer, std::vector<VkMat>& blob_mats_gpu, VkCompute& cmd, const Option& opt) const
937{
938 if (layer->one_blob_only)
939 {
940 // load bottom blob
941 int bottom_blob_index = layer->bottoms[0];
942 int top_blob_index = layer->tops[0];
943
944 VkMat& bottom_blob_ref = blob_mats_gpu[bottom_blob_index];
945 VkMat bottom_blob;
946
947 if (opt.lightmode)
948 {
949 // deep copy for inplace forward if data is shared
950 if (layer->support_inplace && *bottom_blob_ref.refcount != 1)
951 {
952 cmd.record_clone(bottom_blob_ref, bottom_blob, opt);
953 // NCNN_LOGE("clone %p[+%lu] %p[+%lu]", bottom_blob_ref.buffer(), bottom_blob_ref.buffer_offset(), bottom_blob.buffer(), bottom_blob.buffer_offset());
954 }
955 }
956 if (bottom_blob.dims == 0)
957 {
958 bottom_blob = bottom_blob_ref;
959 }
960
961 // forward
962 if (opt.lightmode && layer->support_inplace)
963 {
964 VkMat& bottom_top_blob = bottom_blob;
965 int ret = layer->forward_inplace(bottom_top_blob, cmd, opt);
966 if (ret != 0)
967 return ret;
968
969 // store top blob
970 blob_mats_gpu[top_blob_index] = bottom_top_blob;
971 }
972 else
973 {
974 VkMat top_blob;
975 int ret = layer->forward(bottom_blob, top_blob, cmd, opt);
976 if (ret != 0)
977 return ret;
978
979 // store top blob
980 blob_mats_gpu[top_blob_index] = top_blob;
981 }
982
983 if (opt.lightmode)
984 {
985 // delete after taken in light mode
986 blob_mats_gpu[bottom_blob_index].release();
987 }
988 }
989 else
990 {
991 // load bottom blobs
992 std::vector<VkMat> bottom_blobs(layer->bottoms.size());
993 for (size_t i = 0; i < layer->bottoms.size(); i++)
994 {
995 int bottom_blob_index = layer->bottoms[i];
996
997 VkMat& bottom_blob_ref = blob_mats_gpu[bottom_blob_index];
998 bottom_blobs[i].release();
999
1000 if (opt.lightmode)
1001 {
1002 // deep copy for inplace forward if data is shared
1003 if (layer->support_inplace && *bottom_blob_ref.refcount != 1)
1004 {
1005 cmd.record_clone(bottom_blob_ref, bottom_blobs[i], opt);
1006 // NCNN_LOGE("clone %p[+%lu] %p[+%lu]", bottom_blob_ref.buffer(), bottom_blob_ref.buffer_offset(), bottom_blobs[i].buffer(), bottom_blobs[i].buffer_offset());
1007 }
1008 }
1009 if (bottom_blobs[i].dims == 0)
1010 {
1011 bottom_blobs[i] = bottom_blob_ref;
1012 }
1013 }
1014
1015 // forward
1016 if (opt.lightmode && layer->support_inplace)
1017 {
1018 std::vector<VkMat>& bottom_top_blobs = bottom_blobs;
1019 int ret = layer->forward_inplace(bottom_top_blobs, cmd, opt);
1020 if (ret != 0)
1021 return ret;
1022
1023 // store top blobs
1024 for (size_t i = 0; i < layer->tops.size(); i++)
1025 {
1026 int top_blob_index = layer->tops[i];
1027
1028 blob_mats_gpu[top_blob_index] = bottom_top_blobs[i];
1029 }
1030 }
1031 else
1032 {
1033 std::vector<VkMat> top_blobs(layer->tops.size());
1034 int ret = layer->forward(bottom_blobs, top_blobs, cmd, opt);
1035 if (ret != 0)
1036 return ret;
1037
1038 // store top blobs
1039 for (size_t i = 0; i < layer->tops.size(); i++)
1040 {
1041 int top_blob_index = layer->tops[i];
1042
1043 blob_mats_gpu[top_blob_index] = top_blobs[i];
1044 }
1045 }
1046
1047 if (opt.lightmode)
1048 {
1049 for (size_t i = 0; i < layer->bottoms.size(); i++)
1050 {
1051 int bottom_blob_index = layer->bottoms[i];
1052
1053 // delete after taken in light mode
1054 blob_mats_gpu[bottom_blob_index].release();
1055 }
1056 }
1057 }
1058
1059 return 0;
1060}
1061
1062int NetPrivate::do_forward_layer(const Layer* layer, std::vector<VkImageMat>& blob_mats_gpu_image, VkCompute& cmd, const Option& opt) const
1063{
1064 if (layer->one_blob_only)
1065 {
1066 // load bottom blob
1067 int bottom_blob_index = layer->bottoms[0];
1068 int top_blob_index = layer->tops[0];
1069
1070 VkImageMat& bottom_blob_ref = blob_mats_gpu_image[bottom_blob_index];
1071 VkImageMat bottom_blob;
1072
1073 if (opt.lightmode)
1074 {
1075 // deep copy for inplace forward if data is shared
1076 if (layer->support_inplace && *bottom_blob_ref.refcount != 1)
1077 {
1078 cmd.record_clone(bottom_blob_ref, bottom_blob, opt);
1079 // NCNN_LOGE("clone %p[+%lu] %p[+%lu]", bottom_blob_ref.buffer(), bottom_blob_ref.buffer_offset(), bottom_blob.buffer(), bottom_blob.buffer_offset());
1080 }
1081 }
1082 if (bottom_blob.dims == 0)
1083 {
1084 bottom_blob = bottom_blob_ref;
1085 }
1086
1087 // forward
1088 if (opt.lightmode && layer->support_inplace)
1089 {
1090 VkImageMat& bottom_top_blob = bottom_blob;
1091 int ret = layer->forward_inplace(bottom_top_blob, cmd, opt);
1092 if (ret != 0)
1093 return ret;
1094
1095 // store top blob
1096 blob_mats_gpu_image[top_blob_index] = bottom_top_blob;
1097 }
1098 else
1099 {
1100 VkImageMat top_blob;
1101 int ret = layer->forward(bottom_blob, top_blob, cmd, opt);
1102 if (ret != 0)
1103 return ret;
1104
1105 // store top blob
1106 blob_mats_gpu_image[top_blob_index] = top_blob;
1107 }
1108
1109 if (opt.lightmode)
1110 {
1111 // delete after taken in light mode
1112 blob_mats_gpu_image[bottom_blob_index].release();
1113 }
1114 }
1115 else
1116 {
1117 // load bottom blobs
1118 std::vector<VkImageMat> bottom_blobs(layer->bottoms.size());
1119 for (size_t i = 0; i < layer->bottoms.size(); i++)
1120 {
1121 int bottom_blob_index = layer->bottoms[i];
1122
1123 VkImageMat& bottom_blob_ref = blob_mats_gpu_image[bottom_blob_index];
1124
1125 if (opt.lightmode)
1126 {
1127 // deep copy for inplace forward if data is shared
1128 if (layer->support_inplace && *bottom_blob_ref.refcount != 1)
1129 {
1130 cmd.record_clone(bottom_blob_ref, bottom_blobs[i], opt);
1131 // NCNN_LOGE("clone %p[+%lu] %p[+%lu]", bottom_blob_ref.buffer(), bottom_blob_ref.buffer_offset(), bottom_blobs[i].buffer(), bottom_blobs[i].buffer_offset());
1132 }
1133 }
1134 if (bottom_blobs[i].dims == 0)
1135 {
1136 bottom_blobs[i] = bottom_blob_ref;
1137 }
1138 }
1139
1140 // forward
1141 if (opt.lightmode && layer->support_inplace)
1142 {
1143 std::vector<VkImageMat>& bottom_top_blobs = bottom_blobs;
1144 int ret = layer->forward_inplace(bottom_top_blobs, cmd, opt);
1145 if (ret != 0)
1146 return ret;
1147
1148 // store top blobs
1149 for (size_t i = 0; i < layer->tops.size(); i++)
1150 {
1151 int top_blob_index = layer->tops[i];
1152
1153 blob_mats_gpu_image[top_blob_index] = bottom_top_blobs[i];
1154 }
1155 }
1156 else
1157 {
1158 std::vector<VkImageMat> top_blobs(layer->tops.size());
1159 int ret = layer->forward(bottom_blobs, top_blobs, cmd, opt);
1160 if (ret != 0)
1161 return ret;
1162
1163 // store top blobs
1164 for (size_t i = 0; i < layer->tops.size(); i++)
1165 {
1166 int top_blob_index = layer->tops[i];
1167
1168 blob_mats_gpu_image[top_blob_index] = top_blobs[i];
1169 }
1170 }
1171
1172 if (opt.lightmode)
1173 {
1174 for (size_t i = 0; i < layer->bottoms.size(); i++)
1175 {
1176 int bottom_blob_index = layer->bottoms[i];
1177
1178 // delete after taken in light mode
1179 blob_mats_gpu_image[bottom_blob_index].release();
1180 }
1181 }
1182 }
1183
1184 return 0;
1185}
1186#endif // NCNN_VULKAN
1187
1188void NetPrivate::update_input_output_indexes()
1189{
1190 input_blob_indexes.clear();
1191 output_blob_indexes.clear();
1192
1193 for (size_t i = 0; i < layers.size(); i++)
1194 {
1195 if (layers[i]->typeindex == LayerType::Input)
1196 {
1197 int blob_index = layers[i]->tops[0];
1198 input_blob_indexes.push_back(blob_index);
1199 }
1200 }
1201
1202 for (size_t i = 0; i < blobs.size(); i++)
1203 {
1204 if (blobs[i].producer != -1 && blobs[i].consumer == -1)
1205 {
1206 output_blob_indexes.push_back(i);
1207 }
1208 }
1209}
1210
1211#if NCNN_STRING
1212void NetPrivate::update_input_output_names()
1213{
1214 input_blob_names.clear();
1215 output_blob_names.clear();
1216
1217 for (size_t i = 0; i < input_blob_indexes.size(); i++)
1218 {
1219 int blob_index = input_blob_indexes[i];
1220 input_blob_names.push_back(blobs[blob_index].name.c_str());
1221 }
1222
1223 for (size_t i = 0; i < output_blob_indexes.size(); i++)
1224 {
1225 int blob_index = output_blob_indexes[i];
1226 output_blob_names.push_back(blobs[blob_index].name.c_str());
1227 }
1228}
1229#endif // NCNN_STRING
1230
1231Net::Net()
1232 : d(new NetPrivate(opt))
1233{
1234}
1235
1236Net::~Net()
1237{
1238 clear();
1239
1240 delete d;
1241}
1242
1243Net::Net(const Net&)
1244 : d(0)
1245{
1246}
1247
1248Net& Net::operator=(const Net&)
1249{
1250 return *this;
1251}
1252
1253#if NCNN_STRING
1254int Net::register_custom_layer(const char* type, layer_creator_func creator, layer_destroyer_func destroyer, void* userdata)
1255{
1256 int typeindex = layer_to_index(type);
1257 if (typeindex != -1)
1258 {
1259 NCNN_LOGE("overwrite built-in layer type %s", type);
1260
1261 for (size_t i = 0; i < d->overwrite_builtin_layer_registry.size(); i++)
1262 {
1263 if (d->overwrite_builtin_layer_registry[i].typeindex == typeindex)
1264 {
1265 NCNN_LOGE("overwrite existing overwritten built-in layer index %d", typeindex);
1266
1267 d->overwrite_builtin_layer_registry[i].creator = creator;
1268 d->overwrite_builtin_layer_registry[i].destroyer = destroyer;
1269 d->overwrite_builtin_layer_registry[i].userdata = userdata;
1270 return 0;
1271 }
1272 }
1273
1274 struct overwrite_builtin_layer_registry_entry entry = {typeindex, creator, destroyer, userdata};
1275 d->overwrite_builtin_layer_registry.push_back(entry);
1276 return 0;
1277 }
1278
1279 int custom_index = custom_layer_to_index(type);
1280 if (custom_index == -1)
1281 {
1282 struct custom_layer_registry_entry entry = {type, creator, destroyer, userdata};
1283 d->custom_layer_registry.push_back(entry);
1284 }
1285 else
1286 {
1287 NCNN_LOGE("overwrite existing custom layer type %s", type);
1288 d->custom_layer_registry[custom_index].name = type;
1289 d->custom_layer_registry[custom_index].creator = creator;
1290 d->custom_layer_registry[custom_index].destroyer = destroyer;
1291 d->custom_layer_registry[custom_index].userdata = userdata;
1292 }
1293
1294 return 0;
1295}
1296#endif // NCNN_STRING
1297
1298int Net::register_custom_layer(int index, layer_creator_func creator, layer_destroyer_func destroyer, void* userdata)
1299{
1300 int custom_index = index & ~LayerType::CustomBit;
1301 if (index == custom_index)
1302 {
1303 NCNN_LOGE("overwrite built-in layer type %d", index);
1304
1305 for (size_t i = 0; i < d->overwrite_builtin_layer_registry.size(); i++)
1306 {
1307 if (d->overwrite_builtin_layer_registry[i].typeindex == index)
1308 {
1309 NCNN_LOGE("overwrite existing overwritten built-in layer index %d", index);
1310
1311 d->overwrite_builtin_layer_registry[i].creator = creator;
1312 d->overwrite_builtin_layer_registry[i].destroyer = destroyer;
1313 d->overwrite_builtin_layer_registry[i].userdata = userdata;
1314 return 0;
1315 }
1316 }
1317
1318 struct overwrite_builtin_layer_registry_entry entry = {index, creator, destroyer, userdata};
1319 d->overwrite_builtin_layer_registry.push_back(entry);
1320 return 0;
1321 }
1322
1323 if ((int)d->custom_layer_registry.size() <= custom_index)
1324 {
1325#if NCNN_STRING
1326 struct custom_layer_registry_entry dummy = {"", 0, 0, 0};
1327#else
1328 struct custom_layer_registry_entry dummy = {0, 0, 0};
1329#endif // NCNN_STRING
1330 d->custom_layer_registry.resize(custom_index + 1, dummy);
1331 }
1332
1333 if (d->custom_layer_registry[custom_index].creator)
1334 {
1335 NCNN_LOGE("overwrite existing custom layer index %d", custom_index);
1336 }
1337
1338 d->custom_layer_registry[custom_index].creator = creator;
1339 d->custom_layer_registry[custom_index].destroyer = destroyer;
1340 d->custom_layer_registry[custom_index].userdata = userdata;
1341 return 0;
1342}
1343
1344#if NCNN_STRING
1345int Net::load_param(const DataReader& dr)
1346{
1347#define SCAN_VALUE(fmt, v) \
1348 if (dr.scan(fmt, &v) != 1) \
1349 { \
1350 NCNN_LOGE("parse " #v " failed"); \
1351 return -1; \
1352 }
1353
1354 int magic = 0;
1355 SCAN_VALUE("%d", magic)
1356 if (magic != 7767517)
1357 {
1358 NCNN_LOGE("param is too old, please regenerate");
1359 return -1;
1360 }
1361
1362 // parse
1363 int layer_count = 0;
1364 int blob_count = 0;
1365 SCAN_VALUE("%d", layer_count)
1366 SCAN_VALUE("%d", blob_count)
1367 if (layer_count <= 0 || blob_count <= 0)
1368 {
1369 NCNN_LOGE("invalid layer_count or blob_count");
1370 return -1;
1371 }
1372
1373 d->layers.resize((size_t)layer_count);
1374 d->blobs.resize((size_t)blob_count);
1375
1376#if NCNN_VULKAN
1377 // TODO enable gpu when bf16 conversion implemented
1378 if (opt.use_bf16_storage)
1379 opt.use_vulkan_compute = false;
1380
1381 if (opt.use_vulkan_compute)
1382 {
1383 if (!d->vkdev) d->vkdev = get_gpu_device();
1384 if (!d->vkdev) opt.use_vulkan_compute = false; // no vulkan device, fallback to cpu
1385 }
1386 if (opt.use_vulkan_compute)
1387 {
1388 // sanitize use options
1389 if (!d->vkdev->info.support_fp16_packed()) opt.use_fp16_packed = false;
1390 if (!d->vkdev->info.support_fp16_storage()) opt.use_fp16_storage = false;
1391 if (!d->vkdev->info.support_fp16_uniform()) opt.use_fp16_uniform = false;
1392 if (!d->vkdev->info.support_fp16_arithmetic()) opt.use_fp16_arithmetic = false;
1393 if (!d->vkdev->info.support_int8_packed()) opt.use_int8_packed = false;
1394 if (!d->vkdev->info.support_int8_storage()) opt.use_int8_storage = false;
1395 if (!d->vkdev->info.support_int8_uniform()) opt.use_int8_uniform = false;
1396 if (!d->vkdev->info.support_int8_arithmetic()) opt.use_int8_arithmetic = false;
1397 if (!d->vkdev->info.support_cooperative_matrix()) opt.use_cooperative_matrix = false;
1398
1399 if (d->vkdev->info.bug_buffer_image_load_zero()) opt.use_image_storage = false;
1400
1401 // enable local memory optimization on discrete gpu only
1402 if (d->vkdev->info.type() != 0) opt.use_shader_local_memory = false;
1403
1404 // fp16a makes no sense when fp16 storage disabled
1405 if (!opt.use_fp16_packed && !opt.use_fp16_storage) opt.use_fp16_arithmetic = false;
1406
1407 // fp16 uniform makes no sense when fp16 arithmetic disabled
1408 if (!opt.use_fp16_arithmetic) opt.use_fp16_uniform = false;
1409 }
1410 else
1411 {
1412 // fp16a makes no sense when fp16 storage disabled
1413 if (!opt.use_fp16_storage) opt.use_fp16_arithmetic = false;
1414 }
1415#endif // NCNN_VULKAN
1416
1417 ParamDict pd;
1418
1419 int blob_index = 0;
1420 for (int i = 0; i < layer_count; i++)
1421 {
1422 char layer_type[256];
1423 char layer_name[256];
1424 int bottom_count = 0;
1425 int top_count = 0;
1426 SCAN_VALUE("%255s", layer_type)
1427 SCAN_VALUE("%255s", layer_name)
1428 SCAN_VALUE("%d", bottom_count)
1429 SCAN_VALUE("%d", top_count)
1430
1431 Layer* layer = create_overwrite_builtin_layer(layer_type);
1432#if NCNN_VULKAN
1433 if (!layer && opt.use_vulkan_compute && d->vkdev)
1434 {
1435 layer = create_layer_vulkan(layer_type);
1436 }
1437#endif // NCNN_VULKAN
1438 if (!layer)
1439 {
1440 layer = create_layer_cpu(layer_type);
1441 }
1442 if (!layer)
1443 {
1444 layer = create_custom_layer(layer_type);
1445 }
1446 if (!layer)
1447 {
1448 NCNN_LOGE("layer %s not exists or registered", layer_type);
1449 clear();
1450 return -1;
1451 }
1452
1453#if NCNN_VULKAN
1454 if (opt.use_vulkan_compute)
1455 layer->vkdev = d->vkdev;
1456#endif // NCNN_VULKAN
1457
1458 layer->type = std::string(layer_type);
1459 layer->name = std::string(layer_name);
1460 // NCNN_LOGE("new layer %d %s", i, layer_name);
1461
1462 layer->bottoms.resize(bottom_count);
1463 for (int j = 0; j < bottom_count; j++)
1464 {
1465 char bottom_name[256];
1466 SCAN_VALUE("%255s", bottom_name)
1467
1468 int bottom_blob_index = find_blob_index_by_name(bottom_name);
1469 if (bottom_blob_index == -1)
1470 {
1471 Blob& blob = d->blobs[blob_index];
1472
1473 bottom_blob_index = blob_index;
1474
1475 blob.name = std::string(bottom_name);
1476 // NCNN_LOGE("new blob %s", bottom_name);
1477
1478 blob_index++;
1479 }
1480
1481 Blob& blob = d->blobs[bottom_blob_index];
1482
1483 blob.consumer = i;
1484
1485 layer->bottoms[j] = bottom_blob_index;
1486 }
1487
1488 layer->tops.resize(top_count);
1489 for (int j = 0; j < top_count; j++)
1490 {
1491 Blob& blob = d->blobs[blob_index];
1492
1493 char blob_name[256];
1494 SCAN_VALUE("%255s", blob_name)
1495
1496 blob.name = std::string(blob_name);
1497 // NCNN_LOGE("new blob %s", blob_name);
1498
1499 blob.producer = i;
1500
1501 layer->tops[j] = blob_index;
1502
1503 blob_index++;
1504 }
1505
1506 int layer_support_vulkan = layer->support_vulkan;
1507
1508 // layer specific params
1509 int pdlr = pd.load_param(dr);
1510 if (pdlr != 0)
1511 {
1512 NCNN_LOGE("ParamDict load_param %d %s failed", i, layer_name);
1513 continue;
1514 }
1515
1516 // pull out top shape hints
1517 Mat shape_hints = pd.get(30, Mat());
1518 if (!shape_hints.empty())
1519 {
1520 const int* psh = shape_hints;
1521 for (int j = 0; j < top_count; j++)
1522 {
1523 Blob& blob = d->blobs[layer->tops[j]];
1524
1525 int dims = psh[0];
1526 if (dims == 1)
1527 {
1528 blob.shape = Mat(psh[1], (void*)0, 4u, 1);
1529 }
1530 if (dims == 2)
1531 {
1532 blob.shape = Mat(psh[1], psh[2], (void*)0, 4u, 1);
1533 }
1534 if (dims == 3)
1535 {
1536 blob.shape = Mat(psh[1], psh[2], psh[3], (void*)0, 4u, 1);
1537 }
1538
1539 psh += 4;
1540 }
1541 }
1542
1543 // set bottom and top shape hints
1544 layer->bottom_shapes.resize(bottom_count);
1545 for (int j = 0; j < bottom_count; j++)
1546 {
1547 layer->bottom_shapes[j] = d->blobs[layer->bottoms[j]].shape;
1548 }
1549
1550 layer->top_shapes.resize(top_count);
1551 for (int j = 0; j < top_count; j++)
1552 {
1553 layer->top_shapes[j] = d->blobs[layer->tops[j]].shape;
1554 }
1555
1556 // pull out layer specific feature disabled set
1557 layer->featmask = pd.get(31, 0);
1558
1559 int lr = layer->load_param(pd);
1560 if (lr != 0)
1561 {
1562 NCNN_LOGE("layer load_param %d %s failed", i, layer_name);
1563 continue;
1564 }
1565
1566 if (layer->support_int8_storage)
1567 {
1568 // no int8 gpu support yet
1569 opt.use_vulkan_compute = false;
1570 }
1571
1572 Option opt1 = get_masked_option(opt, layer->featmask);
1573#if NCNN_VULKAN
1574 if (opt1.use_vulkan_compute)
1575 {
1576 if (!layer->support_image_storage) opt1.use_image_storage = false;
1577 }
1578#endif // NCNN_VULKAN
1579
1580 if (layer_support_vulkan && (!layer->support_vulkan || !opt1.use_vulkan_compute))
1581 {
1582 // vulkan layer cannot handle these param, recreate cpu layer
1583 Layer* layer_cpu = create_overwrite_builtin_layer(layer_type);
1584 if (!layer_cpu)
1585 {
1586 layer_cpu = create_layer_cpu(layer_type);
1587 }
1588 if (!layer_cpu)
1589 {
1590 layer_cpu = create_custom_layer(layer_type);
1591 }
1592 if (!layer_cpu)
1593 {
1594 NCNN_LOGE("layer %s not exists or registered", layer_type);
1595 clear();
1596 return -1;
1597 }
1598
1599 layer_cpu->type = layer->type;
1600 layer_cpu->name = layer->name;
1601 layer_cpu->bottoms = layer->bottoms;
1602 layer_cpu->tops = layer->tops;
1603 layer_cpu->bottom_shapes = layer->bottom_shapes;
1604 layer_cpu->top_shapes = layer->top_shapes;
1605 layer_cpu->featmask = layer->featmask;
1606
1607 int lr = layer_cpu->load_param(pd);
1608 if (lr != 0)
1609 {
1610 NCNN_LOGE("layer load_param %d %s failed", i, layer_name);
1611 continue;
1612 }
1613
1614 delete layer;
1615 layer = layer_cpu;
1616 }
1617
1618 d->layers[i] = layer;
1619 }
1620
1621 d->update_input_output_indexes();
1622 d->update_input_output_names();
1623
1624#undef SCAN_VALUE
1625 return 0;
1626}
1627#endif // NCNN_STRING
1628
1629int Net::load_param_bin(const DataReader& dr)
1630{
1631#if __BIG_ENDIAN__
1632#define READ_VALUE(buf) \
1633 if (dr.read(&buf, sizeof(buf)) != sizeof(buf)) \
1634 { \
1635 NCNN_LOGE("read " #buf " failed"); \
1636 return -1; \
1637 } \
1638 if (sizeof(buf) == 2) \
1639 swap_endianness_16(&buf); \
1640 if (sizeof(buf) == 4) \
1641 swap_endianness_32(&buf);
1642#else
1643#define READ_VALUE(buf) \
1644 if (dr.read(&buf, sizeof(buf)) != sizeof(buf)) \
1645 { \
1646 NCNN_LOGE("read " #buf " failed"); \
1647 return -1; \
1648 }
1649#endif
1650
1651 int magic = 0;
1652 READ_VALUE(magic)
1653 if (magic != 7767517)
1654 {
1655 NCNN_LOGE("param is too old, please regenerate");
1656 return -1;
1657 }
1658
1659 int layer_count = 0;
1660 int blob_count = 0;
1661 READ_VALUE(layer_count)
1662 READ_VALUE(blob_count)
1663 if (layer_count <= 0 || blob_count <= 0)
1664 {
1665 NCNN_LOGE("invalid layer_count or blob_count");
1666 return -1;
1667 }
1668
1669 d->layers.resize(layer_count);
1670 d->blobs.resize(blob_count);
1671
1672#if NCNN_VULKAN
1673 // TODO enable gpu when bf16 conversion implemented
1674 if (opt.use_bf16_storage)
1675 opt.use_vulkan_compute = false;
1676
1677 if (opt.use_vulkan_compute)
1678 {
1679 if (!d->vkdev) d->vkdev = get_gpu_device();
1680 if (!d->vkdev) opt.use_vulkan_compute = false; // no vulkan device, fallback to cpu
1681 }
1682 if (opt.use_vulkan_compute)
1683 {
1684 // sanitize use options
1685 if (!d->vkdev->info.support_fp16_packed()) opt.use_fp16_packed = false;
1686 if (!d->vkdev->info.support_fp16_storage()) opt.use_fp16_storage = false;
1687 if (!d->vkdev->info.support_fp16_uniform()) opt.use_fp16_uniform = false;
1688 if (!d->vkdev->info.support_fp16_arithmetic()) opt.use_fp16_arithmetic = false;
1689 if (!d->vkdev->info.support_int8_packed()) opt.use_int8_packed = false;
1690 if (!d->vkdev->info.support_int8_storage()) opt.use_int8_storage = false;
1691 if (!d->vkdev->info.support_int8_uniform()) opt.use_int8_uniform = false;
1692 if (!d->vkdev->info.support_int8_arithmetic()) opt.use_int8_arithmetic = false;
1693 if (!d->vkdev->info.support_cooperative_matrix()) opt.use_cooperative_matrix = false;
1694
1695 if (d->vkdev->info.bug_buffer_image_load_zero()) opt.use_image_storage = false;
1696
1697 // enable local memory optimization on discrete gpu only
1698 if (d->vkdev->info.type() != 0) opt.use_shader_local_memory = false;
1699
1700 // fp16a makes no sense when fp16 storage disabled
1701 if (!opt.use_fp16_packed && !opt.use_fp16_storage) opt.use_fp16_arithmetic = false;
1702
1703 // fp16 uniform makes no sense when fp16 arithmetic disabled
1704 if (!opt.use_fp16_arithmetic) opt.use_fp16_uniform = false;
1705 }
1706 else
1707 {
1708 // fp16a makes no sense when fp16 storage disabled
1709 if (!opt.use_fp16_storage) opt.use_fp16_arithmetic = false;
1710 }
1711#endif // NCNN_VULKAN
1712
1713 ParamDict pd;
1714
1715 for (int i = 0; i < layer_count; i++)
1716 {
1717 int typeindex;
1718 int bottom_count;
1719 int top_count;
1720 READ_VALUE(typeindex)
1721 READ_VALUE(bottom_count)
1722 READ_VALUE(top_count)
1723
1724 Layer* layer = create_overwrite_builtin_layer(typeindex);
1725#if NCNN_VULKAN
1726 if (!layer && opt.use_vulkan_compute && d->vkdev)
1727 {
1728 layer = create_layer_vulkan(typeindex);
1729 }
1730#endif // NCNN_VULKAN
1731 if (!layer)
1732 {
1733 layer = create_layer_cpu(typeindex);
1734 }
1735 if (!layer)
1736 {
1737 int custom_index = typeindex & ~LayerType::CustomBit;
1738 layer = create_custom_layer(custom_index);
1739 }
1740 if (!layer)
1741 {
1742 NCNN_LOGE("layer %d not exists or registered", typeindex);
1743 clear();
1744 return -1;
1745 }
1746
1747#if NCNN_VULKAN
1748 if (opt.use_vulkan_compute)
1749 layer->vkdev = d->vkdev;
1750#endif // NCNN_VULKAN
1751
1752 // layer->type = std::string(layer_type);
1753 // layer->name = std::string(layer_name);
1754 // NCNN_LOGE("new layer %d", typeindex);
1755
1756 layer->bottoms.resize(bottom_count);
1757 for (int j = 0; j < bottom_count; j++)
1758 {
1759 int bottom_blob_index;
1760 READ_VALUE(bottom_blob_index)
1761
1762 Blob& blob = d->blobs[bottom_blob_index];
1763
1764 blob.consumer = i;
1765
1766 layer->bottoms[j] = bottom_blob_index;
1767 }
1768
1769 layer->tops.resize(top_count);
1770 for (int j = 0; j < top_count; j++)
1771 {
1772 int top_blob_index;
1773 READ_VALUE(top_blob_index)
1774
1775 Blob& blob = d->blobs[top_blob_index];
1776
1777 // blob.name = std::string(blob_name);
1778 // NCNN_LOGE("new blob %s", blob_name);
1779
1780 blob.producer = i;
1781
1782 layer->tops[j] = top_blob_index;
1783 }
1784
1785 int layer_support_vulkan = layer->support_vulkan;
1786
1787 // layer specific params
1788 int pdlr = pd.load_param_bin(dr);
1789 if (pdlr != 0)
1790 {
1791 NCNN_LOGE("ParamDict load_param_bin %d failed", i);
1792 continue;
1793 }
1794
1795 // pull out top blob shape hints
1796 Mat shape_hints = pd.get(30, Mat());
1797 if (!shape_hints.empty())
1798 {
1799 const int* psh = shape_hints;
1800 for (int j = 0; j < top_count; j++)
1801 {
1802 Blob& blob = d->blobs[layer->tops[j]];
1803
1804 int dims = psh[0];
1805 if (dims == 1)
1806 {
1807 blob.shape = Mat(psh[1], (void*)0, 4u, 1);
1808 }
1809 if (dims == 2)
1810 {
1811 blob.shape = Mat(psh[1], psh[2], (void*)0, 4u, 1);
1812 }
1813 if (dims == 3)
1814 {
1815 blob.shape = Mat(psh[1], psh[2], psh[3], (void*)0, 4u, 1);
1816 }
1817
1818 psh += 4;
1819 }
1820 }
1821
1822 // set bottom and top shape hints
1823 layer->bottom_shapes.resize(bottom_count);
1824 for (int j = 0; j < bottom_count; j++)
1825 {
1826 layer->bottom_shapes[j] = d->blobs[layer->bottoms[j]].shape;
1827 }
1828
1829 layer->top_shapes.resize(top_count);
1830 for (int j = 0; j < top_count; j++)
1831 {
1832 layer->top_shapes[j] = d->blobs[layer->tops[j]].shape;
1833 }
1834
1835 // pull out layer specific feature disabled set
1836 layer->featmask = pd.get(31, 0);
1837
1838 int lr = layer->load_param(pd);
1839 if (lr != 0)
1840 {
1841 NCNN_LOGE("layer load_param %d failed", i);
1842 continue;
1843 }
1844
1845 if (layer->support_int8_storage)
1846 {
1847 // no int8 gpu support yet
1848 opt.use_vulkan_compute = false;
1849 }
1850
1851 Option opt1 = get_masked_option(opt, layer->featmask);
1852#if NCNN_VULKAN
1853 if (opt1.use_vulkan_compute)
1854 {
1855 if (!layer->support_image_storage) opt1.use_image_storage = false;
1856 }
1857#endif // NCNN_VULKAN
1858
1859 if (layer_support_vulkan && (!layer->support_vulkan || !opt1.use_vulkan_compute))
1860 {
1861 // vulkan layer cannot handle these param, recreate cpu layer
1862 Layer* layer_cpu = create_overwrite_builtin_layer(typeindex);
1863 if (!layer_cpu)
1864 {
1865 layer_cpu = create_layer_cpu(typeindex);
1866 }
1867 if (!layer_cpu)
1868 {
1869 int custom_index = typeindex & ~LayerType::CustomBit;
1870 layer_cpu = create_custom_layer(custom_index);
1871 }
1872 if (!layer_cpu)
1873 {
1874 NCNN_LOGE("layer %d not exists or registered", typeindex);
1875 clear();
1876 return -1;
1877 }
1878
1879 layer_cpu->bottoms = layer->bottoms;
1880 layer_cpu->tops = layer->tops;
1881 layer_cpu->bottom_shapes = layer->bottom_shapes;
1882 layer_cpu->top_shapes = layer->top_shapes;
1883 layer_cpu->featmask = layer->featmask;
1884
1885 int lr = layer_cpu->load_param(pd);
1886 if (lr != 0)
1887 {
1888 NCNN_LOGE("layer load_param %d failed", i);
1889 continue;
1890 }
1891
1892 delete layer;
1893 layer = layer_cpu;
1894 }
1895
1896 d->layers[i] = layer;
1897 }
1898
1899 d->update_input_output_indexes();
1900
1901#undef READ_VALUE
1902 return 0;
1903}
1904
1905int Net::load_model(const DataReader& dr)
1906{
1907 if (d->layers.empty())
1908 {
1909 NCNN_LOGE("network graph not ready");
1910 return -1;
1911 }
1912
1913 int layer_count = (int)d->layers.size();
1914
1915 // load file
1916 int ret = 0;
1917
1918#if NCNN_VULKAN
1919 if (opt.use_vulkan_compute)
1920 {
1921 if (!opt.pipeline_cache)
1922 {
1923 if (!d->pipeline_cache)
1924 d->pipeline_cache = new PipelineCache(d->vkdev);
1925 opt.pipeline_cache = d->pipeline_cache;
1926 }
1927 }
1928#endif // NCNN_VULKAN
1929
1930 ModelBinFromDataReader mb(dr);
1931 for (int i = 0; i < layer_count; i++)
1932 {
1933 Layer* layer = d->layers[i];
1934
1935 //Here we found inconsistent content in the parameter file.
1936 if (!layer)
1937 {
1938 NCNN_LOGE("load_model error at layer %d, parameter file has inconsistent content.", i);
1939 ret = -1;
1940 break;
1941 }
1942
1943 int lret = layer->load_model(mb);
1944 if (lret != 0)
1945 {
1946#if NCNN_STRING
1947 NCNN_LOGE("layer load_model %d %s failed", i, layer->name.c_str());
1948#else
1949 NCNN_LOGE("layer load_model %d failed", i);
1950#endif
1951 ret = -1;
1952 break;
1953 }
1954
1955 Option opt1 = get_masked_option(opt, layer->featmask);
1956
1957 int cret = layer->create_pipeline(opt1);
1958 if (cret != 0)
1959 {
1960#if NCNN_STRING
1961 NCNN_LOGE("layer create_pipeline %d %s failed", i, layer->name.c_str());
1962#else
1963 NCNN_LOGE("layer create_pipeline %d failed", i);
1964#endif
1965 ret = -1;
1966 break;
1967 }
1968 }
1969
1970 if (opt.use_local_pool_allocator)
1971 {
1972 if (opt.blob_allocator == 0)
1973 {
1974 if (!d->local_blob_allocator)
1975 {
1976 d->local_blob_allocator = new PoolAllocator;
1977 d->local_blob_allocator->set_size_compare_ratio(0.f);
1978 }
1979 }
1980 if (opt.workspace_allocator == 0)
1981 {
1982 if (!d->local_workspace_allocator)
1983 {
1984 d->local_workspace_allocator = new PoolAllocator;
1985 d->local_workspace_allocator->set_size_compare_ratio(0.f);
1986 }
1987 }
1988 }
1989
1990#if NCNN_VULKAN
1991 if (ret == 0 && opt.use_vulkan_compute)
1992 {
1993 ret = d->upload_model();
1994 }
1995#endif // NCNN_VULKAN
1996
1997 return ret;
1998}
1999
2000#if NCNN_STDIO
2001#if NCNN_STRING
2002int Net::load_param(FILE* fp)
2003{
2004 DataReaderFromStdio dr(fp);
2005 return load_param(dr);
2006}
2007
2008int Net::load_param_mem(const char* _mem)
2009{
2010 const unsigned char* mem = (const unsigned char*)_mem;
2011 DataReaderFromMemory dr(mem);
2012 return load_param(dr);
2013}
2014
2015int Net::load_param(const char* protopath)
2016{
2017 FILE* fp = fopen(protopath, "rb");
2018 if (!fp)
2019 {
2020 NCNN_LOGE("fopen %s failed", protopath);
2021 return -1;
2022 }
2023
2024 int ret = load_param(fp);
2025 fclose(fp);
2026 return ret;
2027}
2028#endif // NCNN_STRING
2029
2030int Net::load_param_bin(FILE* fp)
2031{
2032 DataReaderFromStdio dr(fp);
2033 return load_param_bin(dr);
2034}
2035
2036int Net::load_param_bin(const char* protopath)
2037{
2038 FILE* fp = fopen(protopath, "rb");
2039 if (!fp)
2040 {
2041 NCNN_LOGE("fopen %s failed", protopath);
2042 return -1;
2043 }
2044
2045 int ret = load_param_bin(fp);
2046 fclose(fp);
2047 return ret;
2048}
2049
2050int Net::load_model(FILE* fp)
2051{
2052 DataReaderFromStdio dr(fp);
2053 return load_model(dr);
2054}
2055
2056int Net::load_model(const char* modelpath)
2057{
2058 FILE* fp = fopen(modelpath, "rb");
2059 if (!fp)
2060 {
2061 NCNN_LOGE("fopen %s failed", modelpath);
2062 return -1;
2063 }
2064
2065 int ret = load_model(fp);
2066 fclose(fp);
2067 return ret;
2068}
2069#endif // NCNN_STDIO
2070
2071int Net::load_param(const unsigned char* _mem)
2072{
2073 const unsigned char* mem = _mem;
2074 DataReaderFromMemory dr(mem);
2075 load_param_bin(dr);
2076 return static_cast<int>(mem - _mem);
2077}
2078
2079int Net::load_model(const unsigned char* _mem)
2080{
2081 const unsigned char* mem = _mem;
2082 DataReaderFromMemory dr(mem);
2083 load_model(dr);
2084 return static_cast<int>(mem - _mem);
2085}
2086
2087#if NCNN_PLATFORM_API
2088#if __ANDROID_API__ >= 9
2089#if NCNN_STRING
2090int Net::load_param(AAsset* asset)
2091{
2092 DataReaderFromAndroidAsset dr(asset);
2093 return load_param(dr);
2094}
2095
2096int Net::load_param(AAssetManager* mgr, const char* assetpath)
2097{
2098 AAsset* asset = AAssetManager_open(mgr, assetpath, AASSET_MODE_BUFFER);
2099 if (!asset)
2100 {
2101 NCNN_LOGE("AAssetManager_open %s failed", assetpath);
2102 return -1;
2103 }
2104
2105 int ret = load_param(asset);
2106 AAsset_close(asset);
2107 return ret;
2108}
2109#endif // NCNN_STRING
2110
2111int Net::load_param_bin(AAsset* asset)
2112{
2113 DataReaderFromAndroidAsset dr(asset);
2114 return load_param_bin(dr);
2115}
2116
2117int Net::load_param_bin(AAssetManager* mgr, const char* assetpath)
2118{
2119 AAsset* asset = AAssetManager_open(mgr, assetpath, AASSET_MODE_BUFFER);
2120 if (!asset)
2121 {
2122 NCNN_LOGE("AAssetManager_open %s failed", assetpath);
2123 return -1;
2124 }
2125
2126 int ret = load_param_bin(asset);
2127 AAsset_close(asset);
2128 return ret;
2129}
2130
2131int Net::load_model(AAsset* asset)
2132{
2133 DataReaderFromAndroidAsset dr(asset);
2134 return load_model(dr);
2135}
2136
2137int Net::load_model(AAssetManager* mgr, const char* assetpath)
2138{
2139 AAsset* asset = AAssetManager_open(mgr, assetpath, AASSET_MODE_STREAMING);
2140 if (!asset)
2141 {
2142 NCNN_LOGE("AAssetManager_open %s failed", assetpath);
2143 return -1;
2144 }
2145
2146 int ret = load_model(asset);
2147 AAsset_close(asset);
2148 return ret;
2149}
2150#endif // __ANDROID_API__ >= 9
2151#endif // NCNN_PLATFORM_API
2152
2153void Net::clear()
2154{
2155 d->blobs.clear();
2156 for (size_t i = 0; i < d->layers.size(); i++)
2157 {
2158 Layer* layer = d->layers[i];
2159
2160 Option opt1 = get_masked_option(opt, layer->featmask);
2161#if NCNN_VULKAN
2162 if (!layer->support_image_storage)
2163 {
2164 opt1.use_image_storage = false;
2165 }
2166#endif // NCNN_VULKAN
2167
2168 int dret = layer->destroy_pipeline(opt1);
2169 if (dret != 0)
2170 {
2171 NCNN_LOGE("layer destroy_pipeline failed");
2172 // ignore anyway
2173 }
2174
2175 if (layer->typeindex & ncnn::LayerType::CustomBit)
2176 {
2177 int custom_index = layer->typeindex & ~ncnn::LayerType::CustomBit;
2178 if (d->custom_layer_registry[custom_index].destroyer)
2179 {
2180 d->custom_layer_registry[custom_index].destroyer(layer, d->custom_layer_registry[custom_index].userdata);
2181 }
2182 else
2183 {
2184 delete layer;
2185 }
2186 }
2187 else
2188 {
2189 // check overwrite builtin layer destroyer
2190 int index = -1;
2191 const size_t overwrite_builtin_layer_registry_entry_count = d->overwrite_builtin_layer_registry.size();
2192 for (size_t i = 0; i < overwrite_builtin_layer_registry_entry_count; i++)
2193 {
2194 if (d->overwrite_builtin_layer_registry[i].typeindex == layer->typeindex)
2195 {
2196 index = i;
2197 break;
2198 }
2199 }
2200
2201 if (index != -1 && d->overwrite_builtin_layer_registry[index].destroyer)
2202 {
2203 d->overwrite_builtin_layer_registry[index].destroyer(layer, d->overwrite_builtin_layer_registry[index].userdata);
2204 }
2205 else
2206 {
2207 delete layer;
2208 }
2209 }
2210 }
2211 d->layers.clear();
2212
2213 if (d->local_blob_allocator)
2214 {
2215 delete d->local_blob_allocator;
2216 d->local_blob_allocator = 0;
2217 }
2218 if (d->local_workspace_allocator)
2219 {
2220 delete d->local_workspace_allocator;
2221 d->local_workspace_allocator = 0;
2222 }
2223
2224#if NCNN_VULKAN
2225 if (d->weight_vkallocator)
2226 {
2227 delete d->weight_vkallocator;
2228 d->weight_vkallocator = 0;
2229 }
2230 if (d->weight_staging_vkallocator)
2231 {
2232 delete d->weight_staging_vkallocator;
2233 d->weight_staging_vkallocator = 0;
2234 }
2235 if (d->pipeline_cache)
2236 {
2237 delete d->pipeline_cache;
2238 d->pipeline_cache = 0;
2239 opt.pipeline_cache = 0;
2240 }
2241#endif // NCNN_VULKAN
2242}
2243
2244Extractor Net::create_extractor() const
2245{
2246 return Extractor(this, d->blobs.size());
2247}
2248
2249const std::vector<int>& Net::input_indexes() const
2250{
2251 return d->input_blob_indexes;
2252}
2253
2254const std::vector<int>& Net::output_indexes() const
2255{
2256 return d->output_blob_indexes;
2257}
2258
2259#if NCNN_STRING
2260const std::vector<const char*>& Net::input_names() const
2261{
2262 return d->input_blob_names;
2263}
2264
2265const std::vector<const char*>& Net::output_names() const
2266{
2267 return d->output_blob_names;
2268}
2269#endif
2270
2271const std::vector<Blob>& Net::blobs() const
2272{
2273 return d->blobs;
2274}
2275
2276const std::vector<Layer*>& Net::layers() const
2277{
2278 return d->layers;
2279}
2280
2281std::vector<Blob>& Net::mutable_blobs()
2282{
2283 return d->blobs;
2284}
2285
2286std::vector<Layer*>& Net::mutable_layers()
2287{
2288 return d->layers;
2289}
2290
2291#if NCNN_VULKAN
2292void Net::set_vulkan_device(int device_index)
2293{
2294 d->vkdev = get_gpu_device(device_index);
2295}
2296
2297void Net::set_vulkan_device(const VulkanDevice* _vkdev)
2298{
2299 d->vkdev = _vkdev;
2300}
2301
2302const VulkanDevice* Net::vulkan_device() const
2303{
2304 return d->vkdev;
2305}
2306#endif // NCNN_VULKAN
2307
2308#if NCNN_STRING
2309int Net::find_blob_index_by_name(const char* name) const
2310{
2311 for (size_t i = 0; i < d->blobs.size(); i++)
2312 {
2313 const Blob& blob = d->blobs[i];
2314 if (blob.name == name)
2315 {
2316 return static_cast<int>(i);
2317 }
2318 }
2319
2320 NCNN_LOGE("find_blob_index_by_name %s failed", name);
2321 return -1;
2322}
2323
2324int Net::find_layer_index_by_name(const char* name) const
2325{
2326 for (size_t i = 0; i < d->layers.size(); i++)
2327 {
2328 const Layer* layer = d->layers[i];
2329 if (layer->name == name)
2330 {
2331 return static_cast<int>(i);
2332 }
2333 }
2334
2335 NCNN_LOGE("find_layer_index_by_name %s failed", name);
2336 return -1;
2337}
2338
2339int Net::custom_layer_to_index(const char* type)
2340{
2341 const size_t custom_layer_registry_entry_count = d->custom_layer_registry.size();
2342 for (size_t i = 0; i < custom_layer_registry_entry_count; i++)
2343 {
2344 if (strcmp(type, d->custom_layer_registry[i].name) == 0)
2345 return static_cast<int>(i);
2346 }
2347
2348 return -1;
2349}
2350
2351Layer* Net::create_custom_layer(const char* type)
2352{
2353 int index = custom_layer_to_index(type);
2354 if (index == -1)
2355 return 0;
2356
2357 return create_custom_layer(index);
2358}
2359
2360Layer* Net::create_overwrite_builtin_layer(const char* type)
2361{
2362 int typeindex = layer_to_index(type);
2363 if (typeindex == -1)
2364 return 0;
2365
2366 return create_overwrite_builtin_layer(typeindex);
2367}
2368#endif // NCNN_STRING
2369
2370Layer* Net::create_custom_layer(int index)
2371{
2372 const size_t custom_layer_registry_entry_count = d->custom_layer_registry.size();
2373 if (index < 0 || static_cast<unsigned int>(index) >= custom_layer_registry_entry_count)
2374 return 0;
2375
2376 layer_creator_func layer_creator = d->custom_layer_registry[index].creator;
2377 if (!layer_creator)
2378 return 0;
2379
2380 Layer* layer = layer_creator(d->custom_layer_registry[index].userdata);
2381 layer->typeindex = ncnn::LayerType::CustomBit | index;
2382 return layer;
2383}
2384
2385Layer* Net::create_overwrite_builtin_layer(int typeindex)
2386{
2387 int index = -1;
2388 const size_t overwrite_builtin_layer_registry_entry_count = d->overwrite_builtin_layer_registry.size();
2389 for (size_t i = 0; i < overwrite_builtin_layer_registry_entry_count; i++)
2390 {
2391 if (d->overwrite_builtin_layer_registry[i].typeindex == typeindex)
2392 {
2393 index = i;
2394 break;
2395 }
2396 }
2397
2398 if (index == -1)
2399 return 0;
2400
2401 layer_creator_func layer_creator = d->overwrite_builtin_layer_registry[index].creator;
2402 if (!layer_creator)
2403 return 0;
2404
2405 Layer* layer = layer_creator(d->overwrite_builtin_layer_registry[index].userdata);
2406 layer->typeindex = typeindex;
2407 return layer;
2408}
2409
2410class ExtractorPrivate
2411{
2412public:
2413 ExtractorPrivate(const Net* _net)
2414 : net(_net)
2415 {
2416 }
2417 const Net* net;
2418 std::vector<Mat> blob_mats;
2419 Option opt;
2420
2421#if NCNN_VULKAN
2422 VkAllocator* local_blob_vkallocator;
2423 VkAllocator* local_staging_vkallocator;
2424
2425 std::vector<VkMat> blob_mats_gpu;
2426 std::vector<VkImageMat> blob_mats_gpu_image;
2427#endif // NCNN_VULKAN
2428};
2429
2430Extractor::Extractor(const Net* _net, size_t blob_count)
2431 : d(new ExtractorPrivate(_net))
2432{
2433 d->blob_mats.resize(blob_count);
2434 d->opt = d->net->opt;
2435
2436#if NCNN_VULKAN
2437 if (d->net->opt.use_vulkan_compute)
2438 {
2439 d->local_blob_vkallocator = 0;
2440 d->local_staging_vkallocator = 0;
2441
2442 d->blob_mats_gpu.resize(blob_count);
2443 d->blob_mats_gpu_image.resize(blob_count);
2444 }
2445#endif // NCNN_VULKAN
2446}
2447
2448Extractor::~Extractor()
2449{
2450 clear();
2451
2452 delete d;
2453}
2454
2455Extractor::Extractor(const Extractor& rhs)
2456 : d(new ExtractorPrivate(0))
2457{
2458 d->net = rhs.d->net;
2459 d->blob_mats = rhs.d->blob_mats;
2460 d->opt = rhs.d->opt;
2461
2462#if NCNN_VULKAN
2463 d->local_blob_vkallocator = 0;
2464 d->local_staging_vkallocator = 0;
2465
2466 d->blob_mats_gpu = rhs.d->blob_mats_gpu;
2467 d->blob_mats_gpu_image = rhs.d->blob_mats_gpu_image;
2468#endif // NCNN_VULKAN
2469}
2470
2471Extractor& Extractor::operator=(const Extractor& rhs)
2472{
2473 if (this == &rhs)
2474 return *this;
2475
2476 d->net = rhs.d->net;
2477 d->blob_mats = rhs.d->blob_mats;
2478 d->opt = rhs.d->opt;
2479
2480#if NCNN_VULKAN
2481 d->local_blob_vkallocator = 0;
2482 d->local_staging_vkallocator = 0;
2483
2484 d->blob_mats_gpu = rhs.d->blob_mats_gpu;
2485 d->blob_mats_gpu_image = rhs.d->blob_mats_gpu_image;
2486#endif // NCNN_VULKAN
2487
2488 return *this;
2489}
2490
2491void Extractor::clear()
2492{
2493 d->blob_mats.clear();
2494
2495#if NCNN_VULKAN
2496 if (d->opt.use_vulkan_compute)
2497 {
2498 d->blob_mats_gpu.clear();
2499 d->blob_mats_gpu_image.clear();
2500
2501 if (d->local_blob_vkallocator)
2502 {
2503 d->net->vulkan_device()->reclaim_blob_allocator(d->local_blob_vkallocator);
2504 }
2505 if (d->local_staging_vkallocator)
2506 {
2507 d->net->vulkan_device()->reclaim_staging_allocator(d->local_staging_vkallocator);
2508 }
2509 }
2510#endif // NCNN_VULKAN
2511}
2512
2513void Extractor::set_light_mode(bool enable)
2514{
2515 d->opt.lightmode = enable;
2516}
2517
2518void Extractor::set_num_threads(int num_threads)
2519{
2520 NCNN_LOGE("ex.set_num_threads() is no-op, please set net.opt.num_threads=N before net.load_param()");
2521 NCNN_LOGE("If you want to use single thread for only some layer, see https://github.com/Tencent/ncnn/wiki/layer-feat-mask");
2522}
2523
2524void Extractor::set_blob_allocator(Allocator* allocator)
2525{
2526 d->opt.blob_allocator = allocator;
2527}
2528
2529void Extractor::set_workspace_allocator(Allocator* allocator)
2530{
2531 d->opt.workspace_allocator = allocator;
2532}
2533
2534#if NCNN_VULKAN
2535void Extractor::set_vulkan_compute(bool enable)
2536{
2537 NCNN_LOGE("ex.set_vulkan_compute() is no-op, please set net.opt.use_vulkan_compute=true/false before net.load_param()");
2538 NCNN_LOGE("If you want to disable vulkan for only some layer, see https://github.com/Tencent/ncnn/wiki/layer-feat-mask");
2539}
2540
2541void Extractor::set_blob_vkallocator(VkAllocator* allocator)
2542{
2543 d->opt.blob_vkallocator = allocator;
2544}
2545
2546void Extractor::set_workspace_vkallocator(VkAllocator* allocator)
2547{
2548 d->opt.workspace_vkallocator = allocator;
2549}
2550
2551void Extractor::set_staging_vkallocator(VkAllocator* allocator)
2552{
2553 d->opt.staging_vkallocator = allocator;
2554}
2555#endif // NCNN_VULKAN
2556
2557#if NCNN_STRING
2558int Extractor::input(const char* blob_name, const Mat& in)
2559{
2560 int blob_index = d->net->find_blob_index_by_name(blob_name);
2561 if (blob_index == -1)
2562 {
2563 NCNN_LOGE("Try");
2564 const std::vector<const char*>& input_names = d->net->input_names();
2565 for (size_t i = 0; i < input_names.size(); i++)
2566 {
2567 NCNN_LOGE(" ex.input(\"%s\", in%d);", input_names[i], (int)i);
2568 }
2569
2570 return -1;
2571 }
2572
2573 return input(blob_index, in);
2574}
2575
2576int Extractor::extract(const char* blob_name, Mat& feat, int type)
2577{
2578 int blob_index = d->net->find_blob_index_by_name(blob_name);
2579 if (blob_index == -1)
2580 {
2581 NCNN_LOGE("Try");
2582 const std::vector<const char*>& output_names = d->net->output_names();
2583 for (size_t i = 0; i < output_names.size(); i++)
2584 {
2585 NCNN_LOGE(" ex.extract(\"%s\", out%d);", output_names[i], (int)i);
2586 }
2587
2588 return -1;
2589 }
2590
2591 return extract(blob_index, feat, type);
2592}
2593#endif // NCNN_STRING
2594
2595int Extractor::input(int blob_index, const Mat& in)
2596{
2597 if (blob_index < 0 || blob_index >= (int)d->blob_mats.size())
2598 return -1;
2599
2600 d->blob_mats[blob_index] = in;
2601
2602 return 0;
2603}
2604
2605int Extractor::extract(int blob_index, Mat& feat, int type)
2606{
2607 if (blob_index < 0 || blob_index >= (int)d->blob_mats.size())
2608 return -1;
2609
2610 int old_blocktime = get_kmp_blocktime();
2611 set_kmp_blocktime(d->opt.openmp_blocktime);
2612
2613 int old_flush_denormals = get_flush_denormals();
2614 set_flush_denormals(d->opt.flush_denormals);
2615
2616 int ret = 0;
2617
2618 if (d->blob_mats[blob_index].dims == 0)
2619 {
2620 int layer_index = d->net->blobs()[blob_index].producer;
2621
2622 // use local allocator
2623 if (d->opt.use_local_pool_allocator)
2624 {
2625 if (!d->opt.blob_allocator)
2626 {
2627 d->opt.blob_allocator = d->net->d->local_blob_allocator;
2628 }
2629 if (!d->opt.workspace_allocator)
2630 {
2631 d->opt.workspace_allocator = d->net->d->local_workspace_allocator;
2632 }
2633 }
2634
2635#if NCNN_VULKAN
2636 if (d->opt.use_vulkan_compute)
2637 {
2638 // use local allocator
2639 if (!d->opt.blob_vkallocator)
2640 {
2641 d->local_blob_vkallocator = d->net->vulkan_device()->acquire_blob_allocator();
2642 d->opt.blob_vkallocator = d->local_blob_vkallocator;
2643 }
2644 if (!d->opt.workspace_vkallocator)
2645 {
2646 d->opt.workspace_vkallocator = d->opt.blob_vkallocator;
2647 }
2648 if (!d->opt.staging_vkallocator)
2649 {
2650 d->local_staging_vkallocator = d->net->vulkan_device()->acquire_staging_allocator();
2651 d->opt.staging_vkallocator = d->local_staging_vkallocator;
2652 }
2653
2654 ncnn::VkCompute cmd(d->net->vulkan_device());
2655#if NCNN_BENCHMARK
2656 cmd.create_query_pool(d->net->layers().size() * 2);
2657#endif // NCNN_BENCHMARK
2658
2659 // TODO vkimagemat for adreno
2660 if (d->opt.use_image_storage)
2661 {
2662 VkImageMat feat_gpu;
2663 ret = extract(blob_index, feat_gpu, cmd);
2664
2665 if (ret == 0 && d->blob_mats[blob_index].dims == 0 && feat_gpu.dims != 0)
2666 {
2667 cmd.record_download(feat_gpu, d->blob_mats[blob_index], d->opt);
2668
2669 ret = cmd.submit_and_wait();
2670
2671#if NCNN_BENCHMARK
2672 std::vector<uint64_t> results(d->net->layers().size() * 2);
2673 cmd.get_query_pool_results(0, d->net->layers().size() * 2, results);
2674 for (size_t i = 0; i < d->net->layers().size(); i++)
2675 {
2676 uint64_t start = results[i * 2];
2677 uint64_t end = results[i * 2 + 1];
2678 if (start == 0 || end == 0)
2679 continue;
2680
2681 double duration_us = (end - start) * d->net->vulkan_device()->info.timestamp_period() / 1000;
2682 NCNN_LOGE("%-24s %-30s %8.2lfus |", d->net->layers()[i]->type.c_str(), d->net->layers()[i]->name.c_str(), duration_us);
2683 }
2684#endif // NCNN_BENCHMARK
2685 }
2686 }
2687 else
2688 {
2689 VkMat feat_gpu;
2690 ret = extract(blob_index, feat_gpu, cmd);
2691
2692 if (ret == 0 && d->blob_mats[blob_index].dims == 0 && feat_gpu.dims != 0)
2693 {
2694 cmd.record_download(feat_gpu, d->blob_mats[blob_index], d->opt);
2695
2696 ret = cmd.submit_and_wait();
2697
2698#if NCNN_BENCHMARK
2699 std::vector<uint64_t> results(d->net->layers().size() * 2);
2700 cmd.get_query_pool_results(0, d->net->layers().size() * 2, results);
2701 for (size_t i = 0; i < d->net->layers().size(); i++)
2702 {
2703 uint64_t start = results[i * 2];
2704 uint64_t end = results[i * 2 + 1];
2705 if (start == 0 || end == 0)
2706 continue;
2707
2708 double duration_us = (end - start) * d->net->vulkan_device()->info.timestamp_period() / 1000;
2709 NCNN_LOGE("%-24s %-30s %8.2lfus |", d->net->layers()[i]->type.c_str(), d->net->layers()[i]->name.c_str(), duration_us);
2710 }
2711#endif // NCNN_BENCHMARK
2712 }
2713 }
2714 }
2715 else
2716 {
2717 ret = d->net->d->forward_layer(layer_index, d->blob_mats, d->opt);
2718 }
2719#else
2720 ret = d->net->d->forward_layer(layer_index, d->blob_mats, d->opt);
2721#endif // NCNN_VULKAN
2722 }
2723
2724 feat = d->blob_mats[blob_index];
2725
2726 // empty is valid for outputs
2727 if (!feat.empty())
2728 {
2729 if (d->opt.use_packing_layout && (type == 0) && feat.elempack != 1)
2730 {
2731 Mat bottom_blob_unpacked;
2732 convert_packing(feat, bottom_blob_unpacked, 1, d->opt);
2733 feat = bottom_blob_unpacked;
2734 if (feat.empty())
2735 return -100;
2736 }
2737
2738 // clang-format off
2739 // *INDENT-OFF*
2740#if NCNN_ARM82
2741 if (d->opt.use_fp16_storage && cpu_support_arm_asimdhp() && (type == 0))
2742 {
2743 if (feat.elembits() == 16)
2744 {
2745 Mat feat_fp32;
2746 cast_float16_to_float32(feat, feat_fp32, d->opt);
2747 feat = feat_fp32;
2748 }
2749 }
2750 else
2751#endif // NCNN_ARM82
2752#if NCNN_VFPV4
2753 if (d->opt.use_fp16_storage && !d->opt.use_bf16_storage && cpu_support_arm_vfpv4() && (type == 0))
2754 {
2755 if (feat.elembits() == 16)
2756 {
2757 Mat feat_fp32;
2758 cast_float16_to_float32(feat, feat_fp32, d->opt);
2759 feat = feat_fp32;
2760 }
2761 }
2762 else
2763#endif // NCNN_VFPV4
2764#if NCNN_RVV
2765 if (d->opt.use_fp16_storage && cpu_support_riscv_v() && cpu_support_riscv_zfh() && (type == 0))
2766 {
2767 if (feat.elembits() == 16)
2768 {
2769 Mat feat_fp32;
2770 cast_float16_to_float32(feat, feat_fp32, d->opt);
2771 feat = feat_fp32;
2772 }
2773 }
2774 else
2775#endif // NCNN_RVV
2776#if NCNN_BF16
2777 if (d->opt.use_bf16_storage && (type == 0))
2778 {
2779 if (feat.elembits() == 16)
2780 {
2781 Mat feat_fp32;
2782 cast_bfloat16_to_float32(feat, feat_fp32, d->opt);
2783 feat = feat_fp32;
2784 }
2785 }
2786 else
2787#endif // NCNN_BF16
2788 if (feat.elembits() == 8 && (type == 0))
2789 {
2790 Mat feat_fp32;
2791 cast_int8_to_float32(feat, feat_fp32, d->opt);
2792 feat = feat_fp32;
2793 }
2794 // *INDENT-ON*
2795 // clang-format on
2796 if (feat.empty())
2797 return -100;
2798
2799 if (d->opt.use_local_pool_allocator && feat.allocator == d->net->d->local_blob_allocator)
2800 {
2801 // detach the returned mat from local pool allocator
2802 // so we could destroy net instance much earlier
2803 feat = feat.clone();
2804 if (feat.empty())
2805 return -100;
2806 }
2807 }
2808
2809 set_kmp_blocktime(old_blocktime);
2810 set_flush_denormals(old_flush_denormals);
2811
2812 return ret;
2813}
2814
2815#if NCNN_VULKAN
2816#if NCNN_STRING
2817int Extractor::input(const char* blob_name, const VkMat& in)
2818{
2819 int blob_index = d->net->find_blob_index_by_name(blob_name);
2820 if (blob_index == -1)
2821 {
2822 NCNN_LOGE("Try");
2823 const std::vector<const char*>& input_names = d->net->input_names();
2824 for (size_t i = 0; i < input_names.size(); i++)
2825 {
2826 NCNN_LOGE(" ex.input(\"%s\", in%d);", input_names[i], (int)i);
2827 }
2828
2829 return -1;
2830 }
2831
2832 return input(blob_index, in);
2833}
2834
2835int Extractor::extract(const char* blob_name, VkMat& feat, VkCompute& cmd)
2836{
2837 int blob_index = d->net->find_blob_index_by_name(blob_name);
2838 if (blob_index == -1)
2839 {
2840 NCNN_LOGE("Try");
2841 const std::vector<const char*>& output_names = d->net->output_names();
2842 for (size_t i = 0; i < output_names.size(); i++)
2843 {
2844 NCNN_LOGE(" ex.extract(\"%s\", out%d);", output_names[i], (int)i);
2845 }
2846
2847 return -1;
2848 }
2849
2850 return extract(blob_index, feat, cmd);
2851}
2852
2853int Extractor::input(const char* blob_name, const VkImageMat& in)
2854{
2855 int blob_index = d->net->find_blob_index_by_name(blob_name);
2856 if (blob_index == -1)
2857 {
2858 NCNN_LOGE("Try");
2859 const std::vector<const char*>& input_names = d->net->input_names();
2860 for (size_t i = 0; i < input_names.size(); i++)
2861 {
2862 NCNN_LOGE(" ex.input(\"%s\", in%d);", input_names[i], (int)i);
2863 }
2864
2865 return -1;
2866 }
2867
2868 return input(blob_index, in);
2869}
2870
2871int Extractor::extract(const char* blob_name, VkImageMat& feat, VkCompute& cmd)
2872{
2873 int blob_index = d->net->find_blob_index_by_name(blob_name);
2874 if (blob_index == -1)
2875 {
2876 NCNN_LOGE("Try");
2877 const std::vector<const char*>& output_names = d->net->output_names();
2878 for (size_t i = 0; i < output_names.size(); i++)
2879 {
2880 NCNN_LOGE(" ex.extract(\"%s\", out%d);", output_names[i], (int)i);
2881 }
2882
2883 return -1;
2884 }
2885
2886 return extract(blob_index, feat, cmd);
2887}
2888#endif // NCNN_STRING
2889
2890int Extractor::input(int blob_index, const VkMat& in)
2891{
2892 if (blob_index < 0 || blob_index >= (int)d->blob_mats.size())
2893 return -1;
2894
2895 d->blob_mats_gpu[blob_index] = in;
2896
2897 return 0;
2898}
2899
2900int Extractor::extract(int blob_index, VkMat& feat, VkCompute& cmd)
2901{
2902 if (blob_index < 0 || blob_index >= (int)d->blob_mats.size())
2903 return -1;
2904
2905 int old_blocktime = get_kmp_blocktime();
2906 set_kmp_blocktime(d->opt.openmp_blocktime);
2907
2908 int old_flush_denormals = get_flush_denormals();
2909 set_flush_denormals(d->opt.flush_denormals);
2910
2911 int ret = 0;
2912
2913 if (d->blob_mats_gpu[blob_index].dims == 0)
2914 {
2915 if (d->blob_mats_gpu_image[blob_index].dims != 0)
2916 {
2917 // image to buffer
2918 cmd.record_image_to_buffer(d->blob_mats_gpu_image[blob_index], d->blob_mats_gpu[blob_index], d->opt);
2919 }
2920 else if (d->blob_mats[blob_index].dims != 0)
2921 {
2922 // host to buffer
2923 cmd.record_upload(d->blob_mats[blob_index], d->blob_mats_gpu[blob_index], d->opt);
2924 }
2925 else
2926 {
2927 int layer_index = d->net->blobs()[blob_index].producer;
2928 ret = d->net->d->forward_layer(layer_index, d->blob_mats, d->blob_mats_gpu, cmd, d->opt);
2929 }
2930 }
2931
2932 feat = d->blob_mats_gpu[blob_index];
2933
2934 set_kmp_blocktime(old_blocktime);
2935 set_flush_denormals(old_flush_denormals);
2936
2937 return ret;
2938}
2939
2940int Extractor::input(int blob_index, const VkImageMat& in)
2941{
2942 if (blob_index < 0 || blob_index >= (int)d->blob_mats.size())
2943 return -1;
2944
2945 d->blob_mats_gpu_image[blob_index] = in;
2946
2947 return 0;
2948}
2949
2950int Extractor::extract(int blob_index, VkImageMat& feat, VkCompute& cmd)
2951{
2952 if (blob_index < 0 || blob_index >= (int)d->blob_mats.size())
2953 return -1;
2954
2955 int old_blocktime = get_kmp_blocktime();
2956 set_kmp_blocktime(d->opt.openmp_blocktime);
2957
2958 int old_flush_denormals = get_flush_denormals();
2959 set_flush_denormals(d->opt.flush_denormals);
2960
2961 int ret = 0;
2962
2963 if (d->blob_mats_gpu_image[blob_index].dims == 0)
2964 {
2965 if (d->blob_mats_gpu[blob_index].dims != 0)
2966 {
2967 // buffer to image
2968 cmd.record_buffer_to_image(d->blob_mats_gpu[blob_index], d->blob_mats_gpu_image[blob_index], d->opt);
2969 }
2970 else if (d->blob_mats[blob_index].dims != 0)
2971 {
2972 // host to image
2973 cmd.record_upload(d->blob_mats[blob_index], d->blob_mats_gpu_image[blob_index], d->opt);
2974 }
2975 else
2976 {
2977 int layer_index = d->net->blobs()[blob_index].producer;
2978 ret = d->net->d->forward_layer(layer_index, d->blob_mats, d->blob_mats_gpu, d->blob_mats_gpu_image, cmd, d->opt);
2979 }
2980 }
2981
2982 feat = d->blob_mats_gpu_image[blob_index];
2983
2984 if (feat.empty())
2985 {
2986 NCNN_LOGE("extract %d image allocation failed", blob_index);
2987 ret = -100;
2988 }
2989
2990 set_kmp_blocktime(old_blocktime);
2991 set_flush_denormals(old_flush_denormals);
2992
2993 return ret;
2994}
2995#endif // NCNN_VULKAN
2996
2997} // namespace ncnn