quantize.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. #include "ggml.h"
  2. #include "utils.h"
  3. #include <cassert>
  4. #include <cinttypes>
  5. #include <cmath>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <fstream>
  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. llama_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 == FILE_MAGIC_UNVERSIONED) {
  54. fprintf(stderr, "%s: invalid model file '%s' (too old, regenerate your model files!)\n",
  55. __func__, fname_inp.c_str());
  56. return false;
  57. }
  58. if (magic != FILE_MAGIC) {
  59. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname_inp.c_str());
  60. return false;
  61. }
  62. fout.write((char *) &magic, sizeof(magic));
  63. uint32_t format_version;
  64. finp.read((char *) &format_version, sizeof(format_version));
  65. if (format_version != FILE_VERSION) {
  66. fprintf(stderr, "%s: invalid model file '%s' (unsupported format version %" PRIu32 ", expected %d)\n",
  67. __func__, fname_inp.c_str(), format_version, FILE_VERSION);
  68. return false;
  69. }
  70. fout.write((char *) &format_version, sizeof(format_version));
  71. }
  72. llama_hparams hparams;
  73. // load hparams
  74. {
  75. finp.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  76. //finp.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  77. finp.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  78. finp.read((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  79. finp.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  80. finp.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  81. finp.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  82. finp.read((char *) &hparams.f16, sizeof(hparams.f16));
  83. printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  84. printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  85. printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
  86. printf("%s: n_mult = %d\n", __func__, hparams.n_mult);
  87. printf("%s: n_head = %d\n", __func__, hparams.n_head);
  88. printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
  89. printf("%s: f16 = %d\n", __func__, hparams.f16);
  90. fout.write((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  91. //fout.write((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  92. fout.write((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  93. fout.write((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  94. fout.write((char *) &hparams.n_head, sizeof(hparams.n_head));
  95. fout.write((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  96. fout.write((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  97. fout.write((char *) &itype, sizeof(hparams.f16));
  98. }
  99. // load vocab
  100. {
  101. const int32_t n_vocab = hparams.n_vocab;
  102. if (n_vocab != hparams.n_vocab) {
  103. fprintf(stderr, "%s: invalid model file '%s' (bad vocab size %d != %d)\n",
  104. __func__, fname_inp.c_str(), n_vocab, hparams.n_vocab);
  105. return false;
  106. }
  107. std::string word;
  108. vocab.id_to_token.resize(n_vocab);
  109. for (int i = 0; i < n_vocab; i++) {
  110. uint32_t len;
  111. finp.read ((char *) &len, sizeof(len));
  112. fout.write((char *) &len, sizeof(len));
  113. word.resize(len);
  114. finp.read ((char *) word.data(), len);
  115. fout.write((char *) word.data(), len);
  116. float score;
  117. finp.read ((char *) &score, sizeof(score));
  118. fout.write((char *) &score, sizeof(score));
  119. vocab.token_to_id[word] = i;
  120. auto &tok_score = vocab.id_to_token[i];
  121. tok_score.tok = word;
  122. tok_score.score = score;
  123. }
  124. }
  125. // load weights
  126. {
  127. size_t total_size_org = 0;
  128. size_t total_size_new = 0;
  129. std::vector<float> work;
  130. std::vector<uint8_t> data_u8;
  131. std::vector<ggml_fp16_t> data_f16;
  132. std::vector<float> data_f32;
  133. std::vector<int64_t> hist_all(1 << 4, 0);
  134. while (true) {
  135. int32_t n_dims;
  136. int32_t length;
  137. int32_t ftype;
  138. finp.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  139. finp.read(reinterpret_cast<char *>(&length), sizeof(length));
  140. finp.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  141. if (finp.eof()) {
  142. break;
  143. }
  144. int32_t nelements = 1;
  145. int32_t ne[2] = { 1, 1 };
  146. for (int i = 0; i < n_dims; ++i) {
  147. finp.read (reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  148. nelements *= ne[i];
  149. }
  150. std::string name(length, 0);
  151. finp.read (&name[0], length);
  152. {
  153. static const char * ftype_str[] = { "f32", "f16", "q4_0", "q4_1", };
  154. printf("%48s - [%5d, %5d], type = %6s ", name.data(), ne[0], ne[1], ftype_str[ftype]);
  155. }
  156. // regexes of tensor names to be quantized
  157. const std::vector<std::string> k_names = {
  158. ".*weight",
  159. };
  160. bool quantize = false;
  161. for (const auto & s : k_names) {
  162. if (std::regex_match(name, std::regex(s))) {
  163. quantize = true;
  164. break;
  165. }
  166. }
  167. // quantize only 2D tensors
  168. quantize &= (n_dims == 2);
  169. if (quantize) {
  170. if (ftype != 0 && ftype != 1) {
  171. fprintf(stderr, "%s: unsupported ftype %d for integer quantization\n", __func__, ftype);
  172. return false;
  173. }
  174. if (ftype == 1) {
  175. data_f16.resize(nelements);
  176. finp.read(reinterpret_cast<char *>(data_f16.data()), nelements * sizeof(ggml_fp16_t));
  177. data_f32.resize(nelements);
  178. for (int i = 0; i < nelements; ++i) {
  179. data_f32[i] = ggml_fp16_to_fp32(data_f16[i]);
  180. }
  181. } else {
  182. data_f32.resize(nelements);
  183. finp.read(reinterpret_cast<char *>(data_f32.data()), nelements * sizeof(float));
  184. }
  185. ftype = itype;
  186. } else {
  187. const int bpe = (ftype == 0) ? sizeof(float) : sizeof(uint16_t);
  188. data_u8.resize(nelements*bpe);
  189. finp.read(reinterpret_cast<char *>(data_u8.data()), nelements * bpe);
  190. }
  191. fout.write(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  192. fout.write(reinterpret_cast<char *>(&length), sizeof(length));
  193. fout.write(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  194. for (int i = 0; i < n_dims; ++i) {
  195. fout.write(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  196. }
  197. fout.write(&name[0], length);
  198. if (quantize) {
  199. printf("quantizing .. ");
  200. work.resize(nelements); // for quantization
  201. size_t cur_size = 0;
  202. std::vector<int64_t> hist_cur(1 << 4, 0);
  203. switch (type) {
  204. case GGML_TYPE_Q4_0:
  205. {
  206. cur_size = ggml_quantize_q4_0(data_f32.data(), work.data(), nelements, ne[0], QK, hist_cur.data());
  207. } break;
  208. case GGML_TYPE_Q4_1:
  209. {
  210. cur_size = ggml_quantize_q4_1(data_f32.data(), work.data(), nelements, ne[0], QK, hist_cur.data());
  211. } break;
  212. default:
  213. {
  214. fprintf(stderr, "%s: unsupported quantization type %d\n", __func__, type);
  215. return false;
  216. }
  217. }
  218. fout.write(reinterpret_cast<char *>(work.data()), cur_size);
  219. total_size_new += cur_size;
  220. printf("size = %8.2f MB -> %8.2f MB | hist: ", nelements * sizeof(float)/1024.0/1024.0, cur_size/1024.0/1024.0);
  221. for (int i = 0; i < hist_cur.size(); ++i) {
  222. hist_all[i] += hist_cur[i];
  223. }
  224. for (int i = 0; i < hist_cur.size(); ++i) {
  225. printf("%5.3f ", hist_cur[i] / (float)nelements);
  226. }
  227. printf("\n");
  228. } else {
  229. printf("size = %8.3f MB\n", data_u8.size()/1024.0/1024.0);
  230. fout.write(reinterpret_cast<char *>(data_u8.data()), data_u8.size());
  231. total_size_new += data_u8.size();
  232. }
  233. total_size_org += nelements * sizeof(float);
  234. }
  235. printf("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  236. printf("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  237. {
  238. int64_t sum_all = 0;
  239. for (int i = 0; i < hist_all.size(); ++i) {
  240. sum_all += hist_all[i];
  241. }
  242. printf("%s: hist: ", __func__);
  243. for (int i = 0; i < hist_all.size(); ++i) {
  244. printf("%5.3f ", hist_all[i] / (float)sum_all);
  245. }
  246. printf("\n");
  247. }
  248. }
  249. finp.close();
  250. fout.close();
  251. return true;
  252. }
  253. // usage:
  254. // ./llama-quantize models/llama/ggml-model.bin models/llama/ggml-model-quant.bin type
  255. //
  256. int main(int argc, char ** argv) {
  257. ggml_time_init();
  258. if (argc != 4) {
  259. fprintf(stderr, "usage: %s model-f32.bin model-quant.bin type\n", argv[0]);
  260. fprintf(stderr, " type = 2 - q4_0\n");
  261. fprintf(stderr, " type = 3 - q4_1\n");
  262. return 1;
  263. }
  264. // needed to initialize f16 tables
  265. {
  266. struct ggml_init_params params = { 0, NULL };
  267. struct ggml_context * ctx = ggml_init(params);
  268. ggml_free(ctx);
  269. }
  270. const std::string fname_inp = argv[1];
  271. const std::string fname_out = argv[2];
  272. const int itype = atoi(argv[3]);
  273. const int64_t t_main_start_us = ggml_time_us();
  274. int64_t t_quantize_us = 0;
  275. // load the model
  276. {
  277. const int64_t t_start_us = ggml_time_us();
  278. if (!llama_model_quantize(fname_inp, fname_out, itype)) {
  279. fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str());
  280. return 1;
  281. }
  282. t_quantize_us = ggml_time_us() - t_start_us;
  283. }
  284. // report timing
  285. {
  286. const int64_t t_main_end_us = ggml_time_us();
  287. printf("\n");
  288. printf("%s: quantize time = %8.2f ms\n", __func__, t_quantize_us/1000.0f);
  289. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
  290. }
  291. return 0;
  292. }