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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  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. }
  976. return 0;
  977. }
  978. static std::vector<std::vector<std::string> > parse_comma_path_list(char* s)
  979. {
  980. std::vector<std::vector<std::string> > aps;
  981. char* pch = strtok(s, ",");
  982. while (pch != NULL)
  983. {
  984. FILE* fp = fopen(pch, "rb");
  985. if (!fp)
  986. {
  987. fprintf(stderr, "fopen %s failed\n", pch);
  988. break;
  989. }
  990. std::vector<std::string> paths;
  991. // one filepath per line
  992. char line[1024];
  993. while (!feof(fp))
  994. {
  995. char* ss = fgets(line, 1024, fp);
  996. if (!ss)
  997. break;
  998. char filepath[256];
  999. int nscan = sscanf(line, "%255s", filepath);
  1000. if (nscan != 1)
  1001. continue;
  1002. paths.push_back(std::string(filepath));
  1003. }
  1004. fclose(fp);
  1005. aps.push_back(paths);
  1006. pch = strtok(NULL, ",");
  1007. }
  1008. return aps;
  1009. }
  1010. static float vstr_to_float(const char vstr[16])
  1011. {
  1012. double v = 0.0;
  1013. const char* p = vstr;
  1014. // sign
  1015. bool sign = *p != '-';
  1016. if (*p == '+' || *p == '-')
  1017. {
  1018. p++;
  1019. }
  1020. // digits before decimal point or exponent
  1021. unsigned int v1 = 0;
  1022. while (isdigit(*p))
  1023. {
  1024. v1 = v1 * 10 + (*p - '0');
  1025. p++;
  1026. }
  1027. v = (double)v1;
  1028. // digits after decimal point
  1029. if (*p == '.')
  1030. {
  1031. p++;
  1032. unsigned int pow10 = 1;
  1033. unsigned int v2 = 0;
  1034. while (isdigit(*p))
  1035. {
  1036. v2 = v2 * 10 + (*p - '0');
  1037. pow10 *= 10;
  1038. p++;
  1039. }
  1040. v += v2 / (double)pow10;
  1041. }
  1042. // exponent
  1043. if (*p == 'e' || *p == 'E')
  1044. {
  1045. p++;
  1046. // sign of exponent
  1047. bool fact = *p != '-';
  1048. if (*p == '+' || *p == '-')
  1049. {
  1050. p++;
  1051. }
  1052. // digits of exponent
  1053. unsigned int expon = 0;
  1054. while (isdigit(*p))
  1055. {
  1056. expon = expon * 10 + (*p - '0');
  1057. p++;
  1058. }
  1059. double scale = 1.0;
  1060. while (expon >= 8)
  1061. {
  1062. scale *= 1e8;
  1063. expon -= 8;
  1064. }
  1065. while (expon > 0)
  1066. {
  1067. scale *= 10.0;
  1068. expon -= 1;
  1069. }
  1070. v = fact ? v * scale : v / scale;
  1071. }
  1072. // fprintf(stderr, "v = %f\n", v);
  1073. return sign ? (float)v : (float)-v;
  1074. }
  1075. static std::vector<std::vector<float> > parse_comma_float_array_list(char* s)
  1076. {
  1077. std::vector<std::vector<float> > aaf;
  1078. char* pch = strtok(s, "[]");
  1079. while (pch != NULL)
  1080. {
  1081. // parse a,b,c
  1082. char vstr[16];
  1083. int nconsumed = 0;
  1084. int nscan = sscanf(pch, "%15[^,]%n", vstr, &nconsumed);
  1085. if (nscan == 1)
  1086. {
  1087. // ok we get array
  1088. pch += nconsumed;
  1089. std::vector<float> af;
  1090. float v = vstr_to_float(vstr);
  1091. af.push_back(v);
  1092. nscan = sscanf(pch, ",%15[^,]%n", vstr, &nconsumed);
  1093. while (nscan == 1)
  1094. {
  1095. pch += nconsumed;
  1096. float v = vstr_to_float(vstr);
  1097. af.push_back(v);
  1098. nscan = sscanf(pch, ",%15[^,]%n", vstr, &nconsumed);
  1099. }
  1100. // array end
  1101. aaf.push_back(af);
  1102. }
  1103. pch = strtok(NULL, "[]");
  1104. }
  1105. return aaf;
  1106. }
  1107. static std::vector<std::vector<int> > parse_comma_int_array_list(char* s)
  1108. {
  1109. std::vector<std::vector<int> > aai;
  1110. char* pch = strtok(s, "[]");
  1111. while (pch != NULL)
  1112. {
  1113. // parse a,b,c
  1114. int v;
  1115. int nconsumed = 0;
  1116. int nscan = sscanf(pch, "%d%n", &v, &nconsumed);
  1117. if (nscan == 1)
  1118. {
  1119. // ok we get array
  1120. pch += nconsumed;
  1121. std::vector<int> ai;
  1122. ai.push_back(v);
  1123. nscan = sscanf(pch, ",%d%n", &v, &nconsumed);
  1124. while (nscan == 1)
  1125. {
  1126. pch += nconsumed;
  1127. ai.push_back(v);
  1128. nscan = sscanf(pch, ",%d%n", &v, &nconsumed);
  1129. }
  1130. // array end
  1131. aai.push_back(ai);
  1132. }
  1133. pch = strtok(NULL, "[]");
  1134. }
  1135. return aai;
  1136. }
  1137. static std::vector<int> parse_comma_pixel_type_list(char* s)
  1138. {
  1139. std::vector<int> aps;
  1140. char* pch = strtok(s, ",");
  1141. while (pch != NULL)
  1142. {
  1143. // RAW/RGB/BGR/GRAY/RGBA/BGRA
  1144. if (strcmp(pch, "RAW") == 0)
  1145. aps.push_back(-233);
  1146. if (strcmp(pch, "RGB") == 0)
  1147. aps.push_back(ncnn::Mat::PIXEL_RGB);
  1148. if (strcmp(pch, "BGR") == 0)
  1149. aps.push_back(ncnn::Mat::PIXEL_BGR);
  1150. if (strcmp(pch, "GRAY") == 0)
  1151. aps.push_back(ncnn::Mat::PIXEL_GRAY);
  1152. if (strcmp(pch, "RGBA") == 0)
  1153. aps.push_back(ncnn::Mat::PIXEL_RGBA);
  1154. if (strcmp(pch, "BGRA") == 0)
  1155. aps.push_back(ncnn::Mat::PIXEL_BGRA);
  1156. pch = strtok(NULL, ",");
  1157. }
  1158. return aps;
  1159. }
  1160. static void show_usage()
  1161. {
  1162. fprintf(stderr, "Usage: ncnn2table [ncnnparam] [ncnnbin] [list,...] [ncnntable] [(key=value)...]\n");
  1163. fprintf(stderr, " mean=[104.0,117.0,123.0],...\n");
  1164. fprintf(stderr, " norm=[1.0,1.0,1.0],...\n");
  1165. fprintf(stderr, " shape=[224,224,3],...\n");
  1166. fprintf(stderr, " pixel=RAW/RGB/BGR/GRAY/RGBA/BGRA,...\n");
  1167. fprintf(stderr, " thread=8\n");
  1168. fprintf(stderr, " method=kl/aciq/eq\n");
  1169. 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");
  1170. }
  1171. int main(int argc, char** argv)
  1172. {
  1173. if (argc < 5)
  1174. {
  1175. show_usage();
  1176. return -1;
  1177. }
  1178. for (int i = 1; i < argc; i++)
  1179. {
  1180. if (argv[i][0] == '-')
  1181. {
  1182. show_usage();
  1183. return -1;
  1184. }
  1185. }
  1186. const char* inparam = argv[1];
  1187. const char* inbin = argv[2];
  1188. char* lists = argv[3];
  1189. const char* outtable = argv[4];
  1190. ncnn::Option opt;
  1191. opt.num_threads = 1;
  1192. opt.use_fp16_packed = false;
  1193. opt.use_fp16_storage = false;
  1194. opt.use_fp16_arithmetic = false;
  1195. QuantNet net;
  1196. net.opt = opt;
  1197. net.load_param(inparam);
  1198. net.load_model(inbin);
  1199. net.init();
  1200. // load lists
  1201. net.listspaths = parse_comma_path_list(lists);
  1202. std::string method = "kl";
  1203. for (int i = 5; i < argc; i++)
  1204. {
  1205. // key=value
  1206. char* kv = argv[i];
  1207. char* eqs = strchr(kv, '=');
  1208. if (eqs == NULL)
  1209. {
  1210. fprintf(stderr, "unrecognized arg %s\n", kv);
  1211. continue;
  1212. }
  1213. // split k v
  1214. eqs[0] = '\0';
  1215. const char* key = kv;
  1216. char* value = eqs + 1;
  1217. fprintf(stderr, "%s = %s\n", key, value);
  1218. // load mean norm shape
  1219. if (memcmp(key, "mean", 4) == 0)
  1220. net.means = parse_comma_float_array_list(value);
  1221. if (memcmp(key, "norm", 4) == 0)
  1222. net.norms = parse_comma_float_array_list(value);
  1223. if (memcmp(key, "shape", 5) == 0)
  1224. net.shapes = parse_comma_int_array_list(value);
  1225. if (memcmp(key, "pixel", 5) == 0)
  1226. net.type_to_pixels = parse_comma_pixel_type_list(value);
  1227. if (memcmp(key, "thread", 6) == 0)
  1228. net.quantize_num_threads = atoi(value);
  1229. if (memcmp(key, "method", 6) == 0)
  1230. method = std::string(value);
  1231. }
  1232. // sanity check
  1233. const size_t input_blob_count = net.input_blobs.size();
  1234. if (net.listspaths.size() != input_blob_count)
  1235. {
  1236. fprintf(stderr, "expect %d lists, but got %d\n", (int)input_blob_count, (int)net.listspaths.size());
  1237. return -1;
  1238. }
  1239. if (net.means.size() != input_blob_count)
  1240. {
  1241. fprintf(stderr, "expect %d means, but got %d\n", (int)input_blob_count, (int)net.means.size());
  1242. return -1;
  1243. }
  1244. if (net.norms.size() != input_blob_count)
  1245. {
  1246. fprintf(stderr, "expect %d norms, but got %d\n", (int)input_blob_count, (int)net.norms.size());
  1247. return -1;
  1248. }
  1249. if (net.shapes.size() != input_blob_count)
  1250. {
  1251. fprintf(stderr, "expect %d shapes, but got %d\n", (int)input_blob_count, (int)net.shapes.size());
  1252. return -1;
  1253. }
  1254. if (net.type_to_pixels.size() != input_blob_count)
  1255. {
  1256. fprintf(stderr, "expect %d pixels, but got %d\n", (int)input_blob_count, (int)net.type_to_pixels.size());
  1257. return -1;
  1258. }
  1259. if (net.quantize_num_threads < 0)
  1260. {
  1261. fprintf(stderr, "malformed thread %d\n", net.quantize_num_threads);
  1262. return -1;
  1263. }
  1264. if (method == "kl")
  1265. {
  1266. net.quantize_KL();
  1267. }
  1268. else if (method == "aciq")
  1269. {
  1270. net.quantize_ACIQ();
  1271. }
  1272. else if (method == "eq")
  1273. {
  1274. net.quantize_EQ();
  1275. }
  1276. else
  1277. {
  1278. fprintf(stderr, "not implemented yet !\n");
  1279. fprintf(stderr, "unknown method %s, expect kl / aciq / eq\n", method.c_str());
  1280. return -1;
  1281. }
  1282. net.print_quant_info();
  1283. net.save_table(outtable);
  1284. return 0;
  1285. }