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

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