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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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. // parse the calibration scale table
  851. if (int8scale_table_path)
  852. {
  853. bool s2 = read_int8scale_table(int8scale_table_path, quantizer.blob_int8scale_table, quantizer.weight_int8scale_table);
  854. if (!s2)
  855. {
  856. fprintf(stderr, "read_int8scale_table failed\n");
  857. return -1;
  858. }
  859. }
  860. quantizer.load_param(inparam);
  861. if (strcmp(inbin, "null") == 0)
  862. {
  863. DataReaderFromEmpty dr;
  864. quantizer.load_model(dr);
  865. quantizer.gen_random_weight = true;
  866. }
  867. else
  868. quantizer.load_model(inbin);
  869. quantizer.quantize_convolution();
  870. quantizer.quantize_convolutiondepthwise();
  871. quantizer.quantize_innerproduct();
  872. quantizer.quantize_rnn();
  873. quantizer.quantize_lstm();
  874. quantizer.quantize_gru();
  875. quantizer.quantize_embed();
  876. quantizer.quantize_gemm();
  877. quantizer.quantize_multiheadattention();
  878. quantizer.fuse_requantize();
  879. quantizer.save(outparam, outbin);
  880. return 0;
  881. }