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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  1. // Copyright 2019 BUG1989
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. #ifdef _MSC_VER
  4. #define _CRT_SECURE_NO_DEPRECATE
  5. #endif
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <map>
  9. #include <set>
  10. #include <vector>
  11. // ncnn public header
  12. #include "datareader.h"
  13. #include "layer.h"
  14. #include "layer_type.h"
  15. #include "net.h"
  16. // ncnn private header
  17. #include "../modelwriter.h"
  18. class DataReaderFromEmpty : public ncnn::DataReader
  19. {
  20. public:
  21. virtual int scan(const char* format, void* p) const
  22. {
  23. return 0;
  24. }
  25. virtual size_t read(void* buf, size_t size) const
  26. {
  27. memset(buf, 0, size);
  28. return size;
  29. }
  30. };
  31. 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)
  32. {
  33. blob_int8scale_table.clear();
  34. weight_int8scale_table.clear();
  35. FILE* fp = fopen(filepath, "rb");
  36. if (!fp)
  37. {
  38. fprintf(stderr, "Open %s failed.\n", filepath);
  39. return false;
  40. }
  41. std::string key_str;
  42. std::vector<float> scales;
  43. std::vector<char> line(10240000);
  44. char* pch = NULL;
  45. size_t len = 0;
  46. while (!feof(fp))
  47. {
  48. char* s = fgets(line.data(), (int)line.size(), fp);
  49. if (!s)
  50. break;
  51. float scale = 1.f;
  52. char key[256];
  53. line[strcspn(line.data(), "\r\n")] = 0;
  54. pch = strtok(line.data(), " ");
  55. if (pch == NULL) break;
  56. bool is_key = true;
  57. while (pch != NULL)
  58. {
  59. if (is_key)
  60. {
  61. sscanf(pch, "%255s", key);
  62. key_str = key;
  63. is_key = false;
  64. }
  65. else
  66. {
  67. sscanf(pch, "%f", &scale);
  68. scales.push_back(scale);
  69. }
  70. pch = strtok(NULL, " ");
  71. }
  72. // XYZ_param_N pattern
  73. if (strstr(key_str.c_str(), "_param_"))
  74. {
  75. weight_int8scale_table[key_str] = ncnn::Mat((int)scales.size(), (void*)scales.data()).clone();
  76. }
  77. else
  78. {
  79. blob_int8scale_table[key_str] = ncnn::Mat((int)scales.size(), (void*)scales.data()).clone();
  80. }
  81. key_str.clear();
  82. scales.clear();
  83. }
  84. fclose(fp);
  85. return true;
  86. }
  87. class NetQuantize : public ModelWriter
  88. {
  89. public:
  90. NetQuantize();
  91. std::map<std::string, ncnn::Mat> blob_int8scale_table;
  92. std::map<std::string, ncnn::Mat> weight_int8scale_table;
  93. public:
  94. int quantize_convolution();
  95. int quantize_convolutiondepthwise();
  96. int quantize_innerproduct();
  97. int quantize_rnn();
  98. int quantize_lstm();
  99. int quantize_gru();
  100. int quantize_embed();
  101. int quantize_gemm();
  102. int quantize_multiheadattention();
  103. int fuse_requantize();
  104. };
  105. NetQuantize::NetQuantize()
  106. : ModelWriter()
  107. {
  108. }
  109. int NetQuantize::quantize_convolution()
  110. {
  111. const int layer_count = static_cast<int>(layers.size());
  112. for (int i = 0; i < layer_count; i++)
  113. {
  114. // find convolution layer
  115. if (layers[i]->type != "Convolution")
  116. continue;
  117. // find convolution layer
  118. std::map<std::string, ncnn::Mat>::iterator iter_data = blob_int8scale_table.find(layers[i]->name);
  119. if (iter_data == blob_int8scale_table.end())
  120. continue;
  121. char key[256];
  122. sprintf(key, "%s_param_0", layers[i]->name.c_str());
  123. std::map<std::string, ncnn::Mat>::iterator iter = weight_int8scale_table.find(key);
  124. if (iter == weight_int8scale_table.end())
  125. {
  126. fprintf(stderr, "this layer need to be quantized, but no scale param!\n");
  127. return -1;
  128. }
  129. // Convolution - quantize weight from fp32 to int8
  130. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  131. ncnn::Mat bottom_blob_int8_scales = iter_data->second;
  132. ncnn::Mat weight_data_int8_scales = iter->second;
  133. fprintf(stderr, "quantize_convolution %s\n", convolution->name.c_str());
  134. {
  135. const int maxk = convolution->kernel_w * convolution->kernel_h;
  136. const int num_input = convolution->weight_data_size / convolution->num_output / maxk;
  137. ncnn::Mat weight_data_r2 = convolution->weight_data.reshape(maxk, num_input, convolution->num_output);
  138. ncnn::Mat weight_data_int8;
  139. ncnn::Option opt_q = opt;
  140. opt_q.blob_allocator = convolution->weight_data.allocator;
  141. opt_q.use_packing_layout = false;
  142. ncnn::quantize_to_int8(weight_data_r2, weight_data_int8, weight_data_int8_scales, opt_q);
  143. if (weight_data_int8.empty())
  144. return -100;
  145. convolution->weight_data = weight_data_int8.reshape(convolution->weight_data_size);
  146. }
  147. convolution->int8_scale_term = 2;
  148. convolution->weight_data_int8_scales = weight_data_int8_scales;
  149. convolution->bottom_blob_int8_scales = bottom_blob_int8_scales;
  150. }
  151. return 0;
  152. }
  153. int NetQuantize::quantize_convolutiondepthwise()
  154. {
  155. const int layer_count = static_cast<int>(layers.size());
  156. for (int i = 0; i < layer_count; i++)
  157. {
  158. // find convolution layer
  159. if (layers[i]->type != "ConvolutionDepthWise")
  160. continue;
  161. // find convolutiondepthwise layer
  162. std::map<std::string, ncnn::Mat>::iterator iter_data = blob_int8scale_table.find(layers[i]->name);
  163. if (iter_data == blob_int8scale_table.end())
  164. continue;
  165. char key[256];
  166. sprintf(key, "%s_param_0", layers[i]->name.c_str());
  167. std::map<std::string, ncnn::Mat>::iterator iter = weight_int8scale_table.find(key);
  168. if (iter == weight_int8scale_table.end())
  169. {
  170. fprintf(stderr, "this layer need to be quantized, but no scale param!\n");
  171. return -1;
  172. }
  173. // Convolution - quantize weight from fp32 to int8
  174. ncnn::ConvolutionDepthWise* convdw = (ncnn::ConvolutionDepthWise*)layers[i];
  175. ncnn::Mat bottom_blob_int8_scales = iter_data->second;
  176. ncnn::Mat weight_data_int8_scales = iter->second;
  177. fprintf(stderr, "quantize_convolutiondepthwise %s\n", convdw->name.c_str());
  178. {
  179. ncnn::Mat int8_weight_data(convdw->weight_data_size, (size_t)1u);
  180. if (int8_weight_data.empty())
  181. return -100;
  182. const int weight_data_size_g = convdw->weight_data_size / convdw->group;
  183. for (int g = 0; g < convdw->group; g++)
  184. {
  185. ncnn::Option opt_q = opt;
  186. opt_q.blob_allocator = int8_weight_data.allocator;
  187. opt_q.use_packing_layout = false;
  188. const ncnn::Mat weight_data_g = convdw->weight_data.range(weight_data_size_g * g, weight_data_size_g);
  189. ncnn::Mat int8_weight_data_g = int8_weight_data.range(weight_data_size_g * g, weight_data_size_g);
  190. const ncnn::Mat weight_data_int8_scales_g = weight_data_int8_scales.range(g, 1);
  191. ncnn::quantize_to_int8(weight_data_g, int8_weight_data_g, weight_data_int8_scales_g, opt_q);
  192. }
  193. convdw->weight_data = int8_weight_data;
  194. }
  195. convdw->int8_scale_term = 1;
  196. convdw->weight_data_int8_scales = weight_data_int8_scales;
  197. convdw->bottom_blob_int8_scales = bottom_blob_int8_scales;
  198. }
  199. return 0;
  200. }
  201. int NetQuantize::quantize_innerproduct()
  202. {
  203. const int layer_count = static_cast<int>(layers.size());
  204. for (int i = 0; i < layer_count; i++)
  205. {
  206. // find convolution layer
  207. if (layers[i]->type != "InnerProduct")
  208. continue;
  209. // find InnerProduct layer
  210. std::map<std::string, ncnn::Mat>::iterator iter_data = blob_int8scale_table.find(layers[i]->name);
  211. if (iter_data == blob_int8scale_table.end())
  212. continue;
  213. char key[256];
  214. sprintf(key, "%s_param_0", layers[i]->name.c_str());
  215. std::map<std::string, ncnn::Mat>::iterator iter = weight_int8scale_table.find(key);
  216. if (iter == weight_int8scale_table.end())
  217. {
  218. fprintf(stderr, "this layer need to be quantized, but no scale param!\n");
  219. return -1;
  220. }
  221. // InnerProduct - quantize weight from fp32 to int8
  222. ncnn::InnerProduct* fc = (ncnn::InnerProduct*)layers[i];
  223. ncnn::Mat bottom_blob_int8_scales = iter_data->second;
  224. ncnn::Mat weight_data_int8_scales = iter->second;
  225. fprintf(stderr, "quantize_innerproduct %s\n", fc->name.c_str());
  226. {
  227. const int num_input = fc->weight_data_size / fc->num_output;
  228. ncnn::Mat weight_data_r2 = fc->weight_data.reshape(num_input, fc->num_output);
  229. ncnn::Mat weight_data_int8;
  230. ncnn::Option opt_q = opt;
  231. opt_q.use_packing_layout = false;
  232. ncnn::quantize_to_int8(weight_data_r2, weight_data_int8, weight_data_int8_scales, opt_q);
  233. if (weight_data_int8.empty())
  234. return -100;
  235. fc->weight_data = weight_data_int8.reshape(fc->weight_data_size);
  236. }
  237. fc->int8_scale_term = 2;
  238. fc->weight_data_int8_scales = weight_data_int8_scales;
  239. fc->bottom_blob_int8_scales = bottom_blob_int8_scales;
  240. }
  241. return 0;
  242. }
  243. int NetQuantize::quantize_rnn()
  244. {
  245. for (size_t i = 0; i < layers.size(); i++)
  246. {
  247. if (layers[i]->type != "RNN")
  248. continue;
  249. // RNN - quantize weight from fp32 to int8
  250. ncnn::RNN* rnn = (ncnn::RNN*)layers[i];
  251. fprintf(stderr, "quantize_rnn %s\n", rnn->name.c_str());
  252. // TODO move to ncnn2table
  253. const int num_directions = rnn->direction == 2 ? 2 : 1;
  254. const int size = rnn->weight_data_size / num_directions / rnn->num_output;
  255. ncnn::Mat weight_xc_data_int8_scales(rnn->num_output * num_directions);
  256. ncnn::Mat weight_hc_data_int8_scales(rnn->num_output * num_directions);
  257. for (int d = 0; d < num_directions; d++)
  258. {
  259. for (int q = 0; q < rnn->num_output; q++)
  260. {
  261. {
  262. const float* weight_xc_ptr = rnn->weight_xc_data.channel(d).row(q);
  263. float absmax = 0.f;
  264. for (int i = 0; i < size; i++)
  265. {
  266. absmax = std::max(absmax, (float)fabs(weight_xc_ptr[i]));
  267. }
  268. weight_xc_data_int8_scales[d * rnn->num_output + q] = 127 / absmax;
  269. }
  270. {
  271. const float* weight_hc_ptr = rnn->weight_hc_data.channel(d).row(q);
  272. float absmax = 0.f;
  273. for (int i = 0; i < size; i++)
  274. {
  275. absmax = std::max(absmax, (float)fabs(weight_hc_ptr[i]));
  276. }
  277. weight_hc_data_int8_scales[d * rnn->num_output + q] = 127 / absmax;
  278. }
  279. }
  280. }
  281. {
  282. ncnn::Mat weight_xc_data_r2 = rnn->weight_xc_data.reshape(size, rnn->num_output * num_directions);
  283. ncnn::Mat weight_xc_data_int8;
  284. ncnn::Option opt_q = opt;
  285. opt_q.blob_allocator = rnn->weight_xc_data.allocator;
  286. opt_q.use_packing_layout = false;
  287. ncnn::quantize_to_int8(weight_xc_data_r2, weight_xc_data_int8, weight_xc_data_int8_scales, opt_q);
  288. if (weight_xc_data_int8.empty())
  289. return -100;
  290. rnn->weight_xc_data = weight_xc_data_int8.reshape(size * rnn->num_output * num_directions);
  291. }
  292. {
  293. ncnn::Mat weight_hc_data_r2 = rnn->weight_hc_data.reshape(rnn->num_output, rnn->num_output * num_directions);
  294. ncnn::Mat weight_hc_data_int8;
  295. ncnn::Option opt_q = opt;
  296. opt_q.blob_allocator = rnn->weight_hc_data.allocator;
  297. opt_q.use_packing_layout = false;
  298. ncnn::quantize_to_int8(weight_hc_data_r2, weight_hc_data_int8, weight_hc_data_int8_scales, opt_q);
  299. if (weight_hc_data_int8.empty())
  300. return -100;
  301. rnn->weight_hc_data = weight_hc_data_int8.reshape(rnn->num_output * rnn->num_output * num_directions);
  302. }
  303. rnn->int8_scale_term = 2;
  304. rnn->weight_xc_data_int8_scales = weight_xc_data_int8_scales;
  305. rnn->weight_hc_data_int8_scales = weight_hc_data_int8_scales;
  306. }
  307. return 0;
  308. }
  309. int NetQuantize::quantize_lstm()
  310. {
  311. for (size_t i = 0; i < layers.size(); i++)
  312. {
  313. if (layers[i]->type != "LSTM")
  314. continue;
  315. // LSTM - quantize weight from fp32 to int8
  316. ncnn::LSTM* lstm = (ncnn::LSTM*)layers[i];
  317. fprintf(stderr, "quantize_lstm %s\n", lstm->name.c_str());
  318. // TODO move to ncnn2table
  319. const int num_directions = lstm->direction == 2 ? 2 : 1;
  320. const int size = lstm->weight_data_size / num_directions / lstm->hidden_size / 4;
  321. ncnn::Mat weight_xc_data_int8_scales(lstm->hidden_size * 4 * num_directions);
  322. ncnn::Mat weight_hc_data_int8_scales(lstm->hidden_size * 4 * num_directions);
  323. for (int d = 0; d < num_directions; d++)
  324. {
  325. for (int q = 0; q < lstm->hidden_size * 4; q++)
  326. {
  327. {
  328. const float* weight_xc_ptr = lstm->weight_xc_data.channel(d).row(q);
  329. float absmax = 0.f;
  330. for (int i = 0; i < size; i++)
  331. {
  332. absmax = std::max(absmax, (float)fabs(weight_xc_ptr[i]));
  333. }
  334. weight_xc_data_int8_scales[d * lstm->hidden_size * 4 + q] = 127 / absmax;
  335. }
  336. {
  337. const float* weight_hc_ptr = lstm->weight_hc_data.channel(d).row(q);
  338. float absmax = 0.f;
  339. for (int i = 0; i < size; i++)
  340. {
  341. absmax = std::max(absmax, (float)fabs(weight_hc_ptr[i]));
  342. }
  343. weight_hc_data_int8_scales[d * lstm->hidden_size * 4 + q] = 127 / absmax;
  344. }
  345. }
  346. }
  347. {
  348. ncnn::Mat weight_xc_data_r2 = lstm->weight_xc_data.reshape(size, lstm->hidden_size * 4 * num_directions);
  349. ncnn::Mat weight_xc_data_int8;
  350. ncnn::Option opt_q = opt;
  351. opt_q.blob_allocator = lstm->weight_xc_data.allocator;
  352. opt_q.use_packing_layout = false;
  353. ncnn::quantize_to_int8(weight_xc_data_r2, weight_xc_data_int8, weight_xc_data_int8_scales, opt_q);
  354. if (weight_xc_data_int8.empty())
  355. return -100;
  356. lstm->weight_xc_data = weight_xc_data_int8.reshape(size * lstm->hidden_size * 4 * num_directions);
  357. }
  358. {
  359. ncnn::Mat weight_hc_data_r2 = lstm->weight_hc_data.reshape(lstm->num_output, lstm->hidden_size * 4 * num_directions);
  360. ncnn::Mat weight_hc_data_int8;
  361. ncnn::Option opt_q = opt;
  362. opt_q.blob_allocator = lstm->weight_hc_data.allocator;
  363. opt_q.use_packing_layout = false;
  364. ncnn::quantize_to_int8(weight_hc_data_r2, weight_hc_data_int8, weight_hc_data_int8_scales, opt_q);
  365. if (weight_hc_data_int8.empty())
  366. return -100;
  367. lstm->weight_hc_data = weight_hc_data_int8.reshape(lstm->num_output * lstm->hidden_size * 4 * num_directions);
  368. }
  369. lstm->int8_scale_term = 2;
  370. lstm->weight_xc_data_int8_scales = weight_xc_data_int8_scales;
  371. lstm->weight_hc_data_int8_scales = weight_hc_data_int8_scales;
  372. }
  373. return 0;
  374. }
  375. int NetQuantize::quantize_gru()
  376. {
  377. for (size_t i = 0; i < layers.size(); i++)
  378. {
  379. if (layers[i]->type != "GRU")
  380. continue;
  381. // GRU - quantize weight from fp32 to int8
  382. ncnn::GRU* gru = (ncnn::GRU*)layers[i];
  383. fprintf(stderr, "quantize_gru %s\n", gru->name.c_str());
  384. // TODO move to ncnn2table
  385. const int num_directions = gru->direction == 2 ? 2 : 1;
  386. const int size = gru->weight_data_size / num_directions / gru->num_output / 3;
  387. ncnn::Mat weight_xc_data_int8_scales(gru->num_output * 3 * num_directions);
  388. ncnn::Mat weight_hc_data_int8_scales(gru->num_output * 3 * num_directions);
  389. for (int d = 0; d < num_directions; d++)
  390. {
  391. for (int q = 0; q < gru->num_output * 3; q++)
  392. {
  393. {
  394. const float* weight_xc_ptr = gru->weight_xc_data.channel(d).row(q);
  395. float absmax = 0.f;
  396. for (int i = 0; i < size; i++)
  397. {
  398. absmax = std::max(absmax, (float)fabs(weight_xc_ptr[i]));
  399. }
  400. weight_xc_data_int8_scales[d * gru->num_output * 3 + q] = 127 / absmax;
  401. }
  402. {
  403. const float* weight_hc_ptr = gru->weight_hc_data.channel(d).row(q);
  404. float absmax = 0.f;
  405. for (int i = 0; i < size; i++)
  406. {
  407. absmax = std::max(absmax, (float)fabs(weight_hc_ptr[i]));
  408. }
  409. weight_hc_data_int8_scales[d * gru->num_output * 3 + q] = 127 / absmax;
  410. }
  411. }
  412. }
  413. {
  414. ncnn::Mat weight_xc_data_r2 = gru->weight_xc_data.reshape(size, gru->num_output * 3 * num_directions);
  415. ncnn::Mat weight_xc_data_int8;
  416. ncnn::Option opt_q = opt;
  417. opt_q.blob_allocator = gru->weight_xc_data.allocator;
  418. opt_q.use_packing_layout = false;
  419. ncnn::quantize_to_int8(weight_xc_data_r2, weight_xc_data_int8, weight_xc_data_int8_scales, opt_q);
  420. if (weight_xc_data_int8.empty())
  421. return -100;
  422. gru->weight_xc_data = weight_xc_data_int8.reshape(size * gru->num_output * 3 * num_directions);
  423. }
  424. {
  425. ncnn::Mat weight_hc_data_r2 = gru->weight_hc_data.reshape(gru->num_output, gru->num_output * 3 * num_directions);
  426. ncnn::Mat weight_hc_data_int8;
  427. ncnn::Option opt_q = opt;
  428. opt_q.blob_allocator = gru->weight_hc_data.allocator;
  429. opt_q.use_packing_layout = false;
  430. ncnn::quantize_to_int8(weight_hc_data_r2, weight_hc_data_int8, weight_hc_data_int8_scales, opt_q);
  431. if (weight_hc_data_int8.empty())
  432. return -100;
  433. gru->weight_hc_data = weight_hc_data_int8.reshape(gru->num_output * gru->num_output * 3 * num_directions);
  434. }
  435. gru->int8_scale_term = 2;
  436. gru->weight_xc_data_int8_scales = weight_xc_data_int8_scales;
  437. gru->weight_hc_data_int8_scales = weight_hc_data_int8_scales;
  438. }
  439. return 0;
  440. }
  441. int NetQuantize::quantize_embed()
  442. {
  443. for (size_t i = 0; i < layers.size(); i++)
  444. {
  445. if (layers[i]->type != "Embed")
  446. continue;
  447. // Embed - quantize weight from fp32 to int8
  448. ncnn::Embed* embed = (ncnn::Embed*)layers[i];
  449. fprintf(stderr, "quantize_embed %s\n", embed->name.c_str());
  450. // TODO move to ncnn2table
  451. const int num_output = embed->num_output;
  452. const int input_dim = embed->input_dim;
  453. ncnn::Mat weight_data_int8_scales(1);
  454. {
  455. const float* ptr = embed->weight_data;
  456. float absmax = 0.f;
  457. for (int i = 0; i < embed->weight_data.w; i++)
  458. {
  459. absmax = std::max(absmax, (float)fabs(ptr[i]));
  460. }
  461. weight_data_int8_scales[0] = absmax == 0.f ? 1.f : 127 / absmax;
  462. }
  463. {
  464. ncnn::Mat weight_data_int8;
  465. ncnn::Option opt_q = opt;
  466. opt_q.blob_allocator = embed->weight_data.allocator;
  467. opt_q.use_packing_layout = false;
  468. ncnn::quantize_to_int8(embed->weight_data, weight_data_int8, weight_data_int8_scales, opt_q);
  469. if (weight_data_int8.empty())
  470. return -100;
  471. embed->weight_data = weight_data_int8;
  472. }
  473. embed->int8_scale_term = 2;
  474. embed->weight_data_int8_scale = weight_data_int8_scales[0];
  475. }
  476. return 0;
  477. }
  478. int NetQuantize::quantize_gemm()
  479. {
  480. for (size_t i = 0; i < layers.size(); i++)
  481. {
  482. if (layers[i]->type != "Gemm")
  483. continue;
  484. // Gemm - quantize weight from fp32 to int8
  485. ncnn::Gemm* gemm = (ncnn::Gemm*)layers[i];
  486. fprintf(stderr, "quantize_gemm %s\n", gemm->name.c_str());
  487. // TODO move to ncnn2table
  488. if (gemm->constantA)
  489. {
  490. if (gemm->transA == 1)
  491. {
  492. // transpose for easier quantization
  493. ncnn::Mat A_data_transposed(gemm->constantK * gemm->constantM);
  494. for (int i = 0; i < gemm->constantM; i++)
  495. {
  496. float* ptr = (float*)A_data_transposed + i * gemm->constantK;
  497. for (int j = 0; j < gemm->constantK; j++)
  498. {
  499. ptr[j] = gemm->A_data[j * gemm->constantM + i];
  500. }
  501. }
  502. gemm->A_data = A_data_transposed;
  503. gemm->transA = 0;
  504. }
  505. gemm->A_data_int8_scales.create(gemm->constantM);
  506. for (int i = 0; i < gemm->constantM; i++)
  507. {
  508. float absmax = 0.f;
  509. const float* ptr = (const float*)gemm->A_data + i * gemm->constantK;
  510. for (int j = 0; j < gemm->constantK; j++)
  511. {
  512. absmax = std::max(absmax, (float)fabs(ptr[j]));
  513. }
  514. gemm->A_data_int8_scales[i] = absmax == 0.f ? 1.f : 127 / absmax;
  515. }
  516. ncnn::Mat A_data = gemm->A_data.reshape(gemm->constantK, gemm->constantM);
  517. ncnn::Mat A_data_int8;
  518. ncnn::Option opt_q = opt;
  519. opt_q.blob_allocator = A_data.allocator;
  520. opt_q.use_packing_layout = false;
  521. ncnn::quantize_to_int8(A_data, A_data_int8, gemm->A_data_int8_scales, opt_q);
  522. if (A_data_int8.empty())
  523. return -100;
  524. gemm->A_data = A_data_int8.reshape(gemm->constantK * gemm->constantM);
  525. }
  526. if (gemm->constantB)
  527. {
  528. if (gemm->transB == 0)
  529. {
  530. // transpose for easier quantization
  531. ncnn::Mat B_data_transposed(gemm->constantK * gemm->constantN);
  532. for (int i = 0; i < gemm->constantN; i++)
  533. {
  534. float* ptr = (float*)B_data_transposed + i * gemm->constantK;
  535. for (int j = 0; j < gemm->constantK; j++)
  536. {
  537. ptr[j] = gemm->B_data[j * gemm->constantN + i];
  538. }
  539. }
  540. gemm->B_data = B_data_transposed;
  541. gemm->transB = 1;
  542. }
  543. const float* ptr = gemm->B_data;
  544. float absmax = 0.f;
  545. for (int j = 0; j < gemm->B_data.w; j++)
  546. {
  547. absmax = std::max(absmax, (float)fabs(ptr[j]));
  548. }
  549. gemm->B_data_int8_scale = absmax == 0.f ? 1.f : 127 / absmax;
  550. ncnn::Mat B_data_int8_scales(1);
  551. B_data_int8_scales[0] = gemm->B_data_int8_scale;
  552. ncnn::Mat B_data_int8;
  553. ncnn::Option opt_q = opt;
  554. opt_q.blob_allocator = gemm->B_data.allocator;
  555. opt_q.use_packing_layout = false;
  556. ncnn::quantize_to_int8(gemm->B_data, B_data_int8, B_data_int8_scales, opt_q);
  557. if (B_data_int8.empty())
  558. return -100;
  559. gemm->B_data = B_data_int8;
  560. }
  561. gemm->int8_scale_term = 2;
  562. }
  563. return 0;
  564. }
  565. int NetQuantize::quantize_multiheadattention()
  566. {
  567. for (size_t i = 0; i < layers.size(); i++)
  568. {
  569. if (layers[i]->type != "MultiHeadAttention")
  570. continue;
  571. // MultiHeadAttention - quantize weight from fp32 to int8
  572. ncnn::MultiHeadAttention* mha = (ncnn::MultiHeadAttention*)layers[i];
  573. fprintf(stderr, "quantize_multiheadattention %s\n", mha->name.c_str());
  574. // TODO move to ncnn2table
  575. const int qdim = mha->weight_data_size / mha->embed_dim;
  576. {
  577. mha->q_weight_data_int8_scales.create(mha->embed_dim);
  578. for (int i = 0; i < mha->embed_dim; i++)
  579. {
  580. float absmax = 0.f;
  581. const float* ptr = (const float*)mha->q_weight_data + i * qdim;
  582. for (int j = 0; j < qdim; j++)
  583. {
  584. absmax = std::max(absmax, (float)fabs(ptr[j]));
  585. }
  586. mha->q_weight_data_int8_scales[i] = absmax == 0.f ? 1.f : 127 / absmax;
  587. }
  588. ncnn::Mat q_weight_data = mha->q_weight_data.reshape(qdim, mha->embed_dim);
  589. ncnn::Mat q_weight_data_int8;
  590. ncnn::Option opt_q = opt;
  591. opt_q.blob_allocator = q_weight_data.allocator;
  592. opt_q.use_packing_layout = false;
  593. ncnn::quantize_to_int8(q_weight_data, q_weight_data_int8, mha->q_weight_data_int8_scales, opt_q);
  594. if (q_weight_data_int8.empty())
  595. return -100;
  596. mha->q_weight_data = q_weight_data_int8.reshape(qdim * mha->embed_dim);
  597. }
  598. {
  599. mha->k_weight_data_int8_scales.create(mha->embed_dim);
  600. for (int i = 0; i < mha->embed_dim; i++)
  601. {
  602. float absmax = 0.f;
  603. const float* ptr = (const float*)mha->k_weight_data + i * mha->kdim;
  604. for (int j = 0; j < mha->kdim; j++)
  605. {
  606. absmax = std::max(absmax, (float)fabs(ptr[j]));
  607. }
  608. mha->k_weight_data_int8_scales[i] = absmax == 0.f ? 1.f : 127 / absmax;
  609. }
  610. ncnn::Mat k_weight_data = mha->k_weight_data.reshape(mha->kdim, mha->embed_dim);
  611. ncnn::Mat k_weight_data_int8;
  612. ncnn::Option opt_q = opt;
  613. opt_q.blob_allocator = k_weight_data.allocator;
  614. opt_q.use_packing_layout = false;
  615. ncnn::quantize_to_int8(k_weight_data, k_weight_data_int8, mha->k_weight_data_int8_scales, opt_q);
  616. if (k_weight_data_int8.empty())
  617. return -100;
  618. mha->k_weight_data = k_weight_data_int8.reshape(mha->kdim * mha->embed_dim);
  619. }
  620. {
  621. mha->v_weight_data_int8_scales.create(mha->embed_dim);
  622. for (int i = 0; i < mha->embed_dim; i++)
  623. {
  624. float absmax = 0.f;
  625. const float* ptr = (const float*)mha->v_weight_data + i * mha->vdim;
  626. for (int j = 0; j < mha->vdim; j++)
  627. {
  628. absmax = std::max(absmax, (float)fabs(ptr[j]));
  629. }
  630. mha->v_weight_data_int8_scales[i] = absmax == 0.f ? 1.f : 127 / absmax;
  631. }
  632. ncnn::Mat v_weight_data = mha->v_weight_data.reshape(mha->vdim, mha->embed_dim);
  633. ncnn::Mat v_weight_data_int8;
  634. ncnn::Option opt_q = opt;
  635. opt_q.blob_allocator = v_weight_data.allocator;
  636. opt_q.use_packing_layout = false;
  637. ncnn::quantize_to_int8(v_weight_data, v_weight_data_int8, mha->v_weight_data_int8_scales, opt_q);
  638. if (v_weight_data_int8.empty())
  639. return -100;
  640. mha->v_weight_data = v_weight_data_int8.reshape(mha->vdim * mha->embed_dim);
  641. }
  642. {
  643. const float* ptr = mha->out_weight_data;
  644. float absmax = 0.f;
  645. for (int j = 0; j < mha->out_weight_data.w; j++)
  646. {
  647. absmax = std::max(absmax, (float)fabs(ptr[j]));
  648. }
  649. mha->out_weight_data_int8_scale = absmax == 0.f ? 1.f : 127 / absmax;
  650. ncnn::Mat out_weight_data_int8_scales(1);
  651. out_weight_data_int8_scales[0] = mha->out_weight_data_int8_scale;
  652. ncnn::Mat out_weight_data_int8;
  653. ncnn::Option opt_q = opt;
  654. opt_q.blob_allocator = mha->out_weight_data.allocator;
  655. opt_q.use_packing_layout = false;
  656. ncnn::quantize_to_int8(mha->out_weight_data, out_weight_data_int8, out_weight_data_int8_scales, opt_q);
  657. if (out_weight_data_int8.empty())
  658. return -100;
  659. mha->out_weight_data = out_weight_data_int8;
  660. }
  661. mha->int8_scale_term = 2;
  662. }
  663. return 0;
  664. }
  665. int NetQuantize::fuse_requantize()
  666. {
  667. const size_t layer_count = layers.size();
  668. for (size_t i = 0; i < layer_count; i++)
  669. {
  670. if (layers[i]->type != "Convolution" && layers[i]->type != "ConvolutionDepthWise")
  671. continue;
  672. // Convolution/ConvolutionDepthWise - Convolution/ConvolutionDepthWise
  673. int top_blob_index = layers[i]->tops[0];
  674. size_t j = i + 1;
  675. for (; j < layer_count; j++)
  676. {
  677. if (layers[j]->type != "Convolution" && layers[j]->type != "ConvolutionDepthWise")
  678. continue;
  679. if (layers[j]->bottoms.size() != 1)
  680. continue;
  681. if (layers[j]->bottoms[0] == top_blob_index)
  682. break;
  683. }
  684. if (j == layer_count)
  685. continue;
  686. // fuse requantize
  687. fprintf(stderr, "fuse_requantize %s %s\n", layers[i]->name.c_str(), layers[j]->name.c_str());
  688. if (layers[i]->type == "Convolution" && layers[j]->type == "Convolution")
  689. {
  690. ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
  691. ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
  692. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  693. continue;
  694. convolution1->int8_scale_term += 100;
  695. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  696. }
  697. if (layers[i]->type == "Convolution" && layers[j]->type == "ConvolutionDepthWise")
  698. {
  699. ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
  700. ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
  701. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  702. continue;
  703. convolution1->int8_scale_term += 100;
  704. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  705. }
  706. if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "Convolution")
  707. {
  708. ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
  709. ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
  710. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  711. continue;
  712. convolution1->int8_scale_term += 100;
  713. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  714. }
  715. if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "ConvolutionDepthWise")
  716. {
  717. ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
  718. ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
  719. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  720. continue;
  721. convolution1->int8_scale_term += 100;
  722. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  723. }
  724. }
  725. for (size_t i = 0; i < layer_count; i++)
  726. {
  727. if (layers[i]->type != "Convolution" && layers[i]->type != "ConvolutionDepthWise")
  728. continue;
  729. // Convolution/ConvolutionDepthWise - Split - Convolution/ConvolutionDepthWise
  730. int top_blob_index = layers[i]->tops[0];
  731. size_t j = i + 1;
  732. for (; j < layer_count; j++)
  733. {
  734. if (layers[j]->type != "Split")
  735. continue;
  736. if (layers[j]->bottoms.size() != 1)
  737. continue;
  738. if (layers[j]->bottoms[0] == top_blob_index)
  739. break;
  740. }
  741. if (j == layer_count)
  742. continue;
  743. ncnn::Split* split = (ncnn::Split*)layers[j];
  744. bool all_conv = true;
  745. for (size_t p = 0; p < split->tops.size(); p++)
  746. {
  747. int split_top_blob_index = split->tops[p];
  748. size_t k = j + 1;
  749. for (; k < layer_count; k++)
  750. {
  751. if (layers[k]->type != "Convolution" && layers[k]->type != "ConvolutionDepthWise")
  752. continue;
  753. if (layers[k]->bottoms.size() != 1)
  754. continue;
  755. if (layers[k]->bottoms[0] == split_top_blob_index)
  756. break;
  757. }
  758. if (k == layer_count)
  759. {
  760. all_conv = false;
  761. break;
  762. }
  763. if (layers[k]->type == "Convolution")
  764. {
  765. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[k];
  766. if (convolution->weight_data.elemsize != 1u)
  767. {
  768. all_conv = false;
  769. break;
  770. }
  771. }
  772. if (layers[k]->type == "ConvolutionDepthWise")
  773. {
  774. ncnn::ConvolutionDepthWise* convolution = (ncnn::ConvolutionDepthWise*)layers[k];
  775. if (convolution->weight_data.elemsize != 1u)
  776. {
  777. all_conv = false;
  778. break;
  779. }
  780. }
  781. }
  782. if (!all_conv)
  783. continue;
  784. j = blobs[split->tops[0]].consumer;
  785. // fuse requantize
  786. fprintf(stderr, "fuse_requantize %s %s\n", layers[i]->name.c_str(), split->name.c_str());
  787. if (layers[i]->type == "Convolution" && layers[j]->type == "Convolution")
  788. {
  789. ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
  790. ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
  791. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  792. continue;
  793. convolution1->int8_scale_term += 100;
  794. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  795. }
  796. if (layers[i]->type == "Convolution" && layers[j]->type == "ConvolutionDepthWise")
  797. {
  798. ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
  799. ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
  800. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  801. continue;
  802. convolution1->int8_scale_term += 100;
  803. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  804. }
  805. if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "Convolution")
  806. {
  807. ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
  808. ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
  809. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  810. continue;
  811. convolution1->int8_scale_term += 100;
  812. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  813. }
  814. if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "ConvolutionDepthWise")
  815. {
  816. ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
  817. ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
  818. if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
  819. continue;
  820. convolution1->int8_scale_term += 100;
  821. convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
  822. }
  823. }
  824. return 0;
  825. }
  826. int main(int argc, char** argv)
  827. {
  828. if (argc != 5 && argc != 6)
  829. {
  830. fprintf(stderr, "usage: %s [inparam] [inbin] [outparam] [outbin] [calibration table]\n", argv[0]);
  831. return -1;
  832. }
  833. const char* inparam = argv[1];
  834. const char* inbin = argv[2];
  835. const char* outparam = argv[3];
  836. const char* outbin = argv[4];
  837. const char* int8scale_table_path = argc == 6 ? argv[5] : NULL;
  838. NetQuantize quantizer;
  839. quantizer.storage_type = 1; // use fp16 where int8 not applied
  840. // parse the calibration scale table
  841. if (int8scale_table_path)
  842. {
  843. bool s2 = read_int8scale_table(int8scale_table_path, quantizer.blob_int8scale_table, quantizer.weight_int8scale_table);
  844. if (!s2)
  845. {
  846. fprintf(stderr, "read_int8scale_table failed\n");
  847. return -1;
  848. }
  849. }
  850. quantizer.load_param(inparam);
  851. if (strcmp(inbin, "null") == 0)
  852. {
  853. DataReaderFromEmpty dr;
  854. quantizer.load_model(dr);
  855. quantizer.gen_random_weight = true;
  856. }
  857. else
  858. quantizer.load_model(inbin);
  859. quantizer.quantize_convolution();
  860. quantizer.quantize_convolutiondepthwise();
  861. quantizer.quantize_innerproduct();
  862. quantizer.quantize_rnn();
  863. quantizer.quantize_lstm();
  864. quantizer.quantize_gru();
  865. quantizer.quantize_embed();
  866. quantizer.quantize_gemm();
  867. quantizer.quantize_multiheadattention();
  868. quantizer.fuse_requantize();
  869. quantizer.save(outparam, outbin);
  870. return 0;
  871. }