Elffuss BraidHub

kikocis/ncnn public

master · 16.9 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2020 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 "platform.h"
16#include "net.h"
17#include "testutil.h"
18
19#include <stdio.h>
20
21#ifdef __EMSCRIPTEN__
22#include <emscripten.h>
23#endif
24
25static ncnn::Mat generate_ncnn_logo(int pixel_type_to, int w, int h)
26{
27 // clang-format off
28 // *INDENT-OFF*
29 static const unsigned char ncnn_logo_data[16][16] =
30 {
31 {245, 245, 33, 245, 245, 245, 245, 245, 245, 245, 245, 245, 245, 33, 245, 245},
32 {245, 33, 33, 33, 245, 245, 245, 245, 245, 245, 245, 245, 33, 33, 33, 245},
33 {245, 33, 158, 158, 33, 245, 245, 245, 245, 245, 245, 33, 158, 158, 33, 245},
34 { 33, 117, 158, 224, 158, 33, 245, 245, 245, 245, 33, 158, 224, 158, 117, 33},
35 { 33, 117, 224, 224, 224, 66, 33, 33, 33, 33, 66, 224, 224, 224, 117, 33},
36 { 33, 189, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 189, 33},
37 { 33, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 33},
38 { 33, 224, 224, 97, 97, 97, 97, 224, 224, 97, 97, 97, 97, 224, 224, 33},
39 { 33, 224, 224, 97, 33, 0, 189, 224, 224, 97, 0, 33, 97, 224, 224, 33},
40 { 33, 224, 224, 97, 33, 0, 189, 224, 224, 97, 0, 33, 97, 224, 224, 33},
41 { 33, 224, 224, 97, 97, 97, 97, 224, 224, 97, 189, 189, 97, 224, 224, 33},
42 { 33, 66, 66, 66, 224, 224, 224, 224, 224, 224, 224, 224, 66, 66, 66, 33},
43 { 66, 158, 158, 66, 66, 224, 224, 224, 224, 224, 224, 66, 158, 158, 66, 66},
44 { 66, 158, 158, 208, 66, 224, 224, 224, 224, 224, 224, 66, 158, 158, 208, 66},
45 { 66, 224, 202, 158, 66, 224, 224, 224, 224, 224, 224, 66, 224, 202, 158, 66},
46 { 66, 158, 224, 158, 66, 224, 224, 224, 224, 224, 224, 66, 158, 224, 158, 66}
47 };
48 // *INDENT-ON*
49 // clang-format on
50
51 const unsigned char* p_ncnn_logo_data = (const unsigned char*)ncnn_logo_data;
52 ncnn::Mat logo = ncnn::Mat::from_pixels(p_ncnn_logo_data, ncnn::Mat::PIXEL_GRAY | (pixel_type_to << ncnn::Mat::PIXEL_CONVERT_SHIFT), 16, 16);
53
54 ncnn::Mat m;
55 ncnn::Option opt;
56 opt.num_threads = 1;
57 ncnn::resize_nearest(logo, m, w, h, opt);
58 return m;
59}
60
61struct compare_score_index
62{
63 inline bool operator()(const std::pair<float, int>& a, const std::pair<float, int>& b)
64 {
65 return a.first > b.first;
66 }
67};
68
69static int check_top2(const std::vector<float>& cls_scores, float epsilon = 0.001)
70{
71 // partial sort topk with index
72 int size = cls_scores.size();
73 std::vector<std::pair<float, int> > vec;
74 vec.resize(size);
75 for (int i = 0; i < size; i++)
76 {
77 vec[i] = std::make_pair(cls_scores[i], i);
78 }
79
80 std::partial_sort(vec.begin(), vec.begin() + 2, vec.end(), compare_score_index());
81
82 int expect_indexes[2] = {532, 920};
83 float expect_scores[2] = {0.189459f, 0.082801f};
84
85 for (int i = 0; i < 2; i++)
86 {
87 int index = vec[i].second;
88 float score = vec[i].first;
89
90 if (index != expect_indexes[i])
91 {
92 fprintf(stderr, "top %d index not match expect %d but got %d\n", i, expect_indexes[i], index);
93 return -1;
94 }
95
96 if (!NearlyEqual(score, expect_scores[i], epsilon))
97 {
98 fprintf(stderr, "top %d score not match expect %f but got %f\n", i, expect_scores[i], score);
99 return -1;
100 }
101 }
102
103 return 0;
104}
105
106static void fread_or_error(void* buffer, size_t size, size_t count, FILE* fp, const char* s)
107{
108 if (count != fread(buffer, size, count, fp))
109 {
110 fprintf(stderr, "Couldn't read from file: %s\n", s);
111 fclose(fp);
112 exit(EXIT_FAILURE);
113 }
114}
115
116static std::string read_file_string(const char* filepath)
117{
118 FILE* fp = fopen(filepath, "rb");
119 if (!fp)
120 {
121 fprintf(stderr, "fopen %s failed\n", filepath);
122 return std::string();
123 }
124
125 fseek(fp, 0, SEEK_END);
126 int len = ftell(fp);
127 rewind(fp);
128
129 std::string s;
130 s.resize(len + 1); // +1 for '\0'
131
132 fread_or_error((char*)s.c_str(), 1, len, fp, filepath);
133 fclose(fp);
134
135 s[len] = '\0';
136
137 return s;
138}
139
140static ncnn::Mat read_file_content(const char* filepath)
141{
142 FILE* fp = fopen(filepath, "rb");
143 if (!fp)
144 {
145 fprintf(stderr, "fopen %s failed\n", filepath);
146 return ncnn::Mat();
147 }
148
149 fseek(fp, 0, SEEK_END);
150 int len = ftell(fp);
151 rewind(fp);
152
153 ncnn::Mat m(len, (size_t)1u, 1);
154
155 fread_or_error(m, 1, len, fp, filepath);
156 fclose(fp);
157
158 return m;
159}
160
161static int test_squeezenet(const ncnn::Option& opt, int load_model_type, float epsilon = 0.001)
162{
163 ncnn::Net squeezenet;
164
165 squeezenet.opt = opt;
166
167#ifdef __EMSCRIPTEN__
168#define MODEL_DIR "/working"
169#else
170#define MODEL_DIR "../../examples"
171#endif
172
173 std::string param_str;
174 ncnn::Mat param_data;
175 ncnn::Mat model_data;
176 if (load_model_type == 0)
177 {
178 // load from plain model file
179 squeezenet.load_param(MODEL_DIR "/squeezenet_v1.1.param");
180
181 // test random feature disabled bits
182 {
183 std::vector<ncnn::Layer*>& layers = squeezenet.mutable_layers();
184 for (size_t i = 0; i < layers.size(); i++)
185 {
186 layers[i]->featmask = i * 11 % 128;
187 }
188 }
189
190 squeezenet.load_model(MODEL_DIR "/squeezenet_v1.1.bin");
191 }
192 if (load_model_type == 1)
193 {
194 // load from plain model memory
195 param_str = read_file_string(MODEL_DIR "/squeezenet_v1.1.param");
196 model_data = read_file_content(MODEL_DIR "/squeezenet_v1.1.bin");
197 squeezenet.load_param_mem((const char*)param_str.c_str());
198 squeezenet.load_model((const unsigned char*)model_data);
199 }
200 if (load_model_type == 2)
201 {
202 // load from binary model file
203 squeezenet.load_param_bin(MODEL_DIR "/squeezenet_v1.1.param.bin");
204 squeezenet.load_model(MODEL_DIR "/squeezenet_v1.1.bin");
205 }
206 if (load_model_type == 3)
207 {
208 // load from binary model memory
209 param_data = read_file_content(MODEL_DIR "/squeezenet_v1.1.param.bin");
210 model_data = read_file_content(MODEL_DIR "/squeezenet_v1.1.bin");
211 squeezenet.load_param((const unsigned char*)param_data);
212 squeezenet.load_model((const unsigned char*)model_data);
213 }
214
215 ncnn::Mat in = generate_ncnn_logo(ncnn::Mat::PIXEL_BGR, 227, 227);
216
217 const float mean_vals[3] = {104.f, 117.f, 123.f};
218 in.substract_mean_normalize(mean_vals, 0);
219
220 ncnn::Extractor ex = squeezenet.create_extractor();
221
222 ncnn::Mat out;
223 if (load_model_type == 0 || load_model_type == 1)
224 {
225 ex.input("data", in);
226 ex.extract("prob", out);
227 }
228 if (load_model_type == 2 || load_model_type == 3)
229 {
230 ex.input(0, in);
231 ex.extract(82, out);
232 }
233
234 std::vector<float> cls_scores;
235 cls_scores.resize(out.w);
236 for (int j = 0; j < out.w; j++)
237 {
238 cls_scores[j] = out[j];
239 }
240
241 return check_top2(cls_scores, epsilon);
242}
243
244class MyConvolution : public ncnn::Layer
245{
246public:
247 MyConvolution()
248 {
249 impl = ncnn::create_layer("Convolution");
250
251 one_blob_only = impl->one_blob_only;
252 support_inplace = impl->support_inplace;
253
254 support_packing = impl->support_packing;
255 support_vulkan = impl->support_vulkan;
256 support_bf16_storage = impl->support_bf16_storage;
257 support_fp16_storage = impl->support_fp16_storage;
258 support_int8_storage = impl->support_int8_storage;
259 support_image_storage = impl->support_image_storage;
260 }
261
262 ~MyConvolution()
263 {
264 delete impl;
265 }
266
267 virtual int load_param(const ncnn::ParamDict& pd)
268 {
269#if NCNN_VULKAN
270 impl->vkdev = vkdev;
271#endif // NCNN_VULKAN
272
273 return impl->load_param(pd);
274 }
275
276 virtual int load_model(const ncnn::ModelBin& mb)
277 {
278 return impl->load_model(mb);
279 }
280
281 virtual int create_pipeline(const ncnn::Option& opt)
282 {
283 int ret = impl->create_pipeline(opt);
284
285 one_blob_only = impl->one_blob_only;
286 support_inplace = impl->support_inplace;
287
288 support_packing = impl->support_packing;
289 support_vulkan = impl->support_vulkan;
290 support_bf16_storage = impl->support_bf16_storage;
291 support_fp16_storage = impl->support_fp16_storage;
292 support_int8_storage = impl->support_int8_storage;
293 support_image_storage = impl->support_image_storage;
294
295 return ret;
296 }
297
298 virtual int destroy_pipeline(const ncnn::Option& opt)
299 {
300 return impl->destroy_pipeline(opt);
301 }
302
303 virtual int forward(const ncnn::Mat& bottom_blob, ncnn::Mat& top_blob, const ncnn::Option& opt) const
304 {
305 return impl->forward(bottom_blob, top_blob, opt);
306 }
307
308#if NCNN_VULKAN
309 virtual int upload_model(ncnn::VkTransfer& cmd, const ncnn::Option& opt)
310 {
311 return impl->upload_model(cmd, opt);
312 }
313
314 virtual int forward(const ncnn::VkMat& bottom_blob, ncnn::VkMat& top_blob, ncnn::VkCompute& cmd, const ncnn::Option& opt) const
315 {
316 return impl->forward(bottom_blob, top_blob, cmd, opt);
317 }
318
319 virtual int forward(const ncnn::VkImageMat& bottom_blob, ncnn::VkImageMat& top_blob, ncnn::VkCompute& cmd, const ncnn::Option& opt) const
320 {
321 return impl->forward(bottom_blob, top_blob, cmd, opt);
322 }
323#endif // NCNN_VULKAN
324
325private:
326 ncnn::Layer* impl;
327};
328
329DEFINE_LAYER_CREATOR(MyConvolution)
330DEFINE_LAYER_DESTROYER(MyConvolution)
331
332static int test_squeezenet_overwrite_softmax(const ncnn::Option& opt, int load_model_type, float epsilon = 0.001)
333{
334 ncnn::Net squeezenet;
335
336 squeezenet.opt = opt;
337
338#ifdef __EMSCRIPTEN__
339#define MODEL_DIR "/working"
340#else
341#define MODEL_DIR "../../examples"
342#endif
343
344 std::string param_str;
345 ncnn::Mat param_data;
346 ncnn::Mat model_data;
347 if (load_model_type == 0)
348 {
349 // load from plain model file
350 squeezenet.register_custom_layer("Convolution", MyConvolution_layer_creator, MyConvolution_layer_destroyer);
351 squeezenet.load_param(MODEL_DIR "/squeezenet_v1.1.param");
352
353 // test random feature disabled bits
354 {
355 std::vector<ncnn::Layer*>& layers = squeezenet.mutable_layers();
356 for (size_t i = 0; i < layers.size(); i++)
357 {
358 layers[i]->featmask = i * 11 % 128;
359 }
360 }
361
362 squeezenet.load_model(MODEL_DIR "/squeezenet_v1.1.bin");
363 }
364 if (load_model_type == 1)
365 {
366 // load from plain model memory
367 squeezenet.register_custom_layer("Convolution", MyConvolution_layer_creator, MyConvolution_layer_destroyer);
368 param_str = read_file_string(MODEL_DIR "/squeezenet_v1.1.param");
369 model_data = read_file_content(MODEL_DIR "/squeezenet_v1.1.bin");
370 squeezenet.load_param_mem((const char*)param_str.c_str());
371 squeezenet.load_model((const unsigned char*)model_data);
372 }
373 if (load_model_type == 2)
374 {
375 // load from binary model file
376 squeezenet.register_custom_layer(ncnn::layer_to_index("Convolution"), MyConvolution_layer_creator, MyConvolution_layer_destroyer);
377 squeezenet.load_param_bin(MODEL_DIR "/squeezenet_v1.1.param.bin");
378 squeezenet.load_model(MODEL_DIR "/squeezenet_v1.1.bin");
379 }
380 if (load_model_type == 3)
381 {
382 // load from binary model memory
383 squeezenet.register_custom_layer(ncnn::layer_to_index("Convolution"), MyConvolution_layer_creator, MyConvolution_layer_destroyer);
384 param_data = read_file_content(MODEL_DIR "/squeezenet_v1.1.param.bin");
385 model_data = read_file_content(MODEL_DIR "/squeezenet_v1.1.bin");
386 squeezenet.load_param((const unsigned char*)param_data);
387 squeezenet.load_model((const unsigned char*)model_data);
388 }
389
390 ncnn::Mat in = generate_ncnn_logo(ncnn::Mat::PIXEL_BGR, 227, 227);
391
392 const float mean_vals[3] = {104.f, 117.f, 123.f};
393 in.substract_mean_normalize(mean_vals, 0);
394
395 ncnn::Extractor ex = squeezenet.create_extractor();
396
397 ncnn::Mat out;
398 if (load_model_type == 0 || load_model_type == 1)
399 {
400 ex.input("data", in);
401 ex.extract("prob", out);
402 }
403 if (load_model_type == 2 || load_model_type == 3)
404 {
405 ex.input(0, in);
406 ex.extract(82, out);
407 }
408
409 std::vector<float> cls_scores;
410 cls_scores.resize(out.w);
411 for (int j = 0; j < out.w; j++)
412 {
413 cls_scores[j] = out[j];
414 }
415
416 return check_top2(cls_scores, epsilon);
417}
418
419int main()
420{
421 SRAND(7767517);
422
423#ifdef __EMSCRIPTEN__
424 EM_ASM(
425 FS.mkdir('/working');
426 FS.mount(NODEFS, {root: '../../examples'}, '/working'););
427#endif // __EMSCRIPTEN__
428
429 ncnn::UnlockedPoolAllocator g_blob_pool_allocator;
430 ncnn::PoolAllocator g_workspace_pool_allocator;
431
432 ncnn::Option opts[4];
433
434 opts[0].use_packing_layout = false;
435 opts[0].use_fp16_packed = false;
436 opts[0].use_fp16_storage = false;
437 opts[0].use_fp16_arithmetic = false;
438 opts[0].use_shader_pack8 = false;
439 opts[0].use_image_storage = false;
440
441 opts[1].use_packing_layout = true;
442 opts[1].use_fp16_packed = true;
443 opts[1].use_fp16_storage = false;
444 opts[1].use_fp16_arithmetic = false;
445 opts[1].use_shader_pack8 = true;
446 opts[1].use_image_storage = false;
447
448 opts[2].use_packing_layout = true;
449 opts[2].use_fp16_packed = true;
450 opts[2].use_fp16_storage = true;
451 opts[2].use_fp16_arithmetic = false;
452 opts[2].use_bf16_storage = false; // FIXME enable me
453 opts[2].use_shader_pack8 = true;
454 opts[2].use_image_storage = true;
455 opts[2].blob_allocator = &g_blob_pool_allocator;
456 opts[2].workspace_allocator = &g_workspace_pool_allocator;
457
458 opts[3].use_packing_layout = true;
459 opts[3].use_fp16_packed = true;
460 opts[3].use_fp16_storage = true;
461 opts[3].use_fp16_arithmetic = false; // FIXME enable me
462 opts[3].use_bf16_storage = false;
463 opts[3].use_shader_pack8 = true;
464 opts[3].use_image_storage = true;
465 opts[3].blob_allocator = &g_blob_pool_allocator;
466 opts[3].workspace_allocator = &g_workspace_pool_allocator;
467
468 int load_model_types[4] = {0, 1, 2, 3};
469
470 for (int i = 0; i < 4; i++)
471 {
472 opts[i].num_threads = 1;
473 }
474
475 for (int i = 0; i < 4; i++)
476 {
477 const ncnn::Option& opt = opts[i];
478
479 float epsilon;
480 if (opt.use_bf16_storage || opt.use_fp16_packed || opt.use_fp16_storage)
481 {
482 epsilon = 0.1;
483 }
484 else
485 {
486 epsilon = 0.01;
487 }
488
489 int ret;
490
491 ncnn::Option opt_cpu = opt;
492 opt_cpu.use_vulkan_compute = false;
493 ret = test_squeezenet(opt_cpu, load_model_types[i], epsilon);
494 if (ret != 0)
495 {
496 fprintf(stderr, "test_squeezenet cpu failed use_packing_layout=%d use_fp16_packed=%d use_fp16_storage=%d use_shader_pack8=%d use_bf16_storage=%d use_image_storage=%d\n", opt.use_packing_layout, opt.use_fp16_packed, opt.use_fp16_storage, opt.use_shader_pack8, opt.use_bf16_storage, opt.use_image_storage);
497 return ret;
498 }
499
500#if NCNN_VULKAN
501 ncnn::Option opt_gpu = opt;
502 opt_gpu.use_vulkan_compute = true;
503 ret = test_squeezenet(opt_gpu, load_model_types[i], epsilon);
504 if (ret != 0)
505 {
506 fprintf(stderr, "test_squeezenet gpu failed use_packing_layout=%d use_fp16_packed=%d use_fp16_storage=%d use_shader_pack8=%d use_bf16_storage=%d use_image_storage=%d\n", opt.use_packing_layout, opt.use_fp16_packed, opt.use_fp16_storage, opt.use_shader_pack8, opt.use_bf16_storage, opt.use_image_storage);
507 return ret;
508 }
509#endif // NCNN_VULKAN
510
511 ret = test_squeezenet_overwrite_softmax(opt_cpu, load_model_types[i], epsilon);
512 if (ret != 0)
513 {
514 fprintf(stderr, "test_squeezenet_overwrite_softmax cpu failed use_packing_layout=%d use_fp16_packed=%d use_fp16_storage=%d use_shader_pack8=%d use_bf16_storage=%d use_image_storage=%d\n", opt.use_packing_layout, opt.use_fp16_packed, opt.use_fp16_storage, opt.use_shader_pack8, opt.use_bf16_storage, opt.use_image_storage);
515 return ret;
516 }
517
518#if NCNN_VULKAN
519 ret = test_squeezenet_overwrite_softmax(opt_gpu, load_model_types[i], epsilon);
520 if (ret != 0)
521 {
522 fprintf(stderr, "test_squeezenet_overwrite_softmax gpu failed use_packing_layout=%d use_fp16_packed=%d use_fp16_storage=%d use_shader_pack8=%d use_bf16_storage=%d use_image_storage=%d\n", opt.use_packing_layout, opt.use_fp16_packed, opt.use_fp16_storage, opt.use_shader_pack8, opt.use_bf16_storage, opt.use_image_storage);
523 return ret;
524 }
525#endif // NCNN_VULKAN
526 }
527
528 return 0;
529}