Elffuss BraidHub

kikocis/ncnn public

master · 54.6 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// author:BUG1989 (https://github.com/BUG1989/) Long-term support.
4// author:JansonZhu (https://github.com/JansonZhu) Implemented the function of entropy calibration.
5//
6// Copyright (C) 2019 BUG1989. All rights reserved.
7// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
8//
9// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
10// in compliance with the License. You may obtain a copy of the License at
11//
12// https://opensource.org/licenses/BSD-3-Clause
13//
14// Unless required by applicable law or agreed to in writing, software distributed
15// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
16// CONDITIONS OF ANY KIND, either express or implied. See the License for the
17// specific language governing permissions and limitations under the License.
18
19#ifdef _MSC_VER
20#define _CRT_SECURE_NO_DEPRECATE
21#endif
22
23#include <float.h>
24#include <limits.h>
25#include <math.h>
26#include <stdio.h>
27#include <stdint.h>
28#include <stdlib.h>
29#include <string.h>
30
31#if defined(USE_NCNN_SIMPLEOCV)
32#include "simpleocv.h"
33#elif defined(USE_LOCAL_IMREADWRITE)
34#include "imreadwrite.h"
35#else
36#include <opencv2/core/core.hpp>
37#include <opencv2/highgui/highgui.hpp>
38#endif
39#include <string>
40#include <vector>
41
42// ncnn public header
43#include "benchmark.h"
44#include "cpu.h"
45#include "net.h"
46
47// ncnn private header
48#include "layer/convolution.h"
49#include "layer/convolutiondepthwise.h"
50#include "layer/innerproduct.h"
51
52class QuantBlobStat
53{
54public:
55 QuantBlobStat()
56 {
57 threshold = 0.f;
58 absmax = 0.f;
59 total = 0;
60 }
61
62public:
63 float threshold;
64 float absmax;
65
66 // ACIQ
67 int total;
68
69 // KL
70 std::vector<uint64_t> histogram;
71 std::vector<float> histogram_normed;
72};
73
74class QuantNet : public ncnn::Net
75{
76public:
77 QuantNet();
78
79 std::vector<ncnn::Blob>& blobs;
80 std::vector<ncnn::Layer*>& layers;
81
82public:
83 std::vector<std::vector<std::string> > listspaths;
84 std::vector<std::vector<float> > means;
85 std::vector<std::vector<float> > norms;
86 std::vector<std::vector<int> > shapes;
87 std::vector<int> type_to_pixels;
88 int quantize_num_threads;
89
90public:
91 int init();
92 void print_quant_info() const;
93 int save_table(const char* tablepath);
94 int quantize_KL();
95 int quantize_ACIQ();
96 int quantize_EQ();
97
98public:
99 std::vector<int> input_blobs;
100 std::vector<int> conv_layers;
101 std::vector<int> conv_bottom_blobs;
102 std::vector<int> conv_top_blobs;
103
104 // result
105 std::vector<QuantBlobStat> quant_blob_stats;
106 std::vector<ncnn::Mat> weight_scales;
107 std::vector<ncnn::Mat> bottom_blob_scales;
108};
109
110QuantNet::QuantNet()
111 : blobs(mutable_blobs()), layers(mutable_layers())
112{
113 quantize_num_threads = ncnn::get_cpu_count();
114}
115
116int QuantNet::init()
117{
118 // find all input layers
119 for (int i = 0; i < (int)layers.size(); i++)
120 {
121 const ncnn::Layer* layer = layers[i];
122 if (layer->type == "Input")
123 {
124 input_blobs.push_back(layer->tops[0]);
125 }
126 }
127
128 // find all conv layers
129 for (int i = 0; i < (int)layers.size(); i++)
130 {
131 const ncnn::Layer* layer = layers[i];
132 if (layer->type == "Convolution" || layer->type == "ConvolutionDepthWise" || layer->type == "InnerProduct")
133 {
134 conv_layers.push_back(i);
135 conv_bottom_blobs.push_back(layer->bottoms[0]);
136 conv_top_blobs.push_back(layer->tops[0]);
137 }
138 }
139
140 const int conv_layer_count = (int)conv_layers.size();
141 const int conv_bottom_blob_count = (int)conv_bottom_blobs.size();
142
143 quant_blob_stats.resize(conv_bottom_blob_count);
144 weight_scales.resize(conv_layer_count);
145 bottom_blob_scales.resize(conv_bottom_blob_count);
146
147 return 0;
148}
149
150int QuantNet::save_table(const char* tablepath)
151{
152 FILE* fp = fopen(tablepath, "wb");
153 if (!fp)
154 {
155 fprintf(stderr, "fopen %s failed\n", tablepath);
156 return -1;
157 }
158
159 const int conv_layer_count = (int)conv_layers.size();
160 const int conv_bottom_blob_count = (int)conv_bottom_blobs.size();
161
162 for (int i = 0; i < conv_layer_count; i++)
163 {
164 const ncnn::Mat& weight_scale = weight_scales[i];
165
166 fprintf(fp, "%s_param_0 ", layers[conv_layers[i]]->name.c_str());
167 for (int j = 0; j < weight_scale.w; j++)
168 {
169 fprintf(fp, "%f ", weight_scale[j]);
170 }
171 fprintf(fp, "\n");
172 }
173
174 for (int i = 0; i < conv_bottom_blob_count; i++)
175 {
176 const ncnn::Mat& bottom_blob_scale = bottom_blob_scales[i];
177
178 fprintf(fp, "%s ", layers[conv_layers[i]]->name.c_str());
179 for (int j = 0; j < bottom_blob_scale.w; j++)
180 {
181 fprintf(fp, "%f ", bottom_blob_scale[j]);
182 }
183 fprintf(fp, "\n");
184 }
185
186 fclose(fp);
187
188 fprintf(stderr, "ncnn int8 calibration table create success, best wish for your int8 inference has a low accuracy loss...\\(^0^)/...233...\n");
189
190 return 0;
191}
192
193void QuantNet::print_quant_info() const
194{
195 for (int i = 0; i < (int)conv_bottom_blobs.size(); i++)
196 {
197 const QuantBlobStat& stat = quant_blob_stats[i];
198
199 float scale = 127 / stat.threshold;
200
201 fprintf(stderr, "%-40s : max = %-15f threshold = %-15f scale = %-15f\n", layers[conv_layers[i]]->name.c_str(), stat.absmax, stat.threshold, scale);
202 }
203}
204
205/**
206 * Read and resize image
207 * shape is input as [w,h,...]
208 * if w and h both are given, image will be resized to exactly size.
209 * if w and h both are zero or negative, image will not be resized.
210 * if only h is zero or negative, image's width will scaled resize to w, keeping aspect ratio.
211 * if only w is zero or negative, image's height will scaled resize to h
212 * @return ncnn::Mat
213 */
214
215inline ncnn::Mat read_and_resize_image(const std::vector<int>& shape, const std::string& imagepath, int pixel_convert_type)
216{
217 int target_w = shape[0];
218 int target_h = shape[1];
219 cv::Mat bgr = cv::imread(imagepath, 1);
220 if (target_h <= 0 && target_w <= 0)
221 {
222 return ncnn::Mat::from_pixels(bgr.data, pixel_convert_type, bgr.cols, bgr.rows);
223 }
224 if (target_h <= 0 || target_w <= 0)
225 {
226 float scale = 1.0;
227 if (target_h <= 0)
228 {
229 scale = 1.0 * bgr.cols / target_w;
230 target_h = int(1.0 * bgr.rows / scale);
231 }
232 if (target_w <= 0)
233 {
234 scale = 1.0 * bgr.rows / target_h;
235 target_w = int(1.0 * bgr.cols / scale);
236 }
237 }
238 return ncnn::Mat::from_pixels_resize(bgr.data, pixel_convert_type, bgr.cols, bgr.rows, target_w, target_h);
239}
240
241static float compute_kl_divergence(const std::vector<float>& a, const std::vector<float>& b)
242{
243 const size_t length = a.size();
244
245 float result = 0;
246 for (size_t i = 0; i < length; i++)
247 {
248 result += a[i] * log(a[i] / b[i]);
249 }
250
251 return result;
252}
253
254int QuantNet::quantize_KL()
255{
256 const int input_blob_count = (int)input_blobs.size();
257 const int conv_layer_count = (int)conv_layers.size();
258 const int conv_bottom_blob_count = (int)conv_bottom_blobs.size();
259 const int image_count = (int)listspaths[0].size();
260
261 const int num_histogram_bins = 2048;
262
263 std::vector<ncnn::UnlockedPoolAllocator> blob_allocators(quantize_num_threads);
264 std::vector<ncnn::UnlockedPoolAllocator> workspace_allocators(quantize_num_threads);
265
266 // initialize conv weight scales
267 #pragma omp parallel for num_threads(quantize_num_threads)
268 for (int i = 0; i < conv_layer_count; i++)
269 {
270 const ncnn::Layer* layer = layers[conv_layers[i]];
271
272 if (layer->type == "Convolution")
273 {
274 const ncnn::Convolution* convolution = (const ncnn::Convolution*)layer;
275
276 const int num_output = convolution->num_output;
277 const int kernel_w = convolution->kernel_w;
278 const int kernel_h = convolution->kernel_h;
279 const int dilation_w = convolution->dilation_w;
280 const int dilation_h = convolution->dilation_h;
281 const int stride_w = convolution->stride_w;
282 const int stride_h = convolution->stride_h;
283
284 const int weight_data_size_output = convolution->weight_data_size / num_output;
285
286 // int8 winograd F43 needs weight data to use 6bit quantization
287 // TODO proper condition for winograd 3x3 int8
288 bool quant_6bit = false;
289 if (kernel_w == 3 && kernel_h == 3 && dilation_w == 1 && dilation_h == 1 && stride_w == 1 && stride_h == 1)
290 quant_6bit = true;
291
292 weight_scales[i].create(num_output);
293
294 for (int n = 0; n < num_output; n++)
295 {
296 const ncnn::Mat weight_data_n = convolution->weight_data.range(weight_data_size_output * n, weight_data_size_output);
297
298 float absmax = 0.f;
299 for (int k = 0; k < weight_data_size_output; k++)
300 {
301 absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
302 }
303
304 if (quant_6bit)
305 {
306 weight_scales[i][n] = 31 / absmax;
307 }
308 else
309 {
310 weight_scales[i][n] = 127 / absmax;
311 }
312 }
313 }
314
315 if (layer->type == "ConvolutionDepthWise")
316 {
317 const ncnn::ConvolutionDepthWise* convolutiondepthwise = (const ncnn::ConvolutionDepthWise*)layer;
318
319 const int group = convolutiondepthwise->group;
320 const int weight_data_size_output = convolutiondepthwise->weight_data_size / group;
321
322 std::vector<float> scales;
323
324 weight_scales[i].create(group);
325
326 for (int n = 0; n < group; n++)
327 {
328 const ncnn::Mat weight_data_n = convolutiondepthwise->weight_data.range(weight_data_size_output * n, weight_data_size_output);
329
330 float absmax = 0.f;
331 for (int k = 0; k < weight_data_size_output; k++)
332 {
333 absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
334 }
335
336 weight_scales[i][n] = 127 / absmax;
337 }
338 }
339
340 if (layer->type == "InnerProduct")
341 {
342 const ncnn::InnerProduct* innerproduct = (const ncnn::InnerProduct*)layer;
343
344 const int num_output = innerproduct->num_output;
345 const int weight_data_size_output = innerproduct->weight_data_size / num_output;
346
347 weight_scales[i].create(num_output);
348
349 for (int n = 0; n < num_output; n++)
350 {
351 const ncnn::Mat weight_data_n = innerproduct->weight_data.range(weight_data_size_output * n, weight_data_size_output);
352
353 float absmax = 0.f;
354 for (int k = 0; k < weight_data_size_output; k++)
355 {
356 absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
357 }
358
359 weight_scales[i][n] = 127 / absmax;
360 }
361 }
362 }
363
364 // count the absmax
365 #pragma omp parallel for num_threads(quantize_num_threads) schedule(static, 1)
366 for (int i = 0; i < image_count; i++)
367 {
368 if (i % 100 == 0)
369 {
370 fprintf(stderr, "count the absmax %.2f%% [ %d / %d ]\n", i * 100.f / image_count, i, image_count);
371 }
372
373 ncnn::Extractor ex = create_extractor();
374 ex.set_light_mode(true);
375
376 const int thread_num = ncnn::get_omp_thread_num();
377 ex.set_blob_allocator(&blob_allocators[thread_num]);
378 ex.set_workspace_allocator(&workspace_allocators[thread_num]);
379
380 for (int j = 0; j < input_blob_count; j++)
381 {
382 const int type_to_pixel = type_to_pixels[j];
383 const std::vector<float>& mean_vals = means[j];
384 const std::vector<float>& norm_vals = norms[j];
385
386 int pixel_convert_type = ncnn::Mat::PIXEL_BGR;
387 if (type_to_pixel != pixel_convert_type)
388 {
389 pixel_convert_type = pixel_convert_type | (type_to_pixel << ncnn::Mat::PIXEL_CONVERT_SHIFT);
390 }
391
392 ncnn::Mat in = read_and_resize_image(shapes[j], listspaths[j][i], pixel_convert_type);
393
394 in.substract_mean_normalize(mean_vals.data(), norm_vals.data());
395
396 ex.input(input_blobs[j], in);
397 }
398
399 for (int j = 0; j < conv_bottom_blob_count; j++)
400 {
401 ncnn::Mat out;
402 ex.extract(conv_bottom_blobs[j], out);
403
404 // count absmax
405 {
406 float absmax = 0.f;
407
408 const int outc = out.c;
409 const int outsize = out.w * out.h;
410 for (int p = 0; p < outc; p++)
411 {
412 const float* ptr = out.channel(p);
413 for (int k = 0; k < outsize; k++)
414 {
415 absmax = std::max(absmax, (float)fabs(ptr[k]));
416 }
417 }
418
419 #pragma omp critical
420 {
421 QuantBlobStat& stat = quant_blob_stats[j];
422 stat.absmax = std::max(stat.absmax, absmax);
423 }
424 }
425 }
426 }
427
428 // initialize histogram
429 #pragma omp parallel for num_threads(quantize_num_threads)
430 for (int i = 0; i < conv_bottom_blob_count; i++)
431 {
432 QuantBlobStat& stat = quant_blob_stats[i];
433
434 stat.histogram.resize(num_histogram_bins, 0);
435 stat.histogram_normed.resize(num_histogram_bins, 0);
436 }
437
438 // build histogram
439 #pragma omp parallel for num_threads(quantize_num_threads) schedule(static, 1)
440 for (int i = 0; i < image_count; i++)
441 {
442 if (i % 100 == 0)
443 {
444 fprintf(stderr, "build histogram %.2f%% [ %d / %d ]\n", i * 100.f / image_count, i, image_count);
445 }
446
447 ncnn::Extractor ex = create_extractor();
448 ex.set_light_mode(true);
449
450 const int thread_num = ncnn::get_omp_thread_num();
451 ex.set_blob_allocator(&blob_allocators[thread_num]);
452 ex.set_workspace_allocator(&workspace_allocators[thread_num]);
453
454 for (int j = 0; j < input_blob_count; j++)
455 {
456 const int type_to_pixel = type_to_pixels[j];
457 const std::vector<float>& mean_vals = means[j];
458 const std::vector<float>& norm_vals = norms[j];
459
460 int pixel_convert_type = ncnn::Mat::PIXEL_BGR;
461 if (type_to_pixel != pixel_convert_type)
462 {
463 pixel_convert_type = pixel_convert_type | (type_to_pixel << ncnn::Mat::PIXEL_CONVERT_SHIFT);
464 }
465
466 ncnn::Mat in = read_and_resize_image(shapes[j], listspaths[j][i], pixel_convert_type);
467
468 in.substract_mean_normalize(mean_vals.data(), norm_vals.data());
469
470 ex.input(input_blobs[j], in);
471 }
472
473 for (int j = 0; j < conv_bottom_blob_count; j++)
474 {
475 ncnn::Mat out;
476 ex.extract(conv_bottom_blobs[j], out);
477
478 // count histogram bin
479 {
480 const float absmax = quant_blob_stats[j].absmax;
481
482 std::vector<uint64_t> histogram(num_histogram_bins, 0);
483
484 const int outc = out.c;
485 const int outsize = out.w * out.h;
486 for (int p = 0; p < outc; p++)
487 {
488 const float* ptr = out.channel(p);
489 for (int k = 0; k < outsize; k++)
490 {
491 if (ptr[k] == 0.f)
492 continue;
493
494 const int index = std::min((int)(fabs(ptr[k]) / absmax * num_histogram_bins), (num_histogram_bins - 1));
495
496 histogram[index] += 1;
497 }
498 }
499
500 #pragma omp critical
501 {
502 QuantBlobStat& stat = quant_blob_stats[j];
503
504 for (int k = 0; k < num_histogram_bins; k++)
505 {
506 stat.histogram[k] += histogram[k];
507 }
508 }
509 }
510 }
511 }
512
513 // using kld to find the best threshold value
514 #pragma omp parallel for num_threads(quantize_num_threads)
515 for (int i = 0; i < conv_bottom_blob_count; i++)
516 {
517 QuantBlobStat& stat = quant_blob_stats[i];
518
519 // normalize histogram bin
520 {
521 uint64_t sum = 0;
522 for (int j = 0; j < num_histogram_bins; j++)
523 {
524 sum += stat.histogram[j];
525 }
526
527 for (int j = 0; j < num_histogram_bins; j++)
528 {
529 stat.histogram_normed[j] = (float)(stat.histogram[j] / (double)sum);
530 }
531 }
532
533 const int target_bin = 128;
534
535 int target_threshold = target_bin;
536 float min_kl_divergence = FLT_MAX;
537
538 for (int threshold = target_bin; threshold < num_histogram_bins; threshold++)
539 {
540 const float kl_eps = 0.0001f;
541
542 std::vector<float> clip_distribution(threshold, kl_eps);
543 {
544 for (int j = 0; j < threshold; j++)
545 {
546 clip_distribution[j] += stat.histogram_normed[j];
547 }
548 for (int j = threshold; j < num_histogram_bins; j++)
549 {
550 clip_distribution[threshold - 1] += stat.histogram_normed[j];
551 }
552 }
553
554 const float num_per_bin = (float)threshold / target_bin;
555
556 std::vector<float> quantize_distribution(target_bin, 0.f);
557 {
558 {
559 const float end = num_per_bin;
560
561 const int right_lower = (int)floor(end);
562 const float right_scale = end - right_lower;
563
564 if (right_scale > 0)
565 {
566 quantize_distribution[0] += right_scale * stat.histogram_normed[right_lower];
567 }
568
569 for (int k = 0; k < right_lower; k++)
570 {
571 quantize_distribution[0] += stat.histogram_normed[k];
572 }
573
574 quantize_distribution[0] /= right_lower + right_scale;
575 }
576 for (int j = 1; j < target_bin - 1; j++)
577 {
578 const float start = j * num_per_bin;
579 const float end = (j + 1) * num_per_bin;
580
581 const int left_upper = (int)ceil(start);
582 const float left_scale = left_upper - start;
583
584 const int right_lower = (int)floor(end);
585 const float right_scale = end - right_lower;
586
587 if (left_scale > 0)
588 {
589 quantize_distribution[j] += left_scale * stat.histogram_normed[left_upper - 1];
590 }
591
592 if (right_scale > 0)
593 {
594 quantize_distribution[j] += right_scale * stat.histogram_normed[right_lower];
595 }
596
597 for (int k = left_upper; k < right_lower; k++)
598 {
599 quantize_distribution[j] += stat.histogram_normed[k];
600 }
601
602 quantize_distribution[j] /= right_lower - left_upper + left_scale + right_scale;
603 }
604 {
605 const float start = threshold - num_per_bin;
606
607 const int left_upper = (int)ceil(start);
608 const float left_scale = left_upper - start;
609
610 if (left_scale > 0)
611 {
612 quantize_distribution[target_bin - 1] += left_scale * stat.histogram_normed[left_upper - 1];
613 }
614
615 for (int k = left_upper; k < threshold; k++)
616 {
617 quantize_distribution[target_bin - 1] += stat.histogram_normed[k];
618 }
619
620 quantize_distribution[target_bin - 1] /= threshold - left_upper + left_scale;
621 }
622 }
623
624 std::vector<float> expand_distribution(threshold, kl_eps);
625 {
626 {
627 const float end = num_per_bin;
628
629 const int right_lower = (int)floor(end);
630 const float right_scale = end - right_lower;
631
632 if (right_scale > 0)
633 {
634 expand_distribution[right_lower] += right_scale * quantize_distribution[0];
635 }
636
637 for (int k = 0; k < right_lower; k++)
638 {
639 expand_distribution[k] += quantize_distribution[0];
640 }
641 }
642 for (int j = 1; j < target_bin - 1; j++)
643 {
644 const float start = j * num_per_bin;
645 const float end = (j + 1) * num_per_bin;
646
647 const int left_upper = (int)ceil(start);
648 const float left_scale = left_upper - start;
649
650 const int right_lower = (int)floor(end);
651 const float right_scale = end - right_lower;
652
653 if (left_scale > 0)
654 {
655 expand_distribution[left_upper - 1] += left_scale * quantize_distribution[j];
656 }
657
658 if (right_scale > 0)
659 {
660 expand_distribution[right_lower] += right_scale * quantize_distribution[j];
661 }
662
663 for (int k = left_upper; k < right_lower; k++)
664 {
665 expand_distribution[k] += quantize_distribution[j];
666 }
667 }
668 {
669 const float start = threshold - num_per_bin;
670
671 const int left_upper = (int)ceil(start);
672 const float left_scale = left_upper - start;
673
674 if (left_scale > 0)
675 {
676 expand_distribution[left_upper - 1] += left_scale * quantize_distribution[target_bin - 1];
677 }
678
679 for (int k = left_upper; k < threshold; k++)
680 {
681 expand_distribution[k] += quantize_distribution[target_bin - 1];
682 }
683 }
684 }
685
686 // kl
687 const float kl_divergence = compute_kl_divergence(clip_distribution, expand_distribution);
688
689 // the best num of bin
690 if (kl_divergence < min_kl_divergence)
691 {
692 min_kl_divergence = kl_divergence;
693 target_threshold = threshold;
694 }
695 }
696
697 stat.threshold = (target_threshold + 0.5f) * stat.absmax / num_histogram_bins;
698 float scale = 127 / stat.threshold;
699
700 bottom_blob_scales[i].create(1);
701 bottom_blob_scales[i][0] = scale;
702 }
703
704 return 0;
705}
706
707static float compute_aciq_gaussian_clip(float absmax, int N, int num_bits = 8)
708{
709 const float alpha_gaussian[8] = {0, 1.71063519, 2.15159277, 2.55913646, 2.93620062, 3.28691474, 3.6151146, 3.92403714};
710
711 const double gaussian_const = (0.5 * 0.35) * (1 + sqrt(3.14159265358979323846 * log(4)));
712
713 double std = (absmax * 2 * gaussian_const) / sqrt(2 * log(N));
714
715 return (float)(alpha_gaussian[num_bits - 1] * std);
716}
717
718int QuantNet::quantize_ACIQ()
719{
720 const int input_blob_count = (int)input_blobs.size();
721 const int conv_layer_count = (int)conv_layers.size();
722 const int conv_bottom_blob_count = (int)conv_bottom_blobs.size();
723 const int image_count = (int)listspaths[0].size();
724
725 std::vector<ncnn::UnlockedPoolAllocator> blob_allocators(quantize_num_threads);
726 std::vector<ncnn::UnlockedPoolAllocator> workspace_allocators(quantize_num_threads);
727
728 // initialize conv weight scales
729 #pragma omp parallel for num_threads(quantize_num_threads)
730 for (int i = 0; i < conv_layer_count; i++)
731 {
732 const ncnn::Layer* layer = layers[conv_layers[i]];
733
734 if (layer->type == "Convolution")
735 {
736 const ncnn::Convolution* convolution = (const ncnn::Convolution*)layer;
737
738 const int num_output = convolution->num_output;
739 const int kernel_w = convolution->kernel_w;
740 const int kernel_h = convolution->kernel_h;
741 const int dilation_w = convolution->dilation_w;
742 const int dilation_h = convolution->dilation_h;
743 const int stride_w = convolution->stride_w;
744 const int stride_h = convolution->stride_h;
745
746 const int weight_data_size_output = convolution->weight_data_size / num_output;
747
748 // int8 winograd F43 needs weight data to use 6bit quantization
749 // TODO proper condition for winograd 3x3 int8
750 bool quant_6bit = false;
751 if (kernel_w == 3 && kernel_h == 3 && dilation_w == 1 && dilation_h == 1 && stride_w == 1 && stride_h == 1)
752 quant_6bit = true;
753
754 weight_scales[i].create(num_output);
755
756 for (int n = 0; n < num_output; n++)
757 {
758 const ncnn::Mat weight_data_n = convolution->weight_data.range(weight_data_size_output * n, weight_data_size_output);
759
760 float absmax = 0.f;
761 for (int k = 0; k < weight_data_size_output; k++)
762 {
763 absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
764 }
765
766 if (quant_6bit)
767 {
768 const float threshold = compute_aciq_gaussian_clip(absmax, weight_data_size_output, 6);
769 weight_scales[i][n] = 31 / threshold;
770 }
771 else
772 {
773 const float threshold = compute_aciq_gaussian_clip(absmax, weight_data_size_output);
774 weight_scales[i][n] = 127 / threshold;
775 }
776 }
777 }
778
779 if (layer->type == "ConvolutionDepthWise")
780 {
781 const ncnn::ConvolutionDepthWise* convolutiondepthwise = (const ncnn::ConvolutionDepthWise*)layer;
782
783 const int group = convolutiondepthwise->group;
784 const int weight_data_size_output = convolutiondepthwise->weight_data_size / group;
785
786 std::vector<float> scales;
787
788 weight_scales[i].create(group);
789
790 for (int n = 0; n < group; n++)
791 {
792 const ncnn::Mat weight_data_n = convolutiondepthwise->weight_data.range(weight_data_size_output * n, weight_data_size_output);
793
794 float absmax = 0.f;
795 for (int k = 0; k < weight_data_size_output; k++)
796 {
797 absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
798 }
799
800 const float threshold = compute_aciq_gaussian_clip(absmax, weight_data_size_output);
801 weight_scales[i][n] = 127 / threshold;
802 }
803 }
804
805 if (layer->type == "InnerProduct")
806 {
807 const ncnn::InnerProduct* innerproduct = (const ncnn::InnerProduct*)layer;
808
809 const int num_output = innerproduct->num_output;
810 const int weight_data_size_output = innerproduct->weight_data_size / num_output;
811
812 weight_scales[i].create(num_output);
813
814 for (int n = 0; n < num_output; n++)
815 {
816 const ncnn::Mat weight_data_n = innerproduct->weight_data.range(weight_data_size_output * n, weight_data_size_output);
817
818 float absmax = 0.f;
819 for (int k = 0; k < weight_data_size_output; k++)
820 {
821 absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
822 }
823
824 const float threshold = compute_aciq_gaussian_clip(absmax, weight_data_size_output);
825 weight_scales[i][n] = 127 / threshold;
826 }
827 }
828 }
829
830 // count the absmax
831 #pragma omp parallel for num_threads(quantize_num_threads) schedule(static, 1)
832 for (int i = 0; i < image_count; i++)
833 {
834 if (i % 100 == 0)
835 {
836 fprintf(stderr, "count the absmax %.2f%% [ %d / %d ]\n", i * 100.f / image_count, i, image_count);
837 }
838
839 ncnn::Extractor ex = create_extractor();
840 ex.set_light_mode(true);
841
842 const int thread_num = ncnn::get_omp_thread_num();
843 ex.set_blob_allocator(&blob_allocators[thread_num]);
844 ex.set_workspace_allocator(&workspace_allocators[thread_num]);
845
846 for (int j = 0; j < input_blob_count; j++)
847 {
848 const int type_to_pixel = type_to_pixels[j];
849 const std::vector<float>& mean_vals = means[j];
850 const std::vector<float>& norm_vals = norms[j];
851
852 int pixel_convert_type = ncnn::Mat::PIXEL_BGR;
853 if (type_to_pixel != pixel_convert_type)
854 {
855 pixel_convert_type = pixel_convert_type | (type_to_pixel << ncnn::Mat::PIXEL_CONVERT_SHIFT);
856 }
857
858 ncnn::Mat in = read_and_resize_image(shapes[j], listspaths[j][i], pixel_convert_type);
859
860 in.substract_mean_normalize(mean_vals.data(), norm_vals.data());
861
862 ex.input(input_blobs[j], in);
863 }
864
865 for (int j = 0; j < conv_bottom_blob_count; j++)
866 {
867 ncnn::Mat out;
868 ex.extract(conv_bottom_blobs[j], out);
869
870 // count absmax
871 {
872 float absmax = 0.f;
873
874 const int outc = out.c;
875 const int outsize = out.w * out.h;
876 for (int p = 0; p < outc; p++)
877 {
878 const float* ptr = out.channel(p);
879 for (int k = 0; k < outsize; k++)
880 {
881 absmax = std::max(absmax, (float)fabs(ptr[k]));
882 }
883 }
884
885 #pragma omp critical
886 {
887 QuantBlobStat& stat = quant_blob_stats[j];
888 stat.absmax = std::max(stat.absmax, absmax);
889 stat.total = outc * outsize;
890 }
891 }
892 }
893 }
894
895 // alpha gaussian
896 #pragma omp parallel for num_threads(quantize_num_threads)
897 for (int i = 0; i < conv_bottom_blob_count; i++)
898 {
899 QuantBlobStat& stat = quant_blob_stats[i];
900
901 stat.threshold = compute_aciq_gaussian_clip(stat.absmax, stat.total);
902 float scale = 127 / stat.threshold;
903
904 bottom_blob_scales[i].create(1);
905 bottom_blob_scales[i][0] = scale;
906 }
907
908 return 0;
909}
910
911static float cosine_similarity(const ncnn::Mat& a, const ncnn::Mat& b)
912{
913 const int chanenls = a.c;
914 const int size = a.w * a.h;
915
916 float sa = 0;
917 float sb = 0;
918 float sum = 0;
919
920 for (int p = 0; p < chanenls; p++)
921 {
922 const float* pa = a.channel(p);
923 const float* pb = b.channel(p);
924
925 for (int i = 0; i < size; i++)
926 {
927 sa += pa[i] * pa[i];
928 sb += pb[i] * pb[i];
929 sum += pa[i] * pb[i];
930 }
931 }
932
933 float sim = (float)sum / sqrt(sa) / sqrt(sb);
934
935 return sim;
936}
937
938static int get_layer_param(const ncnn::Layer* layer, ncnn::ParamDict& pd)
939{
940 if (layer->type == "Convolution")
941 {
942 ncnn::Convolution* convolution = (ncnn::Convolution*)layer;
943
944 pd.set(0, convolution->num_output);
945 pd.set(1, convolution->kernel_w);
946 pd.set(11, convolution->kernel_h);
947 pd.set(2, convolution->dilation_w);
948 pd.set(12, convolution->dilation_h);
949 pd.set(3, convolution->stride_w);
950 pd.set(13, convolution->stride_h);
951 pd.set(4, convolution->pad_left);
952 pd.set(15, convolution->pad_right);
953 pd.set(14, convolution->pad_top);
954 pd.set(16, convolution->pad_bottom);
955 pd.set(18, convolution->pad_value);
956 pd.set(5, convolution->bias_term);
957 pd.set(6, convolution->weight_data_size);
958 pd.set(8, convolution->int8_scale_term);
959 pd.set(9, convolution->activation_type);
960 pd.set(10, convolution->activation_params);
961 }
962 else if (layer->type == "ConvolutionDepthWise")
963 {
964 ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layer;
965
966 pd.set(0, convolutiondepthwise->num_output);
967 pd.set(1, convolutiondepthwise->kernel_w);
968 pd.set(11, convolutiondepthwise->kernel_h);
969 pd.set(2, convolutiondepthwise->dilation_w);
970 pd.set(12, convolutiondepthwise->dilation_h);
971 pd.set(3, convolutiondepthwise->stride_w);
972 pd.set(13, convolutiondepthwise->stride_h);
973 pd.set(4, convolutiondepthwise->pad_left);
974 pd.set(15, convolutiondepthwise->pad_right);
975 pd.set(14, convolutiondepthwise->pad_top);
976 pd.set(16, convolutiondepthwise->pad_bottom);
977 pd.set(18, convolutiondepthwise->pad_value);
978 pd.set(5, convolutiondepthwise->bias_term);
979 pd.set(6, convolutiondepthwise->weight_data_size);
980 pd.set(7, convolutiondepthwise->group);
981 pd.set(8, convolutiondepthwise->int8_scale_term);
982 pd.set(9, convolutiondepthwise->activation_type);
983 pd.set(10, convolutiondepthwise->activation_params);
984 }
985 else if (layer->type == "InnerProduct")
986 {
987 ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layer;
988
989 pd.set(0, innerproduct->num_output);
990 pd.set(1, innerproduct->bias_term);
991 pd.set(2, innerproduct->weight_data_size);
992 pd.set(8, innerproduct->int8_scale_term);
993 pd.set(9, innerproduct->activation_type);
994 pd.set(10, innerproduct->activation_params);
995 }
996 else
997 {
998 fprintf(stderr, "unexpected layer type %s in get_layer_param\n", layer->type.c_str());
999 return -1;
1000 }
1001
1002 return 0;
1003}
1004
1005static int get_layer_weights(const ncnn::Layer* layer, std::vector<ncnn::Mat>& weights)
1006{
1007 if (layer->type == "Convolution")
1008 {
1009 ncnn::Convolution* convolution = (ncnn::Convolution*)layer;
1010 weights.push_back(convolution->weight_data);
1011 if (convolution->bias_term)
1012 weights.push_back(convolution->bias_data);
1013 }
1014 else if (layer->type == "ConvolutionDepthWise")
1015 {
1016 ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layer;
1017 weights.push_back(convolutiondepthwise->weight_data);
1018 if (convolutiondepthwise->bias_term)
1019 weights.push_back(convolutiondepthwise->bias_data);
1020 }
1021 else if (layer->type == "InnerProduct")
1022 {
1023 ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layer;
1024 weights.push_back(innerproduct->weight_data);
1025 if (innerproduct->bias_term)
1026 weights.push_back(innerproduct->bias_data);
1027 }
1028 else
1029 {
1030 fprintf(stderr, "unexpected layer type %s in get_layer_weights\n", layer->type.c_str());
1031 return -1;
1032 }
1033
1034 return 0;
1035}
1036
1037int QuantNet::quantize_EQ()
1038{
1039 // find the initial scale via KL
1040 quantize_KL();
1041
1042 print_quant_info();
1043
1044 const int input_blob_count = (int)input_blobs.size();
1045 const int conv_layer_count = (int)conv_layers.size();
1046 const int conv_bottom_blob_count = (int)conv_bottom_blobs.size();
1047
1048 std::vector<ncnn::UnlockedPoolAllocator> blob_allocators(quantize_num_threads);
1049 std::vector<ncnn::UnlockedPoolAllocator> workspace_allocators(quantize_num_threads);
1050
1051 // max 50 images for EQ
1052 const int image_count = std::min((int)listspaths[0].size(), 50);
1053
1054 const float scale_range_lower = 0.5f;
1055 const float scale_range_upper = 2.0f;
1056 const int search_steps = 100;
1057
1058 for (int i = 0; i < conv_layer_count; i++)
1059 {
1060 ncnn::Mat& weight_scale = weight_scales[i];
1061 ncnn::Mat& bottom_blob_scale = bottom_blob_scales[i];
1062
1063 const ncnn::Layer* layer = layers[conv_layers[i]];
1064
1065 // search weight scale
1066 for (int j = 0; j < weight_scale.w; j++)
1067 {
1068 const float scale = weight_scale[j];
1069 const float scale_lower = scale * scale_range_lower;
1070 const float scale_upper = scale * scale_range_upper;
1071 const float scale_step = (scale_upper - scale_lower) / search_steps;
1072
1073 std::vector<double> avgsims(search_steps, 0.0);
1074
1075 #pragma omp parallel for num_threads(quantize_num_threads) schedule(static, 1)
1076 for (int ii = 0; ii < image_count; ii++)
1077 {
1078 if (ii % 100 == 0)
1079 {
1080 fprintf(stderr, "search weight scale %.2f%% [ %d / %d ] for %d / %d of %d / %d\n", ii * 100.f / image_count, ii, image_count, j, weight_scale.w, i, conv_layer_count);
1081 }
1082
1083 ncnn::Extractor ex = create_extractor();
1084 ex.set_light_mode(true);
1085
1086 const int thread_num = ncnn::get_omp_thread_num();
1087 ex.set_blob_allocator(&blob_allocators[thread_num]);
1088 ex.set_workspace_allocator(&workspace_allocators[thread_num]);
1089
1090 for (int jj = 0; jj < input_blob_count; jj++)
1091 {
1092 const int type_to_pixel = type_to_pixels[jj];
1093 const std::vector<float>& mean_vals = means[jj];
1094 const std::vector<float>& norm_vals = norms[jj];
1095
1096 int pixel_convert_type = ncnn::Mat::PIXEL_BGR;
1097 if (type_to_pixel != pixel_convert_type)
1098 {
1099 pixel_convert_type = pixel_convert_type | (type_to_pixel << ncnn::Mat::PIXEL_CONVERT_SHIFT);
1100 }
1101
1102 ncnn::Mat in = read_and_resize_image(shapes[jj], listspaths[jj][ii], pixel_convert_type);
1103
1104 in.substract_mean_normalize(mean_vals.data(), norm_vals.data());
1105
1106 ex.input(input_blobs[jj], in);
1107 }
1108
1109 ncnn::Mat in;
1110 ex.extract(conv_bottom_blobs[i], in);
1111
1112 ncnn::Mat out;
1113 ex.extract(conv_top_blobs[i], out);
1114
1115 ncnn::Layer* layer_int8 = ncnn::create_layer_cpu(layer->typeindex);
1116
1117 ncnn::ParamDict pd;
1118 get_layer_param(layer, pd);
1119 pd.set(8, 1); //int8_scale_term
1120 layer_int8->load_param(pd);
1121
1122 std::vector<float> sims(search_steps);
1123 for (int k = 0; k < search_steps; k++)
1124 {
1125 ncnn::Mat new_weight_scale = weight_scale.clone();
1126 new_weight_scale[j] = scale_lower + k * scale_step;
1127
1128 std::vector<ncnn::Mat> weights;
1129 get_layer_weights(layer, weights);
1130 weights.push_back(new_weight_scale);
1131 weights.push_back(bottom_blob_scale);
1132 layer_int8->load_model(ncnn::ModelBinFromMatArray(weights.data()));
1133
1134 ncnn::Option opt_int8;
1135 opt_int8.use_packing_layout = false;
1136
1137 layer_int8->create_pipeline(opt_int8);
1138
1139 ncnn::Mat out_int8;
1140 layer_int8->forward(in, out_int8, opt_int8);
1141
1142 layer_int8->destroy_pipeline(opt_int8);
1143
1144 sims[k] = cosine_similarity(out, out_int8);
1145 }
1146
1147 delete layer_int8;
1148
1149 #pragma omp critical
1150 {
1151 for (int k = 0; k < search_steps; k++)
1152 {
1153 avgsims[k] += sims[k];
1154 }
1155 }
1156 }
1157
1158 double max_avgsim = 0.0;
1159 float new_scale = scale;
1160
1161 // find the scale with min cosine distance
1162 for (int k = 0; k < search_steps; k++)
1163 {
1164 if (max_avgsim < avgsims[k])
1165 {
1166 max_avgsim = avgsims[k];
1167 new_scale = scale_lower + k * scale_step;
1168 }
1169 }
1170
1171 fprintf(stderr, "%s w %d = %f -> %f\n", layer->name.c_str(), j, scale, new_scale);
1172 weight_scale[j] = new_scale;
1173 }
1174
1175 // search bottom blob scale
1176 for (int j = 0; j < bottom_blob_scale.w; j++)
1177 {
1178 const float scale = bottom_blob_scale[j];
1179 const float scale_lower = scale * scale_range_lower;
1180 const float scale_upper = scale * scale_range_upper;
1181 const float scale_step = (scale_upper - scale_lower) / search_steps;
1182
1183 std::vector<double> avgsims(search_steps, 0.0);
1184
1185 #pragma omp parallel for num_threads(quantize_num_threads) schedule(static, 1)
1186 for (int ii = 0; ii < image_count; ii++)
1187 {
1188 if (ii % 100 == 0)
1189 {
1190 fprintf(stderr, "search bottom blob scale %.2f%% [ %d / %d ] for %d / %d of %d / %d\n", ii * 100.f / image_count, ii, image_count, j, bottom_blob_scale.w, i, conv_layer_count);
1191 }
1192
1193 ncnn::Extractor ex = create_extractor();
1194 ex.set_light_mode(true);
1195
1196 const int thread_num = ncnn::get_omp_thread_num();
1197 ex.set_blob_allocator(&blob_allocators[thread_num]);
1198 ex.set_workspace_allocator(&workspace_allocators[thread_num]);
1199
1200 for (int jj = 0; jj < input_blob_count; jj++)
1201 {
1202 const int type_to_pixel = type_to_pixels[jj];
1203 const std::vector<float>& mean_vals = means[jj];
1204 const std::vector<float>& norm_vals = norms[jj];
1205
1206 int pixel_convert_type = ncnn::Mat::PIXEL_BGR;
1207 if (type_to_pixel != pixel_convert_type)
1208 {
1209 pixel_convert_type = pixel_convert_type | (type_to_pixel << ncnn::Mat::PIXEL_CONVERT_SHIFT);
1210 }
1211
1212 ncnn::Mat in = read_and_resize_image(shapes[jj], listspaths[jj][ii], pixel_convert_type);
1213
1214 in.substract_mean_normalize(mean_vals.data(), norm_vals.data());
1215
1216 ex.input(input_blobs[jj], in);
1217 }
1218
1219 ncnn::Mat in;
1220 ex.extract(conv_bottom_blobs[i], in);
1221
1222 ncnn::Mat out;
1223 ex.extract(conv_top_blobs[i], out);
1224
1225 ncnn::Layer* layer_int8 = ncnn::create_layer_cpu(layer->typeindex);
1226
1227 ncnn::ParamDict pd;
1228 get_layer_param(layer, pd);
1229 pd.set(8, 1); //int8_scale_term
1230 layer_int8->load_param(pd);
1231
1232 std::vector<float> sims(search_steps);
1233 for (int k = 0; k < search_steps; k++)
1234 {
1235 ncnn::Mat new_bottom_blob_scale = bottom_blob_scale.clone();
1236 new_bottom_blob_scale[j] = scale_lower + k * scale_step;
1237
1238 std::vector<ncnn::Mat> weights;
1239 get_layer_weights(layer, weights);
1240 weights.push_back(weight_scale);
1241 weights.push_back(new_bottom_blob_scale);
1242 layer_int8->load_model(ncnn::ModelBinFromMatArray(weights.data()));
1243
1244 ncnn::Option opt_int8;
1245 opt_int8.use_packing_layout = false;
1246
1247 layer_int8->create_pipeline(opt_int8);
1248
1249 ncnn::Mat out_int8;
1250 layer_int8->forward(in, out_int8, opt_int8);
1251
1252 layer_int8->destroy_pipeline(opt_int8);
1253
1254 sims[k] = cosine_similarity(out, out_int8);
1255 }
1256
1257 delete layer_int8;
1258
1259 #pragma omp critical
1260 {
1261 for (int k = 0; k < search_steps; k++)
1262 {
1263 avgsims[k] += sims[k];
1264 }
1265 }
1266 }
1267
1268 double max_avgsim = 0.0;
1269 float new_scale = scale;
1270
1271 // find the scale with min cosine distance
1272 for (int k = 0; k < search_steps; k++)
1273 {
1274 if (max_avgsim < avgsims[k])
1275 {
1276 max_avgsim = avgsims[k];
1277 new_scale = scale_lower + k * scale_step;
1278 }
1279 }
1280
1281 fprintf(stderr, "%s b %d = %f -> %f\n", layer->name.c_str(), j, scale, new_scale);
1282 bottom_blob_scale[j] = new_scale;
1283 }
1284
1285 // update quant info
1286 QuantBlobStat& stat = quant_blob_stats[i];
1287 stat.threshold = 127 / bottom_blob_scale[0];
1288 }
1289
1290 return 0;
1291}
1292
1293static std::vector<std::vector<std::string> > parse_comma_path_list(char* s)
1294{
1295 std::vector<std::vector<std::string> > aps;
1296
1297 char* pch = strtok(s, ",");
1298 while (pch != NULL)
1299 {
1300 FILE* fp = fopen(pch, "rb");
1301 if (!fp)
1302 {
1303 fprintf(stderr, "fopen %s failed\n", pch);
1304 break;
1305 }
1306
1307 std::vector<std::string> paths;
1308
1309 // one filepath per line
1310 char line[1024];
1311 while (!feof(fp))
1312 {
1313 char* ss = fgets(line, 1024, fp);
1314 if (!ss)
1315 break;
1316
1317 char filepath[256];
1318 int nscan = sscanf(line, "%255s", filepath);
1319 if (nscan != 1)
1320 continue;
1321
1322 paths.push_back(std::string(filepath));
1323 }
1324
1325 fclose(fp);
1326
1327 aps.push_back(paths);
1328
1329 pch = strtok(NULL, ",");
1330 }
1331
1332 return aps;
1333}
1334
1335static float vstr_to_float(const char vstr[20])
1336{
1337 double v = 0.0;
1338
1339 const char* p = vstr;
1340
1341 // sign
1342 bool sign = *p != '-';
1343 if (*p == '+' || *p == '-')
1344 {
1345 p++;
1346 }
1347
1348 // digits before decimal point or exponent
1349 uint64_t v1 = 0;
1350 while (isdigit(*p))
1351 {
1352 v1 = v1 * 10 + (*p - '0');
1353 p++;
1354 }
1355
1356 v = (double)v1;
1357
1358 // digits after decimal point
1359 if (*p == '.')
1360 {
1361 p++;
1362
1363 uint64_t pow10 = 1;
1364 uint64_t v2 = 0;
1365
1366 while (isdigit(*p))
1367 {
1368 v2 = v2 * 10 + (*p - '0');
1369 pow10 *= 10;
1370 p++;
1371 }
1372
1373 v += v2 / (double)pow10;
1374 }
1375
1376 // exponent
1377 if (*p == 'e' || *p == 'E')
1378 {
1379 p++;
1380
1381 // sign of exponent
1382 bool fact = *p != '-';
1383 if (*p == '+' || *p == '-')
1384 {
1385 p++;
1386 }
1387
1388 // digits of exponent
1389 uint64_t expon = 0;
1390 while (isdigit(*p))
1391 {
1392 expon = expon * 10 + (*p - '0');
1393 p++;
1394 }
1395
1396 double scale = 1.0;
1397 while (expon >= 8)
1398 {
1399 scale *= 1e8;
1400 expon -= 8;
1401 }
1402 while (expon > 0)
1403 {
1404 scale *= 10.0;
1405 expon -= 1;
1406 }
1407
1408 v = fact ? v * scale : v / scale;
1409 }
1410
1411 // fprintf(stderr, "v = %f\n", v);
1412 return sign ? (float)v : (float)-v;
1413}
1414
1415static std::vector<std::vector<float> > parse_comma_float_array_list(char* s)
1416{
1417 std::vector<std::vector<float> > aaf;
1418
1419 char* pch = strtok(s, "[]");
1420 while (pch != NULL)
1421 {
1422 // parse a,b,c
1423 char vstr[20];
1424 int nconsumed = 0;
1425 int nscan = sscanf(pch, "%19[^,]%n", vstr, &nconsumed);
1426 if (nscan == 1)
1427 {
1428 // ok we get array
1429 pch += nconsumed;
1430
1431 std::vector<float> af;
1432 float v = vstr_to_float(vstr);
1433 af.push_back(v);
1434
1435 nscan = sscanf(pch, ",%19[^,]%n", vstr, &nconsumed);
1436 while (nscan == 1)
1437 {
1438 pch += nconsumed;
1439
1440 float v = vstr_to_float(vstr);
1441 af.push_back(v);
1442
1443 nscan = sscanf(pch, ",%19[^,]%n", vstr, &nconsumed);
1444 }
1445
1446 // array end
1447 aaf.push_back(af);
1448 }
1449
1450 pch = strtok(NULL, "[]");
1451 }
1452
1453 return aaf;
1454}
1455
1456static std::vector<std::vector<int> > parse_comma_int_array_list(char* s)
1457{
1458 std::vector<std::vector<int> > aai;
1459
1460 char* pch = strtok(s, "[]");
1461 while (pch != NULL)
1462 {
1463 // parse a,b,c
1464 int v;
1465 int nconsumed = 0;
1466 int nscan = sscanf(pch, "%d%n", &v, &nconsumed);
1467 if (nscan == 1)
1468 {
1469 // ok we get array
1470 pch += nconsumed;
1471
1472 std::vector<int> ai;
1473 ai.push_back(v);
1474
1475 nscan = sscanf(pch, ",%d%n", &v, &nconsumed);
1476 while (nscan == 1)
1477 {
1478 pch += nconsumed;
1479
1480 ai.push_back(v);
1481
1482 nscan = sscanf(pch, ",%d%n", &v, &nconsumed);
1483 }
1484
1485 // array end
1486 aai.push_back(ai);
1487 }
1488
1489 pch = strtok(NULL, "[]");
1490 }
1491
1492 return aai;
1493}
1494
1495static std::vector<int> parse_comma_pixel_type_list(char* s)
1496{
1497 std::vector<int> aps;
1498
1499 char* pch = strtok(s, ",");
1500 while (pch != NULL)
1501 {
1502 // RAW/RGB/BGR/GRAY/RGBA/BGRA
1503 if (strcmp(pch, "RAW") == 0)
1504 aps.push_back(-233);
1505 if (strcmp(pch, "RGB") == 0)
1506 aps.push_back(ncnn::Mat::PIXEL_RGB);
1507 if (strcmp(pch, "BGR") == 0)
1508 aps.push_back(ncnn::Mat::PIXEL_BGR);
1509 if (strcmp(pch, "GRAY") == 0)
1510 aps.push_back(ncnn::Mat::PIXEL_GRAY);
1511 if (strcmp(pch, "RGBA") == 0)
1512 aps.push_back(ncnn::Mat::PIXEL_RGBA);
1513 if (strcmp(pch, "BGRA") == 0)
1514 aps.push_back(ncnn::Mat::PIXEL_BGRA);
1515
1516 pch = strtok(NULL, ",");
1517 }
1518
1519 return aps;
1520}
1521
1522static void print_float_array_list(const std::vector<std::vector<float> >& list)
1523{
1524 for (size_t i = 0; i < list.size(); i++)
1525 {
1526 const std::vector<float>& array = list[i];
1527 fprintf(stderr, "[");
1528 for (size_t j = 0; j < array.size(); j++)
1529 {
1530 fprintf(stderr, "%f", array[j]);
1531 if (j != array.size() - 1)
1532 fprintf(stderr, ",");
1533 }
1534 fprintf(stderr, "]");
1535 if (i != list.size() - 1)
1536 fprintf(stderr, ",");
1537 }
1538}
1539
1540static void print_int_array_list(const std::vector<std::vector<int> >& list)
1541{
1542 for (size_t i = 0; i < list.size(); i++)
1543 {
1544 const std::vector<int>& array = list[i];
1545 fprintf(stderr, "[");
1546 for (size_t j = 0; j < array.size(); j++)
1547 {
1548 fprintf(stderr, "%d", array[j]);
1549 if (j != array.size() - 1)
1550 fprintf(stderr, ",");
1551 }
1552 fprintf(stderr, "]");
1553 if (i != list.size() - 1)
1554 fprintf(stderr, ",");
1555 }
1556}
1557
1558static void print_pixel_type_list(const std::vector<int>& list)
1559{
1560 for (size_t i = 0; i < list.size(); i++)
1561 {
1562 const int type = list[i];
1563 if (type == -233)
1564 fprintf(stderr, "RAW");
1565 if (type == ncnn::Mat::PIXEL_RGB)
1566 fprintf(stderr, "RGB");
1567 if (type == ncnn::Mat::PIXEL_BGR)
1568 fprintf(stderr, "BGR");
1569 if (type == ncnn::Mat::PIXEL_GRAY)
1570 fprintf(stderr, "GRAY");
1571 if (type == ncnn::Mat::PIXEL_RGBA)
1572 fprintf(stderr, "RGBA");
1573 if (type == ncnn::Mat::PIXEL_BGRA)
1574 fprintf(stderr, "BGRA");
1575 if (i != list.size() - 1)
1576 fprintf(stderr, ",");
1577 }
1578}
1579
1580static void show_usage()
1581{
1582 fprintf(stderr, "Usage: ncnn2table [ncnnparam] [ncnnbin] [list,...] [ncnntable] [(key=value)...]\n");
1583 fprintf(stderr, " mean=[104.0,117.0,123.0],...\n");
1584 fprintf(stderr, " norm=[1.0,1.0,1.0],...\n");
1585 fprintf(stderr, " shape=[224,224,3],...[w,h,c] or [w,h] **[0,0] will not resize\n");
1586 fprintf(stderr, " pixel=RAW/RGB/BGR/GRAY/RGBA/BGRA,...\n");
1587 fprintf(stderr, " thread=8\n");
1588 fprintf(stderr, " method=kl/aciq/eq\n");
1589 fprintf(stderr, "Sample usage: ncnn2table squeezenet.param squeezenet.bin imagelist.txt squeezenet.table mean=[104.0,117.0,123.0] norm=[1.0,1.0,1.0] shape=[227,227,3] pixel=BGR method=kl\n");
1590}
1591
1592int main(int argc, char** argv)
1593{
1594 if (argc < 5)
1595 {
1596 show_usage();
1597 return -1;
1598 }
1599
1600 for (int i = 1; i < argc; i++)
1601 {
1602 if (argv[i][0] == '-')
1603 {
1604 show_usage();
1605 return -1;
1606 }
1607 }
1608
1609 const char* inparam = argv[1];
1610 const char* inbin = argv[2];
1611 char* lists = argv[3];
1612 const char* outtable = argv[4];
1613
1614 ncnn::Option opt;
1615 opt.num_threads = 1;
1616 opt.lightmode = false;
1617 opt.use_fp16_packed = false;
1618 opt.use_fp16_storage = false;
1619 opt.use_fp16_arithmetic = false;
1620
1621 QuantNet net;
1622 net.opt = opt;
1623 net.load_param(inparam);
1624 net.load_model(inbin);
1625
1626 net.init();
1627
1628 // load lists
1629 net.listspaths = parse_comma_path_list(lists);
1630
1631 std::string method = "kl";
1632
1633 for (int i = 5; i < argc; i++)
1634 {
1635 // key=value
1636 char* kv = argv[i];
1637
1638 char* eqs = strchr(kv, '=');
1639 if (eqs == NULL)
1640 {
1641 fprintf(stderr, "unrecognized arg %s\n", kv);
1642 continue;
1643 }
1644
1645 // split k v
1646 eqs[0] = '\0';
1647 const char* key = kv;
1648 char* value = eqs + 1;
1649
1650 // load mean norm shape
1651 if (memcmp(key, "mean", 4) == 0)
1652 net.means = parse_comma_float_array_list(value);
1653 if (memcmp(key, "norm", 4) == 0)
1654 net.norms = parse_comma_float_array_list(value);
1655 if (memcmp(key, "shape", 5) == 0)
1656 net.shapes = parse_comma_int_array_list(value);
1657 if (memcmp(key, "pixel", 5) == 0)
1658 net.type_to_pixels = parse_comma_pixel_type_list(value);
1659 if (memcmp(key, "thread", 6) == 0)
1660 net.quantize_num_threads = atoi(value);
1661 if (memcmp(key, "method", 6) == 0)
1662 method = std::string(value);
1663 }
1664
1665 // sanity check
1666 const size_t input_blob_count = net.input_blobs.size();
1667 if (net.listspaths.size() != input_blob_count)
1668 {
1669 fprintf(stderr, "expect %d lists, but got %d\n", (int)input_blob_count, (int)net.listspaths.size());
1670 return -1;
1671 }
1672 if (net.means.size() != input_blob_count)
1673 {
1674 fprintf(stderr, "expect %d means, but got %d\n", (int)input_blob_count, (int)net.means.size());
1675 return -1;
1676 }
1677 if (net.norms.size() != input_blob_count)
1678 {
1679 fprintf(stderr, "expect %d norms, but got %d\n", (int)input_blob_count, (int)net.norms.size());
1680 return -1;
1681 }
1682 if (net.shapes.size() != input_blob_count)
1683 {
1684 fprintf(stderr, "expect %d shapes, but got %d\n", (int)input_blob_count, (int)net.shapes.size());
1685 return -1;
1686 }
1687 if (net.type_to_pixels.size() != input_blob_count)
1688 {
1689 fprintf(stderr, "expect %d pixels, but got %d\n", (int)input_blob_count, (int)net.type_to_pixels.size());
1690 return -1;
1691 }
1692 if (net.quantize_num_threads < 0)
1693 {
1694 fprintf(stderr, "malformed thread %d\n", net.quantize_num_threads);
1695 return -1;
1696 }
1697
1698 // print quantnet config
1699 {
1700 fprintf(stderr, "mean = ");
1701 print_float_array_list(net.means);
1702 fprintf(stderr, "\n");
1703 fprintf(stderr, "norm = ");
1704 print_float_array_list(net.norms);
1705 fprintf(stderr, "\n");
1706 fprintf(stderr, "shape = ");
1707 print_int_array_list(net.shapes);
1708 fprintf(stderr, "\n");
1709 fprintf(stderr, "pixel = ");
1710 print_pixel_type_list(net.type_to_pixels);
1711 fprintf(stderr, "\n");
1712 fprintf(stderr, "thread = %d\n", net.quantize_num_threads);
1713 fprintf(stderr, "method = %s\n", method.c_str());
1714 fprintf(stderr, "---------------------------------------\n");
1715 }
1716
1717 if (method == "kl")
1718 {
1719 net.quantize_KL();
1720 }
1721 else if (method == "aciq")
1722 {
1723 net.quantize_ACIQ();
1724 }
1725 else if (method == "eq")
1726 {
1727 net.quantize_EQ();
1728 }
1729 else
1730 {
1731 fprintf(stderr, "not implemented yet !\n");
1732 fprintf(stderr, "unknown method %s, expect kl / aciq / eq\n", method.c_str());
1733 return -1;
1734 }
1735
1736 net.print_quant_info();
1737
1738 net.save_table(outtable);
1739
1740 return 0;
1741}