You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ncnn2table.cpp 51 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596
  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. #ifdef _MSC_VER
  19. #define _CRT_SECURE_NO_DEPRECATE
  20. #endif
  21. #include <float.h>
  22. #include <limits.h>
  23. #include <math.h>
  24. #include <stdio.h>
  25. #include <stdint.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. // #include <algorithm>
  29. // #include <map>
  30. #include <opencv2/core/core.hpp>
  31. #include <opencv2/highgui/highgui.hpp>
  32. #include <string>
  33. #include <vector>
  34. // ncnn public header
  35. #include "benchmark.h"
  36. #include "cpu.h"
  37. #include "net.h"
  38. // ncnn private header
  39. #include "layer/convolution.h"
  40. #include "layer/convolutiondepthwise.h"
  41. #include "layer/innerproduct.h"
  42. class QuantBlobStat
  43. {
  44. public:
  45. QuantBlobStat()
  46. {
  47. threshold = 0.f;
  48. absmax = 0.f;
  49. total = 0;
  50. }
  51. public:
  52. float threshold;
  53. float absmax;
  54. // ACIQ
  55. int total;
  56. // KL
  57. std::vector<uint64_t> histogram;
  58. std::vector<float> histogram_normed;
  59. };
  60. class QuantNet : public ncnn::Net
  61. {
  62. public:
  63. QuantNet();
  64. std::vector<ncnn::Blob>& blobs;
  65. std::vector<ncnn::Layer*>& layers;
  66. public:
  67. std::vector<std::vector<std::string> > listspaths;
  68. std::vector<std::vector<float> > means;
  69. std::vector<std::vector<float> > norms;
  70. std::vector<std::vector<int> > shapes;
  71. std::vector<int> type_to_pixels;
  72. int quantize_num_threads;
  73. public:
  74. int init();
  75. void print_quant_info() const;
  76. int save_table(const char* tablepath);
  77. int quantize_KL();
  78. int quantize_ACIQ();
  79. int quantize_EQ();
  80. public:
  81. std::vector<int> input_blobs;
  82. std::vector<int> conv_layers;
  83. std::vector<int> conv_bottom_blobs;
  84. std::vector<int> conv_top_blobs;
  85. // result
  86. std::vector<QuantBlobStat> quant_blob_stats;
  87. std::vector<ncnn::Mat> weight_scales;
  88. std::vector<ncnn::Mat> bottom_blob_scales;
  89. };
  90. QuantNet::QuantNet()
  91. : blobs(mutable_blobs()), layers(mutable_layers())
  92. {
  93. quantize_num_threads = ncnn::get_cpu_count();
  94. }
  95. int QuantNet::init()
  96. {
  97. // find all input layers
  98. for (int i = 0; i < (int)layers.size(); i++)
  99. {
  100. const ncnn::Layer* layer = layers[i];
  101. if (layer->type == "Input")
  102. {
  103. input_blobs.push_back(layer->tops[0]);
  104. }
  105. }
  106. // find all conv layers
  107. for (int i = 0; i < (int)layers.size(); i++)
  108. {
  109. const ncnn::Layer* layer = layers[i];
  110. if (layer->type == "Convolution" || layer->type == "ConvolutionDepthWise" || layer->type == "InnerProduct")
  111. {
  112. conv_layers.push_back(i);
  113. conv_bottom_blobs.push_back(layer->bottoms[0]);
  114. conv_top_blobs.push_back(layer->tops[0]);
  115. }
  116. }
  117. const int conv_layer_count = (int)conv_layers.size();
  118. const int conv_bottom_blob_count = (int)conv_bottom_blobs.size();
  119. quant_blob_stats.resize(conv_bottom_blob_count);
  120. weight_scales.resize(conv_layer_count);
  121. bottom_blob_scales.resize(conv_bottom_blob_count);
  122. return 0;
  123. }
  124. int QuantNet::save_table(const char* tablepath)
  125. {
  126. FILE* fp = fopen(tablepath, "wb");
  127. if (!fp)
  128. {
  129. fprintf(stderr, "fopen %s failed\n", tablepath);
  130. return -1;
  131. }
  132. const int conv_layer_count = (int)conv_layers.size();
  133. const int conv_bottom_blob_count = (int)conv_bottom_blobs.size();
  134. for (int i = 0; i < conv_layer_count; i++)
  135. {
  136. const ncnn::Mat& weight_scale = weight_scales[i];
  137. fprintf(fp, "%s_param_0 ", layers[conv_layers[i]]->name.c_str());
  138. for (int j = 0; j < weight_scale.w; j++)
  139. {
  140. fprintf(fp, "%f ", weight_scale[j]);
  141. }
  142. fprintf(fp, "\n");
  143. }
  144. for (int i = 0; i < conv_bottom_blob_count; i++)
  145. {
  146. const ncnn::Mat& bottom_blob_scale = bottom_blob_scales[i];
  147. fprintf(fp, "%s ", layers[conv_layers[i]]->name.c_str());
  148. for (int j = 0; j < bottom_blob_scale.w; j++)
  149. {
  150. fprintf(fp, "%f ", bottom_blob_scale[j]);
  151. }
  152. fprintf(fp, "\n");
  153. }
  154. fclose(fp);
  155. fprintf(stderr, "ncnn int8 calibration table create success, best wish for your int8 inference has a low accuracy loss...\\(^0^)/...233...\n");
  156. return 0;
  157. }
  158. void QuantNet::print_quant_info() const
  159. {
  160. for (int i = 0; i < (int)conv_bottom_blobs.size(); i++)
  161. {
  162. const QuantBlobStat& stat = quant_blob_stats[i];
  163. float scale = 127 / stat.threshold;
  164. fprintf(stderr, "%-40s : max = %-15f threshold = %-15f scale = %-15f\n", layers[conv_layers[i]]->name.c_str(), stat.absmax, stat.threshold, scale);
  165. }
  166. }
  167. static float compute_kl_divergence(const std::vector<float>& a, const std::vector<float>& b)
  168. {
  169. const size_t length = a.size();
  170. float result = 0;
  171. for (size_t i = 0; i < length; i++)
  172. {
  173. result += a[i] * log(a[i] / b[i]);
  174. }
  175. return result;
  176. }
  177. int QuantNet::quantize_KL()
  178. {
  179. const int input_blob_count = (int)input_blobs.size();
  180. const int conv_layer_count = (int)conv_layers.size();
  181. const int conv_bottom_blob_count = (int)conv_bottom_blobs.size();
  182. const int image_count = (int)listspaths[0].size();
  183. const int num_histogram_bins = 2048;
  184. // initialize conv weight scales
  185. #pragma omp parallel for num_threads(quantize_num_threads)
  186. for (int i = 0; i < conv_layer_count; i++)
  187. {
  188. const ncnn::Layer* layer = layers[conv_layers[i]];
  189. if (layer->type == "Convolution")
  190. {
  191. const ncnn::Convolution* convolution = (const ncnn::Convolution*)layer;
  192. const int num_output = convolution->num_output;
  193. const int kernel_w = convolution->kernel_w;
  194. const int kernel_h = convolution->kernel_h;
  195. const int dilation_w = convolution->dilation_w;
  196. const int dilation_h = convolution->dilation_h;
  197. const int stride_w = convolution->stride_w;
  198. const int stride_h = convolution->stride_h;
  199. const int weight_data_size_output = convolution->weight_data_size / num_output;
  200. // int8 winograd F43 needs weight data to use 6bit quantization
  201. // TODO proper condition for winograd 3x3 int8
  202. bool quant_6bit = false;
  203. if (kernel_w == 3 && kernel_h == 3 && dilation_w == 1 && dilation_h == 1 && stride_w == 1 && stride_h == 1)
  204. quant_6bit = true;
  205. weight_scales[i].create(num_output);
  206. for (int n = 0; n < num_output; n++)
  207. {
  208. const ncnn::Mat weight_data_n = convolution->weight_data.range(weight_data_size_output * n, weight_data_size_output);
  209. float absmax = 0.f;
  210. for (int k = 0; k < weight_data_size_output; k++)
  211. {
  212. absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
  213. }
  214. if (quant_6bit)
  215. {
  216. weight_scales[i][n] = 31 / absmax;
  217. }
  218. else
  219. {
  220. weight_scales[i][n] = 127 / absmax;
  221. }
  222. }
  223. }
  224. if (layer->type == "ConvolutionDepthWise")
  225. {
  226. const ncnn::ConvolutionDepthWise* convolutiondepthwise = (const ncnn::ConvolutionDepthWise*)layer;
  227. const int group = convolutiondepthwise->group;
  228. const int weight_data_size_output = convolutiondepthwise->weight_data_size / group;
  229. std::vector<float> scales;
  230. weight_scales[i].create(group);
  231. for (int n = 0; n < group; n++)
  232. {
  233. const ncnn::Mat weight_data_n = convolutiondepthwise->weight_data.range(weight_data_size_output * n, weight_data_size_output);
  234. float absmax = 0.f;
  235. for (int k = 0; k < weight_data_size_output; k++)
  236. {
  237. absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
  238. }
  239. weight_scales[i][n] = 127 / absmax;
  240. }
  241. }
  242. if (layer->type == "InnerProduct")
  243. {
  244. const ncnn::InnerProduct* innerproduct = (const ncnn::InnerProduct*)layer;
  245. const int num_output = innerproduct->num_output;
  246. const int weight_data_size_output = innerproduct->weight_data_size / num_output;
  247. weight_scales[i].create(num_output);
  248. for (int n = 0; n < num_output; n++)
  249. {
  250. const ncnn::Mat weight_data_n = innerproduct->weight_data.range(weight_data_size_output * n, weight_data_size_output);
  251. float absmax = 0.f;
  252. for (int k = 0; k < weight_data_size_output; k++)
  253. {
  254. absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
  255. }
  256. weight_scales[i][n] = 127 / absmax;
  257. }
  258. }
  259. }
  260. // count the absmax
  261. #pragma omp parallel for num_threads(quantize_num_threads)
  262. for (int i = 0; i < image_count; i++)
  263. {
  264. ncnn::Extractor ex = create_extractor();
  265. for (int j = 0; j < input_blob_count; j++)
  266. {
  267. const std::string& imagepath = listspaths[j][i];
  268. const std::vector<int>& shape = shapes[j];
  269. const int type_to_pixel = type_to_pixels[j];
  270. const std::vector<float>& mean_vals = means[j];
  271. const std::vector<float>& norm_vals = norms[j];
  272. int pixel_convert_type = ncnn::Mat::PIXEL_BGR;
  273. if (type_to_pixel != pixel_convert_type)
  274. {
  275. pixel_convert_type = pixel_convert_type | (type_to_pixel << ncnn::Mat::PIXEL_CONVERT_SHIFT);
  276. }
  277. const int target_w = shape[0];
  278. const int target_h = shape[1];
  279. cv::Mat bgr = cv::imread(imagepath, 1);
  280. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, pixel_convert_type, bgr.cols, bgr.rows, target_w, target_h);
  281. in.substract_mean_normalize(mean_vals.data(), norm_vals.data());
  282. ex.input(input_blobs[j], in);
  283. }
  284. for (int j = 0; j < conv_bottom_blob_count; j++)
  285. {
  286. ncnn::Mat out;
  287. ex.extract(conv_bottom_blobs[j], out);
  288. // count absmax
  289. {
  290. float absmax = 0.f;
  291. const int outc = out.c;
  292. const int outsize = out.w * out.h;
  293. for (int p = 0; p < outc; p++)
  294. {
  295. const float* ptr = out.channel(p);
  296. for (int k = 0; k < outsize; k++)
  297. {
  298. absmax = std::max(absmax, (float)fabs(ptr[k]));
  299. }
  300. }
  301. #pragma omp critical
  302. {
  303. QuantBlobStat& stat = quant_blob_stats[j];
  304. stat.absmax = std::max(stat.absmax, absmax);
  305. }
  306. }
  307. }
  308. }
  309. // initialize histogram
  310. #pragma omp parallel for num_threads(quantize_num_threads)
  311. for (int i = 0; i < conv_bottom_blob_count; i++)
  312. {
  313. QuantBlobStat& stat = quant_blob_stats[i];
  314. stat.histogram.resize(num_histogram_bins, 0);
  315. stat.histogram_normed.resize(num_histogram_bins, 0);
  316. }
  317. // build histogram
  318. #pragma omp parallel for num_threads(quantize_num_threads)
  319. for (int i = 0; i < image_count; i++)
  320. {
  321. ncnn::Extractor ex = create_extractor();
  322. for (int j = 0; j < input_blob_count; j++)
  323. {
  324. const std::string& imagepath = listspaths[j][i];
  325. const std::vector<int>& shape = shapes[j];
  326. const int type_to_pixel = type_to_pixels[j];
  327. const std::vector<float>& mean_vals = means[j];
  328. const std::vector<float>& norm_vals = norms[j];
  329. int pixel_convert_type = ncnn::Mat::PIXEL_BGR;
  330. if (type_to_pixel != pixel_convert_type)
  331. {
  332. pixel_convert_type = pixel_convert_type | (type_to_pixel << ncnn::Mat::PIXEL_CONVERT_SHIFT);
  333. }
  334. const int target_w = shape[0];
  335. const int target_h = shape[1];
  336. cv::Mat bgr = cv::imread(imagepath, 1);
  337. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, pixel_convert_type, bgr.cols, bgr.rows, target_w, target_h);
  338. in.substract_mean_normalize(mean_vals.data(), norm_vals.data());
  339. ex.input(input_blobs[j], in);
  340. }
  341. for (int j = 0; j < conv_bottom_blob_count; j++)
  342. {
  343. ncnn::Mat out;
  344. ex.extract(conv_bottom_blobs[j], out);
  345. // count histogram bin
  346. {
  347. const float absmax = quant_blob_stats[j].absmax;
  348. std::vector<uint64_t> histogram(num_histogram_bins, 0);
  349. const int outc = out.c;
  350. const int outsize = out.w * out.h;
  351. for (int p = 0; p < outc; p++)
  352. {
  353. const float* ptr = out.channel(p);
  354. for (int k = 0; k < outsize; k++)
  355. {
  356. if (ptr[k] == 0.f)
  357. continue;
  358. const int index = std::min((int)(fabs(ptr[k]) / absmax * num_histogram_bins), (num_histogram_bins - 1));
  359. histogram[index] += 1;
  360. }
  361. }
  362. #pragma omp critical
  363. {
  364. QuantBlobStat& stat = quant_blob_stats[j];
  365. for (int k = 0; k < num_histogram_bins; k++)
  366. {
  367. stat.histogram[k] += histogram[k];
  368. }
  369. }
  370. }
  371. }
  372. }
  373. // using kld to find the best threshold value
  374. #pragma omp parallel for num_threads(quantize_num_threads)
  375. for (int i = 0; i < conv_bottom_blob_count; i++)
  376. {
  377. QuantBlobStat& stat = quant_blob_stats[i];
  378. // normalize histogram bin
  379. {
  380. uint64_t sum = 0;
  381. for (int j = 0; j < num_histogram_bins; j++)
  382. {
  383. sum += stat.histogram[j];
  384. }
  385. for (int j = 0; j < num_histogram_bins; j++)
  386. {
  387. stat.histogram_normed[j] = (float)(stat.histogram[j] / (double)sum);
  388. }
  389. }
  390. const int target_bin = 128;
  391. int target_threshold = target_bin;
  392. float min_kl_divergence = FLT_MAX;
  393. for (int threshold = target_bin; threshold < num_histogram_bins; threshold++)
  394. {
  395. const float kl_eps = 0.0001f;
  396. std::vector<float> clip_distribution(threshold, kl_eps);
  397. {
  398. for (int j = 0; j < threshold; j++)
  399. {
  400. clip_distribution[j] += stat.histogram_normed[j];
  401. }
  402. for (int j = threshold; j < num_histogram_bins; j++)
  403. {
  404. clip_distribution[threshold - 1] += stat.histogram_normed[j];
  405. }
  406. }
  407. const float num_per_bin = (float)threshold / target_bin;
  408. std::vector<float> quantize_distribution(target_bin, 0.f);
  409. {
  410. {
  411. const float end = num_per_bin;
  412. const int right_lower = (int)floor(end);
  413. const float right_scale = end - right_lower;
  414. if (right_scale > 0)
  415. {
  416. quantize_distribution[0] += right_scale * stat.histogram_normed[right_lower];
  417. }
  418. for (int k = 0; k < right_lower; k++)
  419. {
  420. quantize_distribution[0] += stat.histogram_normed[k];
  421. }
  422. quantize_distribution[0] /= right_lower + right_scale;
  423. }
  424. for (int j = 1; j < target_bin - 1; j++)
  425. {
  426. const float start = j * num_per_bin;
  427. const float end = (j + 1) * num_per_bin;
  428. const int left_upper = (int)ceil(start);
  429. const float left_scale = left_upper - start;
  430. const int right_lower = (int)floor(end);
  431. const float right_scale = end - right_lower;
  432. if (left_scale > 0)
  433. {
  434. quantize_distribution[j] += left_scale * stat.histogram_normed[left_upper - 1];
  435. }
  436. if (right_scale > 0)
  437. {
  438. quantize_distribution[j] += right_scale * stat.histogram_normed[right_lower];
  439. }
  440. for (int k = left_upper; k < right_lower; k++)
  441. {
  442. quantize_distribution[j] += stat.histogram_normed[k];
  443. }
  444. quantize_distribution[j] /= right_lower - left_upper + left_scale + right_scale;
  445. }
  446. {
  447. const float start = threshold - num_per_bin;
  448. const int left_upper = (int)ceil(start);
  449. const float left_scale = left_upper - start;
  450. if (left_scale > 0)
  451. {
  452. quantize_distribution[target_bin - 1] += left_scale * stat.histogram_normed[left_upper - 1];
  453. }
  454. for (int k = left_upper; k < threshold; k++)
  455. {
  456. quantize_distribution[target_bin - 1] += stat.histogram_normed[k];
  457. }
  458. quantize_distribution[target_bin - 1] /= threshold - left_upper + left_scale;
  459. }
  460. }
  461. std::vector<float> expand_distribution(threshold, kl_eps);
  462. {
  463. {
  464. const float end = num_per_bin;
  465. const int right_lower = (int)floor(end);
  466. const float right_scale = end - right_lower;
  467. if (right_scale > 0)
  468. {
  469. expand_distribution[right_lower] += right_scale * quantize_distribution[0];
  470. }
  471. for (int k = 0; k < right_lower; k++)
  472. {
  473. expand_distribution[k] += quantize_distribution[0];
  474. }
  475. }
  476. for (int j = 1; j < target_bin - 1; j++)
  477. {
  478. const float start = j * num_per_bin;
  479. const float end = (j + 1) * num_per_bin;
  480. const int left_upper = (int)ceil(start);
  481. const float left_scale = left_upper - start;
  482. const int right_lower = (int)floor(end);
  483. const float right_scale = end - right_lower;
  484. if (left_scale > 0)
  485. {
  486. expand_distribution[left_upper - 1] += left_scale * quantize_distribution[j];
  487. }
  488. if (right_scale > 0)
  489. {
  490. expand_distribution[right_lower] += right_scale * quantize_distribution[j];
  491. }
  492. for (int k = left_upper; k < right_lower; k++)
  493. {
  494. expand_distribution[k] += quantize_distribution[j];
  495. }
  496. }
  497. {
  498. const float start = threshold - num_per_bin;
  499. const int left_upper = (int)ceil(start);
  500. const float left_scale = left_upper - start;
  501. if (left_scale > 0)
  502. {
  503. expand_distribution[left_upper - 1] += left_scale * quantize_distribution[target_bin - 1];
  504. }
  505. for (int k = left_upper; k < threshold; k++)
  506. {
  507. expand_distribution[k] += quantize_distribution[target_bin - 1];
  508. }
  509. }
  510. }
  511. // kl
  512. const float kl_divergence = compute_kl_divergence(clip_distribution, expand_distribution);
  513. // the best num of bin
  514. if (kl_divergence < min_kl_divergence)
  515. {
  516. min_kl_divergence = kl_divergence;
  517. target_threshold = threshold;
  518. }
  519. }
  520. stat.threshold = (target_threshold + 0.5f) * stat.absmax / num_histogram_bins;
  521. float scale = 127 / stat.threshold;
  522. bottom_blob_scales[i].create(1);
  523. bottom_blob_scales[i][0] = scale;
  524. }
  525. return 0;
  526. }
  527. static float compute_aciq_gaussian_clip(float absmax, int N, int num_bits = 8)
  528. {
  529. const float alpha_gaussian[8] = {0, 1.71063519, 2.15159277, 2.55913646, 2.93620062, 3.28691474, 3.6151146, 3.92403714};
  530. const double gaussian_const = (0.5 * 0.35) * (1 + sqrt(3.14159265358979323846 * log(4)));
  531. double std = (absmax * 2 * gaussian_const) / sqrt(2 * log(N));
  532. return (float)(alpha_gaussian[num_bits - 1] * std);
  533. }
  534. int QuantNet::quantize_ACIQ()
  535. {
  536. const int input_blob_count = (int)input_blobs.size();
  537. const int conv_layer_count = (int)conv_layers.size();
  538. const int conv_bottom_blob_count = (int)conv_bottom_blobs.size();
  539. const int image_count = (int)listspaths[0].size();
  540. // initialize conv weight scales
  541. #pragma omp parallel for num_threads(quantize_num_threads)
  542. for (int i = 0; i < conv_layer_count; i++)
  543. {
  544. const ncnn::Layer* layer = layers[conv_layers[i]];
  545. if (layer->type == "Convolution")
  546. {
  547. const ncnn::Convolution* convolution = (const ncnn::Convolution*)layer;
  548. const int num_output = convolution->num_output;
  549. const int kernel_w = convolution->kernel_w;
  550. const int kernel_h = convolution->kernel_h;
  551. const int dilation_w = convolution->dilation_w;
  552. const int dilation_h = convolution->dilation_h;
  553. const int stride_w = convolution->stride_w;
  554. const int stride_h = convolution->stride_h;
  555. const int weight_data_size_output = convolution->weight_data_size / num_output;
  556. // int8 winograd F43 needs weight data to use 6bit quantization
  557. // TODO proper condition for winograd 3x3 int8
  558. bool quant_6bit = false;
  559. if (kernel_w == 3 && kernel_h == 3 && dilation_w == 1 && dilation_h == 1 && stride_w == 1 && stride_h == 1)
  560. quant_6bit = true;
  561. weight_scales[i].create(num_output);
  562. for (int n = 0; n < num_output; n++)
  563. {
  564. const ncnn::Mat weight_data_n = convolution->weight_data.range(weight_data_size_output * n, weight_data_size_output);
  565. float absmax = 0.f;
  566. for (int k = 0; k < weight_data_size_output; k++)
  567. {
  568. absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
  569. }
  570. if (quant_6bit)
  571. {
  572. const float threshold = compute_aciq_gaussian_clip(absmax, weight_data_size_output, 6);
  573. weight_scales[i][n] = 31 / threshold;
  574. }
  575. else
  576. {
  577. const float threshold = compute_aciq_gaussian_clip(absmax, weight_data_size_output);
  578. weight_scales[i][n] = 127 / threshold;
  579. }
  580. }
  581. }
  582. if (layer->type == "ConvolutionDepthWise")
  583. {
  584. const ncnn::ConvolutionDepthWise* convolutiondepthwise = (const ncnn::ConvolutionDepthWise*)layer;
  585. const int group = convolutiondepthwise->group;
  586. const int weight_data_size_output = convolutiondepthwise->weight_data_size / group;
  587. std::vector<float> scales;
  588. weight_scales[i].create(group);
  589. for (int n = 0; n < group; n++)
  590. {
  591. const ncnn::Mat weight_data_n = convolutiondepthwise->weight_data.range(weight_data_size_output * n, weight_data_size_output);
  592. float absmax = 0.f;
  593. for (int k = 0; k < weight_data_size_output; k++)
  594. {
  595. absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
  596. }
  597. const float threshold = compute_aciq_gaussian_clip(absmax, weight_data_size_output);
  598. weight_scales[i][n] = 127 / threshold;
  599. }
  600. }
  601. if (layer->type == "InnerProduct")
  602. {
  603. const ncnn::InnerProduct* innerproduct = (const ncnn::InnerProduct*)layer;
  604. const int num_output = innerproduct->num_output;
  605. const int weight_data_size_output = innerproduct->weight_data_size / num_output;
  606. weight_scales[i].create(num_output);
  607. for (int n = 0; n < num_output; n++)
  608. {
  609. const ncnn::Mat weight_data_n = innerproduct->weight_data.range(weight_data_size_output * n, weight_data_size_output);
  610. float absmax = 0.f;
  611. for (int k = 0; k < weight_data_size_output; k++)
  612. {
  613. absmax = std::max(absmax, (float)fabs(weight_data_n[k]));
  614. }
  615. const float threshold = compute_aciq_gaussian_clip(absmax, weight_data_size_output);
  616. weight_scales[i][n] = 127 / threshold;
  617. }
  618. }
  619. }
  620. // count the absmax abssum
  621. #pragma omp parallel for num_threads(quantize_num_threads)
  622. for (int i = 0; i < image_count; i++)
  623. {
  624. ncnn::Extractor ex = create_extractor();
  625. for (int j = 0; j < input_blob_count; j++)
  626. {
  627. const std::string& imagepath = listspaths[j][i];
  628. const std::vector<int>& shape = shapes[j];
  629. const int type_to_pixel = type_to_pixels[j];
  630. const std::vector<float>& mean_vals = means[j];
  631. const std::vector<float>& norm_vals = norms[j];
  632. int pixel_convert_type = ncnn::Mat::PIXEL_BGR;
  633. if (type_to_pixel != pixel_convert_type)
  634. {
  635. pixel_convert_type = pixel_convert_type | (type_to_pixel << ncnn::Mat::PIXEL_CONVERT_SHIFT);
  636. }
  637. const int target_w = shape[0];
  638. const int target_h = shape[1];
  639. cv::Mat bgr = cv::imread(imagepath, 1);
  640. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, pixel_convert_type, bgr.cols, bgr.rows, target_w, target_h);
  641. in.substract_mean_normalize(mean_vals.data(), norm_vals.data());
  642. ex.input(input_blobs[j], in);
  643. }
  644. for (int j = 0; j < conv_bottom_blob_count; j++)
  645. {
  646. ncnn::Mat out;
  647. ex.extract(conv_bottom_blobs[j], out);
  648. // count absmax
  649. {
  650. float absmax = 0.f;
  651. const int outc = out.c;
  652. const int outsize = out.w * out.h;
  653. for (int p = 0; p < outc; p++)
  654. {
  655. const float* ptr = out.channel(p);
  656. for (int k = 0; k < outsize; k++)
  657. {
  658. absmax = std::max(absmax, (float)fabs(ptr[k]));
  659. }
  660. }
  661. #pragma omp critical
  662. {
  663. QuantBlobStat& stat = quant_blob_stats[j];
  664. stat.absmax = std::max(stat.absmax, absmax);
  665. stat.total = outc * outsize;
  666. }
  667. }
  668. }
  669. }
  670. // alpha gaussian
  671. #pragma omp parallel for num_threads(quantize_num_threads)
  672. for (int i = 0; i < conv_bottom_blob_count; i++)
  673. {
  674. QuantBlobStat& stat = quant_blob_stats[i];
  675. stat.threshold = compute_aciq_gaussian_clip(stat.absmax, stat.total);
  676. float scale = 127 / stat.threshold;
  677. bottom_blob_scales[i].create(1);
  678. bottom_blob_scales[i][0] = scale;
  679. }
  680. return 0;
  681. }
  682. static float cosine_similarity(const ncnn::Mat& a, const ncnn::Mat& b)
  683. {
  684. const int chanenls = a.c;
  685. const int size = a.w * a.h;
  686. float sa = 0;
  687. float sb = 0;
  688. float sum = 0;
  689. for (int p = 0; p < chanenls; p++)
  690. {
  691. const float* pa = a.channel(p);
  692. const float* pb = b.channel(p);
  693. for (int i = 0; i < size; i++)
  694. {
  695. sa += pa[i] * pa[i];
  696. sb += pb[i] * pb[i];
  697. sum += pa[i] * pb[i];
  698. }
  699. }
  700. float sim = (float)sum / sqrt(sa) / sqrt(sb);
  701. return sim;
  702. }
  703. static int get_layer_param(const ncnn::Layer* layer, ncnn::ParamDict& pd)
  704. {
  705. if (layer->type == "Convolution")
  706. {
  707. ncnn::Convolution* convolution = (ncnn::Convolution*)layer;
  708. pd.set(0, convolution->num_output);
  709. pd.set(1, convolution->kernel_w);
  710. pd.set(11, convolution->kernel_h);
  711. pd.set(2, convolution->dilation_w);
  712. pd.set(12, convolution->dilation_h);
  713. pd.set(3, convolution->stride_w);
  714. pd.set(13, convolution->stride_h);
  715. pd.set(4, convolution->pad_left);
  716. pd.set(15, convolution->pad_right);
  717. pd.set(14, convolution->pad_top);
  718. pd.set(16, convolution->pad_bottom);
  719. pd.set(18, convolution->pad_value);
  720. pd.set(5, convolution->bias_term);
  721. pd.set(6, convolution->weight_data_size);
  722. pd.set(8, convolution->int8_scale_term);
  723. pd.set(9, convolution->activation_type);
  724. pd.set(10, convolution->activation_params);
  725. }
  726. else if (layer->type == "ConvolutionDepthWise")
  727. {
  728. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layer;
  729. pd.set(0, convolutiondepthwise->num_output);
  730. pd.set(1, convolutiondepthwise->kernel_w);
  731. pd.set(11, convolutiondepthwise->kernel_h);
  732. pd.set(2, convolutiondepthwise->dilation_w);
  733. pd.set(12, convolutiondepthwise->dilation_h);
  734. pd.set(3, convolutiondepthwise->stride_w);
  735. pd.set(13, convolutiondepthwise->stride_h);
  736. pd.set(4, convolutiondepthwise->pad_left);
  737. pd.set(15, convolutiondepthwise->pad_right);
  738. pd.set(14, convolutiondepthwise->pad_top);
  739. pd.set(16, convolutiondepthwise->pad_bottom);
  740. pd.set(18, convolutiondepthwise->pad_value);
  741. pd.set(5, convolutiondepthwise->bias_term);
  742. pd.set(6, convolutiondepthwise->weight_data_size);
  743. pd.set(7, convolutiondepthwise->group);
  744. pd.set(8, convolutiondepthwise->int8_scale_term);
  745. pd.set(9, convolutiondepthwise->activation_type);
  746. pd.set(10, convolutiondepthwise->activation_params);
  747. }
  748. else if (layer->type == "InnerProduct")
  749. {
  750. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layer;
  751. pd.set(0, innerproduct->num_output);
  752. pd.set(1, innerproduct->bias_term);
  753. pd.set(2, innerproduct->weight_data_size);
  754. pd.set(8, innerproduct->int8_scale_term);
  755. pd.set(9, innerproduct->activation_type);
  756. pd.set(10, innerproduct->activation_params);
  757. }
  758. else
  759. {
  760. fprintf(stderr, "unexpected layer type %s in get_layer_param\n", layer->type.c_str());
  761. return -1;
  762. }
  763. return 0;
  764. }
  765. static int get_layer_weights(const ncnn::Layer* layer, std::vector<ncnn::Mat>& weights)
  766. {
  767. if (layer->type == "Convolution")
  768. {
  769. ncnn::Convolution* convolution = (ncnn::Convolution*)layer;
  770. weights.push_back(convolution->weight_data);
  771. if (convolution->bias_term)
  772. weights.push_back(convolution->bias_data);
  773. }
  774. else if (layer->type == "ConvolutionDepthWise")
  775. {
  776. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layer;
  777. weights.push_back(convolutiondepthwise->weight_data);
  778. if (convolutiondepthwise->bias_term)
  779. weights.push_back(convolutiondepthwise->bias_data);
  780. }
  781. else if (layer->type == "InnerProduct")
  782. {
  783. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layer;
  784. weights.push_back(innerproduct->weight_data);
  785. if (innerproduct->bias_term)
  786. weights.push_back(innerproduct->bias_data);
  787. }
  788. else
  789. {
  790. fprintf(stderr, "unexpected layer type %s in get_layer_weights\n", layer->type.c_str());
  791. return -1;
  792. }
  793. return 0;
  794. }
  795. int QuantNet::quantize_EQ()
  796. {
  797. // find the initial scale via KL
  798. quantize_KL();
  799. print_quant_info();
  800. const int input_blob_count = (int)input_blobs.size();
  801. const int conv_layer_count = (int)conv_layers.size();
  802. const int conv_bottom_blob_count = (int)conv_bottom_blobs.size();
  803. // max 50 images for EQ
  804. const int image_count = std::min((int)listspaths[0].size(), 50);
  805. const float scale_range_lower = 0.5f;
  806. const float scale_range_upper = 2.0f;
  807. const int search_steps = 100;
  808. for (int i = 0; i < conv_layer_count; i++)
  809. {
  810. ncnn::Mat& weight_scale = weight_scales[i];
  811. ncnn::Mat& bottom_blob_scale = bottom_blob_scales[i];
  812. const ncnn::Layer* layer = layers[conv_layers[i]];
  813. // search weight scale
  814. for (int j = 0; j < weight_scale.w; j++)
  815. {
  816. const float scale = weight_scale[j];
  817. const float scale_lower = scale * scale_range_lower;
  818. const float scale_upper = scale * scale_range_upper;
  819. const float scale_step = (scale_upper - scale_lower) / search_steps;
  820. std::vector<double> avgsims(search_steps, 0.0);
  821. #pragma omp parallel for num_threads(quantize_num_threads)
  822. for (int ii = 0; ii < image_count; ii++)
  823. {
  824. ncnn::Extractor ex = create_extractor();
  825. for (int jj = 0; jj < input_blob_count; jj++)
  826. {
  827. const std::string& imagepath = listspaths[jj][ii];
  828. const std::vector<int>& shape = shapes[jj];
  829. const int type_to_pixel = type_to_pixels[jj];
  830. const std::vector<float>& mean_vals = means[jj];
  831. const std::vector<float>& norm_vals = norms[jj];
  832. int pixel_convert_type = ncnn::Mat::PIXEL_BGR;
  833. if (type_to_pixel != pixel_convert_type)
  834. {
  835. pixel_convert_type = pixel_convert_type | (type_to_pixel << ncnn::Mat::PIXEL_CONVERT_SHIFT);
  836. }
  837. const int target_w = shape[0];
  838. const int target_h = shape[1];
  839. cv::Mat bgr = cv::imread(imagepath, 1);
  840. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, pixel_convert_type, bgr.cols, bgr.rows, target_w, target_h);
  841. in.substract_mean_normalize(mean_vals.data(), norm_vals.data());
  842. ex.input(input_blobs[jj], in);
  843. }
  844. ncnn::Mat in;
  845. ex.extract(conv_bottom_blobs[i], in);
  846. ncnn::Mat out;
  847. ex.extract(conv_top_blobs[i], out);
  848. ncnn::Layer* layer_int8 = ncnn::create_layer(layer->typeindex);
  849. ncnn::ParamDict pd;
  850. get_layer_param(layer, pd);
  851. pd.set(8, 1); //int8_scale_term
  852. layer_int8->load_param(pd);
  853. std::vector<float> sims(search_steps);
  854. for (int k = 0; k < search_steps; k++)
  855. {
  856. ncnn::Mat new_weight_scale = weight_scale.clone();
  857. new_weight_scale[j] = scale_lower + k * scale_step;
  858. std::vector<ncnn::Mat> weights;
  859. get_layer_weights(layer, weights);
  860. weights.push_back(new_weight_scale);
  861. weights.push_back(bottom_blob_scale);
  862. layer_int8->load_model(ncnn::ModelBinFromMatArray(weights.data()));
  863. ncnn::Option opt_int8;
  864. opt_int8.use_packing_layout = false;
  865. layer_int8->create_pipeline(opt_int8);
  866. ncnn::Mat out_int8;
  867. layer_int8->forward(in, out_int8, opt_int8);
  868. layer_int8->destroy_pipeline(opt_int8);
  869. sims[k] = cosine_similarity(out, out_int8);
  870. }
  871. delete layer_int8;
  872. #pragma omp critical
  873. {
  874. for (int k = 0; k < search_steps; k++)
  875. {
  876. avgsims[k] += sims[k];
  877. }
  878. }
  879. }
  880. double max_avgsim = 0.0;
  881. float new_scale = scale;
  882. // find the scale with min cosine distance
  883. for (int k = 0; k < search_steps; k++)
  884. {
  885. if (max_avgsim < avgsims[k])
  886. {
  887. max_avgsim = avgsims[k];
  888. new_scale = scale_lower + k * scale_step;
  889. }
  890. }
  891. fprintf(stderr, "%s w %d = %f -> %f\n", layer->name.c_str(), j, scale, new_scale);
  892. weight_scale[j] = new_scale;
  893. }
  894. // search bottom blob scale
  895. for (int j = 0; j < bottom_blob_scale.w; j++)
  896. {
  897. const float scale = bottom_blob_scale[j];
  898. const float scale_lower = scale * scale_range_lower;
  899. const float scale_upper = scale * scale_range_upper;
  900. const float scale_step = (scale_upper - scale_lower) / search_steps;
  901. std::vector<double> avgsims(search_steps, 0.0);
  902. #pragma omp parallel for num_threads(quantize_num_threads)
  903. for (int ii = 0; ii < image_count; ii++)
  904. {
  905. ncnn::Extractor ex = create_extractor();
  906. for (int jj = 0; jj < input_blob_count; jj++)
  907. {
  908. const std::string& imagepath = listspaths[jj][ii];
  909. const std::vector<int>& shape = shapes[jj];
  910. const int type_to_pixel = type_to_pixels[jj];
  911. const std::vector<float>& mean_vals = means[jj];
  912. const std::vector<float>& norm_vals = norms[jj];
  913. int pixel_convert_type = ncnn::Mat::PIXEL_BGR;
  914. if (type_to_pixel != pixel_convert_type)
  915. {
  916. pixel_convert_type = pixel_convert_type | (type_to_pixel << ncnn::Mat::PIXEL_CONVERT_SHIFT);
  917. }
  918. const int target_w = shape[0];
  919. const int target_h = shape[1];
  920. cv::Mat bgr = cv::imread(imagepath, 1);
  921. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, pixel_convert_type, bgr.cols, bgr.rows, target_w, target_h);
  922. in.substract_mean_normalize(mean_vals.data(), norm_vals.data());
  923. ex.input(input_blobs[jj], in);
  924. }
  925. ncnn::Mat in;
  926. ex.extract(conv_bottom_blobs[i], in);
  927. ncnn::Mat out;
  928. ex.extract(conv_top_blobs[i], out);
  929. ncnn::Layer* layer_int8 = ncnn::create_layer(layer->typeindex);
  930. ncnn::ParamDict pd;
  931. get_layer_param(layer, pd);
  932. pd.set(8, 1); //int8_scale_term
  933. layer_int8->load_param(pd);
  934. std::vector<float> sims(search_steps);
  935. for (int k = 0; k < search_steps; k++)
  936. {
  937. ncnn::Mat new_bottom_blob_scale = bottom_blob_scale.clone();
  938. new_bottom_blob_scale[j] = scale_lower + k * scale_step;
  939. std::vector<ncnn::Mat> weights;
  940. get_layer_weights(layer, weights);
  941. weights.push_back(weight_scale);
  942. weights.push_back(new_bottom_blob_scale);
  943. layer_int8->load_model(ncnn::ModelBinFromMatArray(weights.data()));
  944. ncnn::Option opt_int8;
  945. opt_int8.use_packing_layout = false;
  946. layer_int8->create_pipeline(opt_int8);
  947. ncnn::Mat out_int8;
  948. layer_int8->forward(in, out_int8, opt_int8);
  949. layer_int8->destroy_pipeline(opt_int8);
  950. sims[k] = cosine_similarity(out, out_int8);
  951. }
  952. delete layer_int8;
  953. #pragma omp critical
  954. {
  955. for (int k = 0; k < search_steps; k++)
  956. {
  957. avgsims[k] += sims[k];
  958. }
  959. }
  960. }
  961. double max_avgsim = 0.0;
  962. float new_scale = scale;
  963. // find the scale with min cosine distance
  964. for (int k = 0; k < search_steps; k++)
  965. {
  966. if (max_avgsim < avgsims[k])
  967. {
  968. max_avgsim = avgsims[k];
  969. new_scale = scale_lower + k * scale_step;
  970. }
  971. }
  972. fprintf(stderr, "%s b %d = %f -> %f\n", layer->name.c_str(), j, scale, new_scale);
  973. bottom_blob_scale[j] = new_scale;
  974. }
  975. // update quant info
  976. QuantBlobStat& stat = quant_blob_stats[i];
  977. stat.threshold = 127 / bottom_blob_scale[0];
  978. }
  979. return 0;
  980. }
  981. static std::vector<std::vector<std::string> > parse_comma_path_list(char* s)
  982. {
  983. std::vector<std::vector<std::string> > aps;
  984. char* pch = strtok(s, ",");
  985. while (pch != NULL)
  986. {
  987. FILE* fp = fopen(pch, "rb");
  988. if (!fp)
  989. {
  990. fprintf(stderr, "fopen %s failed\n", pch);
  991. break;
  992. }
  993. std::vector<std::string> paths;
  994. // one filepath per line
  995. char line[1024];
  996. while (!feof(fp))
  997. {
  998. char* ss = fgets(line, 1024, fp);
  999. if (!ss)
  1000. break;
  1001. char filepath[256];
  1002. int nscan = sscanf(line, "%255s", filepath);
  1003. if (nscan != 1)
  1004. continue;
  1005. paths.push_back(std::string(filepath));
  1006. }
  1007. fclose(fp);
  1008. aps.push_back(paths);
  1009. pch = strtok(NULL, ",");
  1010. }
  1011. return aps;
  1012. }
  1013. static float vstr_to_float(const char vstr[16])
  1014. {
  1015. double v = 0.0;
  1016. const char* p = vstr;
  1017. // sign
  1018. bool sign = *p != '-';
  1019. if (*p == '+' || *p == '-')
  1020. {
  1021. p++;
  1022. }
  1023. // digits before decimal point or exponent
  1024. unsigned int v1 = 0;
  1025. while (isdigit(*p))
  1026. {
  1027. v1 = v1 * 10 + (*p - '0');
  1028. p++;
  1029. }
  1030. v = (double)v1;
  1031. // digits after decimal point
  1032. if (*p == '.')
  1033. {
  1034. p++;
  1035. unsigned int pow10 = 1;
  1036. unsigned int v2 = 0;
  1037. while (isdigit(*p))
  1038. {
  1039. v2 = v2 * 10 + (*p - '0');
  1040. pow10 *= 10;
  1041. p++;
  1042. }
  1043. v += v2 / (double)pow10;
  1044. }
  1045. // exponent
  1046. if (*p == 'e' || *p == 'E')
  1047. {
  1048. p++;
  1049. // sign of exponent
  1050. bool fact = *p != '-';
  1051. if (*p == '+' || *p == '-')
  1052. {
  1053. p++;
  1054. }
  1055. // digits of exponent
  1056. unsigned int expon = 0;
  1057. while (isdigit(*p))
  1058. {
  1059. expon = expon * 10 + (*p - '0');
  1060. p++;
  1061. }
  1062. double scale = 1.0;
  1063. while (expon >= 8)
  1064. {
  1065. scale *= 1e8;
  1066. expon -= 8;
  1067. }
  1068. while (expon > 0)
  1069. {
  1070. scale *= 10.0;
  1071. expon -= 1;
  1072. }
  1073. v = fact ? v * scale : v / scale;
  1074. }
  1075. // fprintf(stderr, "v = %f\n", v);
  1076. return sign ? (float)v : (float)-v;
  1077. }
  1078. static std::vector<std::vector<float> > parse_comma_float_array_list(char* s)
  1079. {
  1080. std::vector<std::vector<float> > aaf;
  1081. char* pch = strtok(s, "[]");
  1082. while (pch != NULL)
  1083. {
  1084. // parse a,b,c
  1085. char vstr[16];
  1086. int nconsumed = 0;
  1087. int nscan = sscanf(pch, "%15[^,]%n", vstr, &nconsumed);
  1088. if (nscan == 1)
  1089. {
  1090. // ok we get array
  1091. pch += nconsumed;
  1092. std::vector<float> af;
  1093. float v = vstr_to_float(vstr);
  1094. af.push_back(v);
  1095. nscan = sscanf(pch, ",%15[^,]%n", vstr, &nconsumed);
  1096. while (nscan == 1)
  1097. {
  1098. pch += nconsumed;
  1099. float v = vstr_to_float(vstr);
  1100. af.push_back(v);
  1101. nscan = sscanf(pch, ",%15[^,]%n", vstr, &nconsumed);
  1102. }
  1103. // array end
  1104. aaf.push_back(af);
  1105. }
  1106. pch = strtok(NULL, "[]");
  1107. }
  1108. return aaf;
  1109. }
  1110. static std::vector<std::vector<int> > parse_comma_int_array_list(char* s)
  1111. {
  1112. std::vector<std::vector<int> > aai;
  1113. char* pch = strtok(s, "[]");
  1114. while (pch != NULL)
  1115. {
  1116. // parse a,b,c
  1117. int v;
  1118. int nconsumed = 0;
  1119. int nscan = sscanf(pch, "%d%n", &v, &nconsumed);
  1120. if (nscan == 1)
  1121. {
  1122. // ok we get array
  1123. pch += nconsumed;
  1124. std::vector<int> ai;
  1125. ai.push_back(v);
  1126. nscan = sscanf(pch, ",%d%n", &v, &nconsumed);
  1127. while (nscan == 1)
  1128. {
  1129. pch += nconsumed;
  1130. ai.push_back(v);
  1131. nscan = sscanf(pch, ",%d%n", &v, &nconsumed);
  1132. }
  1133. // array end
  1134. aai.push_back(ai);
  1135. }
  1136. pch = strtok(NULL, "[]");
  1137. }
  1138. return aai;
  1139. }
  1140. static std::vector<int> parse_comma_pixel_type_list(char* s)
  1141. {
  1142. std::vector<int> aps;
  1143. char* pch = strtok(s, ",");
  1144. while (pch != NULL)
  1145. {
  1146. // RAW/RGB/BGR/GRAY/RGBA/BGRA
  1147. if (strcmp(pch, "RAW") == 0)
  1148. aps.push_back(-233);
  1149. if (strcmp(pch, "RGB") == 0)
  1150. aps.push_back(ncnn::Mat::PIXEL_RGB);
  1151. if (strcmp(pch, "BGR") == 0)
  1152. aps.push_back(ncnn::Mat::PIXEL_BGR);
  1153. if (strcmp(pch, "GRAY") == 0)
  1154. aps.push_back(ncnn::Mat::PIXEL_GRAY);
  1155. if (strcmp(pch, "RGBA") == 0)
  1156. aps.push_back(ncnn::Mat::PIXEL_RGBA);
  1157. if (strcmp(pch, "BGRA") == 0)
  1158. aps.push_back(ncnn::Mat::PIXEL_BGRA);
  1159. pch = strtok(NULL, ",");
  1160. }
  1161. return aps;
  1162. }
  1163. static void show_usage()
  1164. {
  1165. fprintf(stderr, "Usage: ncnn2table [ncnnparam] [ncnnbin] [list,...] [ncnntable] [(key=value)...]\n");
  1166. fprintf(stderr, " mean=[104.0,117.0,123.0],...\n");
  1167. fprintf(stderr, " norm=[1.0,1.0,1.0],...\n");
  1168. fprintf(stderr, " shape=[224,224,3],...\n");
  1169. fprintf(stderr, " pixel=RAW/RGB/BGR/GRAY/RGBA/BGRA,...\n");
  1170. fprintf(stderr, " thread=8\n");
  1171. fprintf(stderr, " method=kl/aciq/eq\n");
  1172. 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");
  1173. }
  1174. int main(int argc, char** argv)
  1175. {
  1176. if (argc < 5)
  1177. {
  1178. show_usage();
  1179. return -1;
  1180. }
  1181. for (int i = 1; i < argc; i++)
  1182. {
  1183. if (argv[i][0] == '-')
  1184. {
  1185. show_usage();
  1186. return -1;
  1187. }
  1188. }
  1189. const char* inparam = argv[1];
  1190. const char* inbin = argv[2];
  1191. char* lists = argv[3];
  1192. const char* outtable = argv[4];
  1193. ncnn::Option opt;
  1194. opt.num_threads = 1;
  1195. opt.use_fp16_packed = false;
  1196. opt.use_fp16_storage = false;
  1197. opt.use_fp16_arithmetic = false;
  1198. QuantNet net;
  1199. net.opt = opt;
  1200. net.load_param(inparam);
  1201. net.load_model(inbin);
  1202. net.init();
  1203. // load lists
  1204. net.listspaths = parse_comma_path_list(lists);
  1205. std::string method = "kl";
  1206. for (int i = 5; i < argc; i++)
  1207. {
  1208. // key=value
  1209. char* kv = argv[i];
  1210. char* eqs = strchr(kv, '=');
  1211. if (eqs == NULL)
  1212. {
  1213. fprintf(stderr, "unrecognized arg %s\n", kv);
  1214. continue;
  1215. }
  1216. // split k v
  1217. eqs[0] = '\0';
  1218. const char* key = kv;
  1219. char* value = eqs + 1;
  1220. fprintf(stderr, "%s = %s\n", key, value);
  1221. // load mean norm shape
  1222. if (memcmp(key, "mean", 4) == 0)
  1223. net.means = parse_comma_float_array_list(value);
  1224. if (memcmp(key, "norm", 4) == 0)
  1225. net.norms = parse_comma_float_array_list(value);
  1226. if (memcmp(key, "shape", 5) == 0)
  1227. net.shapes = parse_comma_int_array_list(value);
  1228. if (memcmp(key, "pixel", 5) == 0)
  1229. net.type_to_pixels = parse_comma_pixel_type_list(value);
  1230. if (memcmp(key, "thread", 6) == 0)
  1231. net.quantize_num_threads = atoi(value);
  1232. if (memcmp(key, "method", 6) == 0)
  1233. method = std::string(value);
  1234. }
  1235. // sanity check
  1236. const size_t input_blob_count = net.input_blobs.size();
  1237. if (net.listspaths.size() != input_blob_count)
  1238. {
  1239. fprintf(stderr, "expect %d lists, but got %d\n", (int)input_blob_count, (int)net.listspaths.size());
  1240. return -1;
  1241. }
  1242. if (net.means.size() != input_blob_count)
  1243. {
  1244. fprintf(stderr, "expect %d means, but got %d\n", (int)input_blob_count, (int)net.means.size());
  1245. return -1;
  1246. }
  1247. if (net.norms.size() != input_blob_count)
  1248. {
  1249. fprintf(stderr, "expect %d norms, but got %d\n", (int)input_blob_count, (int)net.norms.size());
  1250. return -1;
  1251. }
  1252. if (net.shapes.size() != input_blob_count)
  1253. {
  1254. fprintf(stderr, "expect %d shapes, but got %d\n", (int)input_blob_count, (int)net.shapes.size());
  1255. return -1;
  1256. }
  1257. if (net.type_to_pixels.size() != input_blob_count)
  1258. {
  1259. fprintf(stderr, "expect %d pixels, but got %d\n", (int)input_blob_count, (int)net.type_to_pixels.size());
  1260. return -1;
  1261. }
  1262. if (net.quantize_num_threads < 0)
  1263. {
  1264. fprintf(stderr, "malformed thread %d\n", net.quantize_num_threads);
  1265. return -1;
  1266. }
  1267. if (method == "kl")
  1268. {
  1269. net.quantize_KL();
  1270. }
  1271. else if (method == "aciq")
  1272. {
  1273. net.quantize_ACIQ();
  1274. }
  1275. else if (method == "eq")
  1276. {
  1277. net.quantize_EQ();
  1278. }
  1279. else
  1280. {
  1281. fprintf(stderr, "not implemented yet !\n");
  1282. fprintf(stderr, "unknown method %s, expect kl / aciq / eq\n", method.c_str());
  1283. return -1;
  1284. }
  1285. net.print_quant_info();
  1286. net.save_table(outtable);
  1287. return 0;
  1288. }