quantize.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #include "ggml.h"
  2. #include "utils.h"
  3. #include <cassert>
  4. #include <cmath>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <fstream>
  8. #include <map>
  9. #include <string>
  10. #include <vector>
  11. #include <regex>
  12. // TODO: move somewhere else
  13. #define QK 32
  14. // default hparams (LLaMA76B)
  15. struct llama_hparams {
  16. int32_t n_vocab = 32000;
  17. int32_t n_ctx = 512; // this is provided as user input?
  18. int32_t n_embd = 4096;
  19. int32_t n_mult = 256;
  20. int32_t n_head = 32;
  21. int32_t n_layer = 32;
  22. int32_t n_rot = 64;
  23. int32_t f16 = 1;
  24. };
  25. // quantize a model
  26. bool llama_model_quantize(const std::string & fname_inp, const std::string & fname_out, int itype) {
  27. ggml_type type = GGML_TYPE_Q4_1;
  28. switch (itype) {
  29. case 2: type = GGML_TYPE_Q4_0; break;
  30. case 3: type = GGML_TYPE_Q4_1; break;
  31. default: fprintf(stderr, "%s: invalid quantization type %d\n", __func__, itype); return 1;
  32. };
  33. if (type != GGML_TYPE_Q4_0 && type != GGML_TYPE_Q4_1) {
  34. fprintf(stderr, "%s: invalid quantization type %d\n", __func__, type);
  35. return false;
  36. }
  37. gpt_vocab vocab;
  38. printf("%s: loading model from '%s'\n", __func__, fname_inp.c_str());
  39. auto finp = std::ifstream(fname_inp, std::ios::binary);
  40. if (!finp) {
  41. fprintf(stderr, "%s: failed to open '%s' for reading\n", __func__, fname_inp.c_str());
  42. return false;
  43. }
  44. auto fout = std::ofstream(fname_out, std::ios::binary);
  45. if (!fout) {
  46. fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname_out.c_str());
  47. return false;
  48. }
  49. // verify magic
  50. {
  51. uint32_t magic;
  52. finp.read((char *) &magic, sizeof(magic));
  53. if (magic != 0x67676d6c) {
  54. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname_inp.c_str());
  55. return false;
  56. }
  57. fout.write((char *) &magic, sizeof(magic));
  58. }
  59. llama_hparams hparams;
  60. // load hparams
  61. {
  62. finp.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  63. //finp.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  64. finp.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  65. finp.read((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  66. finp.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  67. finp.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  68. finp.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  69. finp.read((char *) &hparams.f16, sizeof(hparams.f16));
  70. printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  71. printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  72. printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
  73. printf("%s: n_mult = %d\n", __func__, hparams.n_mult);
  74. printf("%s: n_head = %d\n", __func__, hparams.n_head);
  75. printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
  76. printf("%s: f16 = %d\n", __func__, hparams.f16);
  77. fout.write((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  78. //fout.write((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  79. fout.write((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  80. fout.write((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  81. fout.write((char *) &hparams.n_head, sizeof(hparams.n_head));
  82. fout.write((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  83. fout.write((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  84. fout.write((char *) &itype, sizeof(hparams.f16));
  85. }
  86. // load vocab
  87. {
  88. const int32_t n_vocab = hparams.n_vocab;
  89. if (n_vocab != hparams.n_vocab) {
  90. fprintf(stderr, "%s: invalid model file '%s' (bad vocab size %d != %d)\n",
  91. __func__, fname_inp.c_str(), n_vocab, hparams.n_vocab);
  92. return false;
  93. }
  94. std::string word;
  95. for (int i = 0; i < n_vocab; i++) {
  96. uint32_t len;
  97. finp.read ((char *) &len, sizeof(len));
  98. fout.write((char *) &len, sizeof(len));
  99. word.resize(len);
  100. finp.read ((char *) word.data(), len);
  101. fout.write((char *) word.data(), len);
  102. vocab.token_to_id[word] = i;
  103. vocab.id_to_token[i] = word;
  104. }
  105. }
  106. // load weights
  107. {
  108. size_t total_size_org = 0;
  109. size_t total_size_new = 0;
  110. std::vector<float> work;
  111. std::vector<uint8_t> data_u8;
  112. std::vector<ggml_fp16_t> data_f16;
  113. std::vector<float> data_f32;
  114. std::vector<int64_t> hist_all(1 << 4, 0);
  115. while (true) {
  116. int32_t n_dims;
  117. int32_t length;
  118. int32_t ftype;
  119. finp.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  120. finp.read(reinterpret_cast<char *>(&length), sizeof(length));
  121. finp.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  122. if (finp.eof()) {
  123. break;
  124. }
  125. int32_t nelements = 1;
  126. int32_t ne[2] = { 1, 1 };
  127. for (int i = 0; i < n_dims; ++i) {
  128. finp.read (reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  129. nelements *= ne[i];
  130. }
  131. std::string name(length, 0);
  132. finp.read (&name[0], length);
  133. {
  134. static const char * ftype_str[] = { "f32", "f16", "q4_0", "q4_1", };
  135. printf("%48s - [%5d, %5d], type = %6s ", name.data(), ne[0], ne[1], ftype_str[ftype]);
  136. }
  137. // regexes of tensor names to be quantized
  138. const std::vector<std::string> k_names = {
  139. ".*weight",
  140. };
  141. bool quantize = false;
  142. for (const auto & s : k_names) {
  143. if (std::regex_match(name, std::regex(s))) {
  144. quantize = true;
  145. break;
  146. }
  147. }
  148. // quantize only 2D tensors
  149. quantize &= (n_dims == 2);
  150. if (quantize) {
  151. if (ftype != 0 && ftype != 1) {
  152. fprintf(stderr, "%s: unsupported ftype %d for integer quantization\n", __func__, ftype);
  153. return false;
  154. }
  155. if (ftype == 1) {
  156. data_f16.resize(nelements);
  157. finp.read(reinterpret_cast<char *>(data_f16.data()), nelements * sizeof(ggml_fp16_t));
  158. data_f32.resize(nelements);
  159. for (int i = 0; i < nelements; ++i) {
  160. data_f32[i] = ggml_fp16_to_fp32(data_f16[i]);
  161. }
  162. } else {
  163. data_f32.resize(nelements);
  164. finp.read(reinterpret_cast<char *>(data_f32.data()), nelements * sizeof(float));
  165. }
  166. ftype = itype;
  167. } else {
  168. const int bpe = (ftype == 0) ? sizeof(float) : sizeof(uint16_t);
  169. data_u8.resize(nelements*bpe);
  170. finp.read(reinterpret_cast<char *>(data_u8.data()), nelements * bpe);
  171. }
  172. fout.write(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  173. fout.write(reinterpret_cast<char *>(&length), sizeof(length));
  174. fout.write(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  175. for (int i = 0; i < n_dims; ++i) {
  176. fout.write(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  177. }
  178. fout.write(&name[0], length);
  179. if (quantize) {
  180. printf("quantizing .. ");
  181. work.resize(nelements); // for quantization
  182. size_t cur_size = 0;
  183. std::vector<int64_t> hist_cur(1 << 4, 0);
  184. switch (type) {
  185. case GGML_TYPE_Q4_0:
  186. {
  187. cur_size = ggml_quantize_q4_0(data_f32.data(), work.data(), nelements, ne[0], QK, hist_cur.data());
  188. } break;
  189. case GGML_TYPE_Q4_1:
  190. {
  191. cur_size = ggml_quantize_q4_1(data_f32.data(), work.data(), nelements, ne[0], QK, hist_cur.data());
  192. } break;
  193. default:
  194. {
  195. fprintf(stderr, "%s: unsupported quantization type %d\n", __func__, type);
  196. return false;
  197. }
  198. }
  199. fout.write(reinterpret_cast<char *>(work.data()), cur_size);
  200. total_size_new += cur_size;
  201. printf("size = %8.2f MB -> %8.2f MB | hist: ", nelements * sizeof(float)/1024.0/1024.0, cur_size/1024.0/1024.0);
  202. for (int i = 0; i < hist_cur.size(); ++i) {
  203. hist_all[i] += hist_cur[i];
  204. }
  205. for (int i = 0; i < hist_cur.size(); ++i) {
  206. printf("%5.3f ", hist_cur[i] / (float)nelements);
  207. }
  208. printf("\n");
  209. } else {
  210. printf("size = %8.3f MB\n", data_u8.size()/1024.0/1024.0);
  211. fout.write(reinterpret_cast<char *>(data_u8.data()), data_u8.size());
  212. total_size_new += data_u8.size();
  213. }
  214. total_size_org += nelements * sizeof(float);
  215. }
  216. printf("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  217. printf("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  218. {
  219. int64_t sum_all = 0;
  220. for (int i = 0; i < hist_all.size(); ++i) {
  221. sum_all += hist_all[i];
  222. }
  223. printf("%s: hist: ", __func__);
  224. for (int i = 0; i < hist_all.size(); ++i) {
  225. printf("%5.3f ", hist_all[i] / (float)sum_all);
  226. }
  227. printf("\n");
  228. }
  229. }
  230. finp.close();
  231. fout.close();
  232. return true;
  233. }
  234. // usage:
  235. // ./llama-quantize models/llama/ggml-model.bin models/llama/ggml-model-quant.bin type
  236. //
  237. int main(int argc, char ** argv) {
  238. ggml_time_init();
  239. if (argc != 4) {
  240. fprintf(stderr, "usage: %s model-f32.bin model-quant.bin type\n", argv[0]);
  241. fprintf(stderr, " type = 2 - q4_0\n");
  242. fprintf(stderr, " type = 3 - q4_1\n");
  243. return 1;
  244. }
  245. // needed to initialize f16 tables
  246. {
  247. struct ggml_init_params params = { 0, NULL };
  248. struct ggml_context * ctx = ggml_init(params);
  249. ggml_free(ctx);
  250. }
  251. const std::string fname_inp = argv[1];
  252. const std::string fname_out = argv[2];
  253. const int itype = atoi(argv[3]);
  254. const int64_t t_main_start_us = ggml_time_us();
  255. int64_t t_quantize_us = 0;
  256. // load the model
  257. {
  258. const int64_t t_start_us = ggml_time_us();
  259. if (!llama_model_quantize(fname_inp, fname_out, itype)) {
  260. fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str());
  261. return 1;
  262. }
  263. t_quantize_us = ggml_time_us() - t_start_us;
  264. }
  265. // report timing
  266. {
  267. const int64_t t_main_end_us = ggml_time_us();
  268. printf("\n");
  269. printf("%s: quantize time = %8.2f ms\n", __func__, t_quantize_us/1000.0f);
  270. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
  271. }
  272. return 0;
  273. }