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 18 kB

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