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.

ncnn2int8.cpp 19 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. // BUG1989 is pleased to support the open source community by supporting ncnn available.
  2. //
  3. // Copyright (C) 2019 BUG1989. All rights reserved.
  4. //
  5. // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // https://opensource.org/licenses/BSD-3-Clause
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #ifdef _MSC_VER
  15. #define _CRT_SECURE_NO_DEPRECATE
  16. #endif
  17. #include <cstdio>
  18. #include <cstring>
  19. #include <map>
  20. #include <set>
  21. #include <vector>
  22. // ncnn public header
  23. #include "datareader.h"
  24. #include "layer.h"
  25. #include "layer_type.h"
  26. #include "net.h"
  27. // ncnn private header
  28. #include "../modelwriter.h"
  29. class DataReaderFromEmpty : public ncnn::DataReader
  30. {
  31. public:
  32. virtual int scan(const char* format, void* p) const
  33. {
  34. return 0;
  35. }
  36. virtual size_t read(void* buf, size_t size) const
  37. {
  38. memset(buf, 0, size);
  39. return size;
  40. }
  41. };
  42. static bool read_int8scale_table(const char* filepath, std::map<std::string, ncnn::Mat>& blob_int8scale_table, std::map<std::string, ncnn::Mat>& weight_int8scale_table)
  43. {
  44. blob_int8scale_table.clear();
  45. weight_int8scale_table.clear();
  46. FILE* fp = fopen(filepath, "rb");
  47. if (!fp)
  48. {
  49. fprintf(stderr, "Open %s failed.\n", filepath);
  50. return false;
  51. }
  52. std::string key_str;
  53. std::vector<float> scales;
  54. std::vector<char> line(10240000);
  55. char* pch = NULL;
  56. size_t len = 0;
  57. while (!feof(fp))
  58. {
  59. char* s = fgets(line.data(), (int)line.size(), fp);
  60. if (!s)
  61. break;
  62. float scale = 1.f;
  63. char key[256];
  64. line[strcspn(line.data(), "\r\n")] = 0;
  65. pch = strtok(line.data(), " ");
  66. if (pch == NULL) break;
  67. bool is_key = true;
  68. while (pch != NULL)
  69. {
  70. if (is_key)
  71. {
  72. sscanf(pch, "%255s", key);
  73. key_str = key;
  74. is_key = false;
  75. }
  76. else
  77. {
  78. sscanf(pch, "%f", &scale);
  79. scales.push_back(scale);
  80. }
  81. pch = strtok(NULL, " ");
  82. }
  83. // XYZ_param_N pattern
  84. if (strstr(key_str.c_str(), "_param_"))
  85. {
  86. weight_int8scale_table[key_str] = ncnn::Mat((int)scales.size(), (void*)scales.data()).clone();
  87. }
  88. else
  89. {
  90. blob_int8scale_table[key_str] = ncnn::Mat((int)scales.size(), (void*)scales.data()).clone();
  91. }
  92. key_str.clear();
  93. scales.clear();
  94. }
  95. fclose(fp);
  96. return true;
  97. }
  98. class NetQuantize : public ModelWriter
  99. {
  100. public:
  101. NetQuantize();
  102. std::map<std::string, ncnn::Mat> blob_int8scale_table;
  103. std::map<std::string, ncnn::Mat> weight_int8scale_table;
  104. public:
  105. int quantize_convolution();
  106. int quantize_convolutiondepthwise();
  107. int quantize_innerproduct();
  108. int fuse_requantize();
  109. };
  110. NetQuantize::NetQuantize()
  111. : ModelWriter()
  112. {
  113. }
  114. int NetQuantize::quantize_convolution()
  115. {
  116. const int layer_count = static_cast<int>(layers.size());
  117. for (int i = 0; i < layer_count; i++)
  118. {
  119. // find convolution layer
  120. if (layers[i]->type != "Convolution")
  121. continue;
  122. // find convolution layer
  123. std::map<std::string, ncnn::Mat>::iterator iter_data = blob_int8scale_table.find(layers[i]->name);
  124. if (iter_data == blob_int8scale_table.end())
  125. continue;
  126. char key[256];
  127. sprintf(key, "%s_param_0", layers[i]->name.c_str());
  128. std::map<std::string, ncnn::Mat>::iterator iter = weight_int8scale_table.find(key);
  129. if (iter == weight_int8scale_table.end())
  130. {
  131. fprintf(stderr, "this layer need to be quantized, but no scale param!\n");
  132. return -1;
  133. }
  134. // Convolution - quantize weight from fp32 to int8
  135. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  136. ncnn::Mat bottom_blob_int8_scales = iter_data->second;
  137. ncnn::Mat weight_data_int8_scales = iter->second;
  138. fprintf(stderr, "quantize_convolution %s\n", convolution->name.c_str());
  139. {
  140. const int maxk = convolution->kernel_w * convolution->kernel_h;
  141. const int num_input = convolution->weight_data_size / convolution->num_output / maxk;
  142. ncnn::Mat weight_data_r2 = convolution->weight_data.reshape(maxk, num_input, convolution->num_output);
  143. ncnn::Mat weight_data_int8;
  144. ncnn::Option opt_q = opt;
  145. opt_q.blob_allocator = convolution->weight_data.allocator;
  146. opt_q.use_packing_layout = false;
  147. ncnn::quantize_to_int8(weight_data_r2, weight_data_int8, weight_data_int8_scales, opt_q);
  148. if (weight_data_int8.empty())
  149. return -100;
  150. convolution->weight_data = weight_data_int8.reshape(convolution->weight_data_size);
  151. }
  152. convolution->int8_scale_term = 2;
  153. convolution->weight_data_int8_scales = weight_data_int8_scales;
  154. convolution->bottom_blob_int8_scales = bottom_blob_int8_scales;
  155. }
  156. return 0;
  157. }
  158. int NetQuantize::quantize_convolutiondepthwise()
  159. {
  160. const int layer_count = static_cast<int>(layers.size());
  161. for (int i = 0; i < layer_count; i++)
  162. {
  163. // find convolution layer
  164. if (layers[i]->type != "ConvolutionDepthWise")
  165. continue;
  166. // find convolutiondepthwise layer
  167. std::map<std::string, ncnn::Mat>::iterator iter_data = blob_int8scale_table.find(layers[i]->name);
  168. if (iter_data == blob_int8scale_table.end())
  169. continue;
  170. char key[256];
  171. sprintf(key, "%s_param_0", layers[i]->name.c_str());
  172. std::map<std::string, ncnn::Mat>::iterator iter = weight_int8scale_table.find(key);
  173. if (iter == weight_int8scale_table.end())
  174. {
  175. fprintf(stderr, "this layer need to be quantized, but no scale param!\n");
  176. return -1;
  177. }
  178. // Convolution - quantize weight from fp32 to int8
  179. ncnn::ConvolutionDepthWise* convdw = (ncnn::ConvolutionDepthWise*)layers[i];
  180. ncnn::Mat bottom_blob_int8_scales = iter_data->second;
  181. ncnn::Mat weight_data_int8_scales = iter->second;
  182. fprintf(stderr, "quantize_convolutiondepthwise %s\n", convdw->name.c_str());
  183. {
  184. ncnn::Mat int8_weight_data(convdw->weight_data_size, (size_t)1u);
  185. if (int8_weight_data.empty())
  186. return -100;
  187. const int weight_data_size_g = convdw->weight_data_size / convdw->group;
  188. for (int g = 0; g < convdw->group; g++)
  189. {
  190. ncnn::Option opt_q = opt;
  191. opt_q.blob_allocator = int8_weight_data.allocator;
  192. opt_q.use_packing_layout = false;
  193. const ncnn::Mat weight_data_g = convdw->weight_data.range(weight_data_size_g * g, weight_data_size_g);
  194. ncnn::Mat int8_weight_data_g = int8_weight_data.range(weight_data_size_g * g, weight_data_size_g);
  195. const ncnn::Mat weight_data_int8_scales_g = weight_data_int8_scales.range(g, 1);
  196. ncnn::quantize_to_int8(weight_data_g, int8_weight_data_g, weight_data_int8_scales_g, opt_q);
  197. }
  198. convdw->weight_data = int8_weight_data;
  199. }
  200. convdw->int8_scale_term = 1;
  201. convdw->weight_data_int8_scales = weight_data_int8_scales;
  202. convdw->bottom_blob_int8_scales = bottom_blob_int8_scales;
  203. }
  204. return 0;
  205. }
  206. int NetQuantize::quantize_innerproduct()
  207. {
  208. const int layer_count = static_cast<int>(layers.size());
  209. for (int i = 0; i < layer_count; i++)
  210. {
  211. // find convolution layer
  212. if (layers[i]->type != "InnerProduct")
  213. continue;
  214. // find InnerProduct layer
  215. std::map<std::string, ncnn::Mat>::iterator iter_data = blob_int8scale_table.find(layers[i]->name);
  216. if (iter_data == blob_int8scale_table.end())
  217. continue;
  218. char key[256];
  219. sprintf(key, "%s_param_0", layers[i]->name.c_str());
  220. std::map<std::string, ncnn::Mat>::iterator iter = weight_int8scale_table.find(key);
  221. if (iter == weight_int8scale_table.end())
  222. {
  223. fprintf(stderr, "this layer need to be quantized, but no scale param!\n");
  224. return -1;
  225. }
  226. // InnerProduct - quantize weight from fp32 to int8
  227. ncnn::InnerProduct* fc = (ncnn::InnerProduct*)layers[i];
  228. ncnn::Mat bottom_blob_int8_scales = iter_data->second;
  229. ncnn::Mat weight_data_int8_scales = iter->second;
  230. fprintf(stderr, "quantize_innerproduct %s\n", fc->name.c_str());
  231. {
  232. const int num_input = fc->weight_data_size / fc->num_output;
  233. ncnn::Mat weight_data_r2 = fc->weight_data.reshape(num_input, fc->num_output);
  234. ncnn::Mat weight_data_int8;
  235. ncnn::Option opt_q = opt;
  236. opt_q.use_packing_layout = false;
  237. ncnn::quantize_to_int8(weight_data_r2, weight_data_int8, weight_data_int8_scales, opt_q);
  238. if (weight_data_int8.empty())
  239. return -100;
  240. fc->weight_data = weight_data_int8.reshape(fc->weight_data_size);
  241. }
  242. fc->int8_scale_term = 2;
  243. fc->weight_data_int8_scales = weight_data_int8_scales;
  244. fc->bottom_blob_int8_scales = bottom_blob_int8_scales;
  245. }
  246. return 0;
  247. }
  248. int NetQuantize::fuse_requantize()
  249. {
  250. const size_t layer_count = layers.size();
  251. for (size_t i = 0; i < layer_count; i++)
  252. {
  253. if (layers[i]->type != "Convolution" && layers[i]->type != "ConvolutionDepthWise")
  254. continue;
  255. // Convolution/ConvolutionDepthWise - Convolution/ConvolutionDepthWise
  256. int top_blob_index = layers[i]->tops[0];
  257. size_t j = i + 1;
  258. for (; j < layer_count; j++)
  259. {
  260. if (layers[j]->type != "Convolution" && layers[j]->type != "ConvolutionDepthWise")
  261. continue;
  262. if (layers[j]->bottoms.size() != 1)
  263. continue;
  264. if (layers[j]->bottoms[0] == top_blob_index)
  265. break;
  266. }
  267. if (j == layer_count)
  268. continue;
  269. // fuse requantize
  270. fprintf(stderr, "fuse_requantize %s %s\n", layers[i]->name.c_str(), layers[j]->name.c_str());
  271. if (layers[i]->type == "Convolution" && layers[j]->type == "Convolution")
  272. {
  273. ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
  274. ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
  275. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  276. continue;
  277. convolution1->int8_scale_term += 100;
  278. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  279. }
  280. if (layers[i]->type == "Convolution" && layers[j]->type == "ConvolutionDepthWise")
  281. {
  282. ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
  283. ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
  284. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  285. continue;
  286. convolution1->int8_scale_term += 100;
  287. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  288. }
  289. if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "Convolution")
  290. {
  291. ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
  292. ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
  293. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  294. continue;
  295. convolution1->int8_scale_term += 100;
  296. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  297. }
  298. if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "ConvolutionDepthWise")
  299. {
  300. ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
  301. ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
  302. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  303. continue;
  304. convolution1->int8_scale_term += 100;
  305. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  306. }
  307. }
  308. for (size_t i = 0; i < layer_count; i++)
  309. {
  310. if (layers[i]->type != "Convolution" && layers[i]->type != "ConvolutionDepthWise")
  311. continue;
  312. // Convolution/ConvolutionDepthWise - Split - Convolution/ConvolutionDepthWise
  313. int top_blob_index = layers[i]->tops[0];
  314. size_t j = i + 1;
  315. for (; j < layer_count; j++)
  316. {
  317. if (layers[j]->type != "Split")
  318. continue;
  319. if (layers[j]->bottoms.size() != 1)
  320. continue;
  321. if (layers[j]->bottoms[0] == top_blob_index)
  322. break;
  323. }
  324. if (j == layer_count)
  325. continue;
  326. ncnn::Split* split = (ncnn::Split*)layers[j];
  327. bool all_conv = true;
  328. for (size_t p = 0; p < split->tops.size(); p++)
  329. {
  330. int split_top_blob_index = split->tops[p];
  331. size_t k = j + 1;
  332. for (; k < layer_count; k++)
  333. {
  334. if (layers[k]->type != "Convolution" && layers[k]->type != "ConvolutionDepthWise")
  335. continue;
  336. if (layers[k]->bottoms.size() != 1)
  337. continue;
  338. if (layers[k]->bottoms[0] == split_top_blob_index)
  339. break;
  340. }
  341. if (k == layer_count)
  342. {
  343. all_conv = false;
  344. break;
  345. }
  346. if (layers[k]->type == "Convolution")
  347. {
  348. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[k];
  349. if (convolution->weight_data.elemsize != 1u)
  350. {
  351. all_conv = false;
  352. break;
  353. }
  354. }
  355. if (layers[k]->type == "ConvolutionDepthWise")
  356. {
  357. ncnn::ConvolutionDepthWise* convolution = (ncnn::ConvolutionDepthWise*)layers[k];
  358. if (convolution->weight_data.elemsize != 1u)
  359. {
  360. all_conv = false;
  361. break;
  362. }
  363. }
  364. }
  365. if (!all_conv)
  366. continue;
  367. j = blobs[split->tops[0]].consumer;
  368. // fuse requantize
  369. fprintf(stderr, "fuse_requantize %s %s\n", layers[i]->name.c_str(), split->name.c_str());
  370. if (layers[i]->type == "Convolution" && layers[j]->type == "Convolution")
  371. {
  372. ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
  373. ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
  374. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  375. continue;
  376. convolution1->int8_scale_term += 100;
  377. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  378. }
  379. if (layers[i]->type == "Convolution" && layers[j]->type == "ConvolutionDepthWise")
  380. {
  381. ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
  382. ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
  383. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  384. continue;
  385. convolution1->int8_scale_term += 100;
  386. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  387. }
  388. if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "Convolution")
  389. {
  390. ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
  391. ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
  392. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  393. continue;
  394. convolution1->int8_scale_term += 100;
  395. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  396. }
  397. if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "ConvolutionDepthWise")
  398. {
  399. ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
  400. ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
  401. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  402. continue;
  403. convolution1->int8_scale_term += 100;
  404. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  405. }
  406. }
  407. return 0;
  408. }
  409. int main(int argc, char** argv)
  410. {
  411. if (argc != 6)
  412. {
  413. fprintf(stderr, "usage: %s [inparam] [inbin] [outparam] [outbin] [calibration table]\n", argv[0]);
  414. return -1;
  415. }
  416. const char* inparam = argv[1];
  417. const char* inbin = argv[2];
  418. const char* outparam = argv[3];
  419. const char* outbin = argv[4];
  420. const char* int8scale_table_path = argv[5];
  421. NetQuantize quantizer;
  422. // parse the calibration scale table
  423. if (int8scale_table_path)
  424. {
  425. bool s2 = read_int8scale_table(int8scale_table_path, quantizer.blob_int8scale_table, quantizer.weight_int8scale_table);
  426. if (!s2)
  427. {
  428. fprintf(stderr, "read_int8scale_table failed\n");
  429. return -1;
  430. }
  431. }
  432. quantizer.load_param(inparam);
  433. if (strcmp(inbin, "null") == 0)
  434. {
  435. DataReaderFromEmpty dr;
  436. quantizer.load_model(dr);
  437. quantizer.gen_random_weight = true;
  438. }
  439. else
  440. quantizer.load_model(inbin);
  441. quantizer.quantize_convolution();
  442. quantizer.quantize_convolutiondepthwise();
  443. quantizer.quantize_innerproduct();
  444. quantizer.fuse_requantize();
  445. quantizer.save(outparam, outbin);
  446. return 0;
  447. }