quantize.cpp 12 KB

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