quantize.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <cstdio>
  4. #include <cstring>
  5. #include <vector>
  6. #include <string>
  7. #include <unordered_map>
  8. #include <fstream>
  9. #include <cmath>
  10. #include <algorithm>
  11. struct quant_option {
  12. std::string name;
  13. llama_ftype ftype;
  14. std::string desc;
  15. };
  16. static const std::vector<struct quant_option> QUANT_OPTIONS = {
  17. { "Q4_0", LLAMA_FTYPE_MOSTLY_Q4_0, " 3.56G, +0.2166 ppl @ LLaMA-v1-7B", },
  18. { "Q4_1", LLAMA_FTYPE_MOSTLY_Q4_1, " 3.90G, +0.1585 ppl @ LLaMA-v1-7B", },
  19. { "Q5_0", LLAMA_FTYPE_MOSTLY_Q5_0, " 4.33G, +0.0683 ppl @ LLaMA-v1-7B", },
  20. { "Q5_1", LLAMA_FTYPE_MOSTLY_Q5_1, " 4.70G, +0.0349 ppl @ LLaMA-v1-7B", },
  21. { "IQ2_XXS",LLAMA_FTYPE_MOSTLY_IQ2_XXS," 2.06 bpw quantization", },
  22. { "IQ2_XS", LLAMA_FTYPE_MOSTLY_IQ2_XS, " 2.31 bpw quantization", },
  23. { "Q2_K", LLAMA_FTYPE_MOSTLY_Q2_K, " 2.63G, +0.6717 ppl @ LLaMA-v1-7B", },
  24. { "Q2_K_S", LLAMA_FTYPE_MOSTLY_Q2_K_S, " 2.16G, +9.0634 ppl @ LLaMA-v1-7B", },
  25. { "IQ3_XXS",LLAMA_FTYPE_MOSTLY_IQ3_XXS," 3.06 bpw quantization", },
  26. { "Q3_K", LLAMA_FTYPE_MOSTLY_Q3_K_M, "alias for Q3_K_M" },
  27. { "Q3_K_XS",LLAMA_FTYPE_MOSTLY_Q3_K_XS,"3-bit extra small quantization" , },
  28. { "Q3_K_S", LLAMA_FTYPE_MOSTLY_Q3_K_S, " 2.75G, +0.5551 ppl @ LLaMA-v1-7B", },
  29. { "Q3_K_M", LLAMA_FTYPE_MOSTLY_Q3_K_M, " 3.07G, +0.2496 ppl @ LLaMA-v1-7B", },
  30. { "Q3_K_L", LLAMA_FTYPE_MOSTLY_Q3_K_L, " 3.35G, +0.1764 ppl @ LLaMA-v1-7B", },
  31. { "Q4_K", LLAMA_FTYPE_MOSTLY_Q4_K_M, "alias for Q4_K_M", },
  32. { "Q4_K_S", LLAMA_FTYPE_MOSTLY_Q4_K_S, " 3.59G, +0.0992 ppl @ LLaMA-v1-7B", },
  33. { "Q4_K_M", LLAMA_FTYPE_MOSTLY_Q4_K_M, " 3.80G, +0.0532 ppl @ LLaMA-v1-7B", },
  34. { "Q5_K", LLAMA_FTYPE_MOSTLY_Q5_K_M, "alias for Q5_K_M", },
  35. { "Q5_K_S", LLAMA_FTYPE_MOSTLY_Q5_K_S, " 4.33G, +0.0400 ppl @ LLaMA-v1-7B", },
  36. { "Q5_K_M", LLAMA_FTYPE_MOSTLY_Q5_K_M, " 4.45G, +0.0122 ppl @ LLaMA-v1-7B", },
  37. { "Q6_K", LLAMA_FTYPE_MOSTLY_Q6_K, " 5.15G, +0.0008 ppl @ LLaMA-v1-7B", },
  38. { "Q8_0", LLAMA_FTYPE_MOSTLY_Q8_0, " 6.70G, +0.0004 ppl @ LLaMA-v1-7B", },
  39. { "F16", LLAMA_FTYPE_MOSTLY_F16, "13.00G @ 7B", },
  40. { "F32", LLAMA_FTYPE_ALL_F32, "26.00G @ 7B", },
  41. // Note: Ensure COPY comes after F32 to avoid ftype 0 from matching.
  42. { "COPY", LLAMA_FTYPE_ALL_F32, "only copy tensors, no quantizing", },
  43. };
  44. static bool try_parse_ftype(const std::string & ftype_str_in, llama_ftype & ftype, std::string & ftype_str_out) {
  45. std::string ftype_str;
  46. for (auto ch : ftype_str_in) {
  47. ftype_str.push_back(std::toupper(ch));
  48. }
  49. for (auto & it : QUANT_OPTIONS) {
  50. if (it.name == ftype_str) {
  51. ftype = it.ftype;
  52. ftype_str_out = it.name;
  53. return true;
  54. }
  55. }
  56. try {
  57. int ftype_int = std::stoi(ftype_str);
  58. for (auto & it : QUANT_OPTIONS) {
  59. if (it.ftype == ftype_int) {
  60. ftype = it.ftype;
  61. ftype_str_out = it.name;
  62. return true;
  63. }
  64. }
  65. }
  66. catch (...) {
  67. // stoi failed
  68. }
  69. return false;
  70. }
  71. // usage:
  72. // ./quantize [--allow-requantize] [--leave-output-tensor] [--pure] models/llama/ggml-model.gguf [models/llama/ggml-model-quant.gguf] type [nthreads]
  73. //
  74. [[noreturn]]
  75. static void usage(const char * executable) {
  76. printf("usage: %s [--help] [--allow-requantize] [--leave-output-tensor] [--pure] [--imatrix] [--include-weights] [--exclude-weights] model-f32.gguf [model-quant.gguf] type [nthreads]\n\n", executable);
  77. printf(" --allow-requantize: Allows requantizing tensors that have already been quantized. Warning: This can severely reduce quality compared to quantizing from 16bit or 32bit\n");
  78. printf(" --leave-output-tensor: Will leave output.weight un(re)quantized. Increases model size but may also increase quality, especially when requantizing\n");
  79. printf(" --pure: Disable k-quant mixtures and quantize all tensors to the same type\n");
  80. printf(" --imatrix file_name: use data in file_name as importance matrix for quant optimizations\n");
  81. printf(" --include-weights tensor_name: use importance matrix for this/these tensor(s)\n");
  82. printf(" --exclude-weights tensor_name: use importance matrix for this/these tensor(s)\n");
  83. printf("Note: --include-weights and --exclude-weights cannot be used together\n");
  84. printf("\nAllowed quantization types:\n");
  85. for (auto & it : QUANT_OPTIONS) {
  86. if (it.name != "COPY") {
  87. printf(" %2d or ", it.ftype);
  88. } else {
  89. printf(" ");
  90. }
  91. printf("%-7s : %s\n", it.name.c_str(), it.desc.c_str());
  92. }
  93. exit(1);
  94. }
  95. static void load_imatrix(const std::string& imatrix_file, std::unordered_map<std::string, std::vector<float>>& imatrix_data) {
  96. std::ifstream in(imatrix_file.c_str(), std::ios::binary);
  97. if (!in) {
  98. printf("%s: failed to open %s\n",__func__,imatrix_file.c_str());
  99. return;
  100. }
  101. int n_entries;
  102. in.read((char*)&n_entries, sizeof(n_entries));
  103. if (in.fail() || n_entries < 1) {
  104. printf("%s: no data in file %s\n", __func__, imatrix_file.c_str());
  105. return;
  106. }
  107. for (int i = 0; i < n_entries; ++i) {
  108. int len; in.read((char *)&len, sizeof(len));
  109. std::vector<char> name_as_vec(len+1);
  110. in.read((char *)name_as_vec.data(), len);
  111. if (in.fail()) {
  112. printf("%s: failed reading name for entry %d from %s\n",__func__,i+1,imatrix_file.c_str());
  113. return;
  114. }
  115. name_as_vec[len] = 0;
  116. std::string name{name_as_vec.data()};
  117. auto& e = imatrix_data[std::move(name)];
  118. int ncall;
  119. in.read((char*)&ncall, sizeof(ncall));
  120. int nval;
  121. in.read((char *)&nval, sizeof(nval));
  122. if (in.fail() || nval < 1) {
  123. printf("%s: failed reading number of values for entry %d\n",__func__,i);
  124. imatrix_data = {};
  125. return;
  126. }
  127. e.resize(nval);
  128. in.read((char*)e.data(), nval*sizeof(float));
  129. if (in.fail()) {
  130. printf("%s: failed reading data for entry %d\n",__func__,i);
  131. imatrix_data = {};
  132. return;
  133. }
  134. if (ncall > 0) {
  135. for (auto& v : e) v /= ncall;
  136. }
  137. }
  138. printf("%s: loaded %d importance matrix entries from %s\n",__func__,int(imatrix_data.size()),imatrix_file.c_str());
  139. }
  140. static void prepare_imatrix(const std::string& imatrix_file,
  141. const std::vector<std::string>& included_weights,
  142. const std::vector<std::string>& excluded_weights,
  143. std::unordered_map<std::string, std::vector<float>>& imatrix_data) {
  144. if (!imatrix_file.empty()) {
  145. load_imatrix(imatrix_file, imatrix_data);
  146. }
  147. if (imatrix_data.empty()) {
  148. return;
  149. }
  150. if (!excluded_weights.empty()) {
  151. for (auto& name : excluded_weights) {
  152. for (auto it = imatrix_data.begin(); it != imatrix_data.end(); ) {
  153. auto pos = it->first.find(name);
  154. if (pos != std::string::npos) it = imatrix_data.erase(it);
  155. else ++it;
  156. }
  157. }
  158. }
  159. if (!included_weights.empty()) {
  160. std::unordered_map<std::string, std::vector<float>> tmp;
  161. for (auto& name : included_weights) {
  162. for (auto& e : imatrix_data) {
  163. auto pos = e.first.find(name);
  164. if (pos != std::string::npos) {
  165. tmp.emplace(std::move(e));
  166. }
  167. }
  168. }
  169. imatrix_data = std::move(tmp);
  170. }
  171. if (!imatrix_data.empty()) {
  172. printf("%s: have %d importance matrix entries\n", __func__, int(imatrix_data.size()));
  173. }
  174. }
  175. int main(int argc, char ** argv) {
  176. if (argc < 3) {
  177. usage(argv[0]);
  178. }
  179. llama_model_quantize_params params = llama_model_quantize_default_params();
  180. int arg_idx = 1;
  181. std::string imatrix_file;
  182. std::vector<std::string> included_weights, excluded_weights;
  183. for (; arg_idx < argc && strncmp(argv[arg_idx], "--", 2) == 0; arg_idx++) {
  184. if (strcmp(argv[arg_idx], "--leave-output-tensor") == 0) {
  185. params.quantize_output_tensor = false;
  186. } else if (strcmp(argv[arg_idx], "--allow-requantize") == 0) {
  187. params.allow_requantize = true;
  188. } else if (strcmp(argv[arg_idx], "--pure") == 0) {
  189. params.pure = true;
  190. } else if (strcmp(argv[arg_idx], "--imatrix") == 0) {
  191. if (arg_idx < argc-1) {
  192. imatrix_file = argv[++arg_idx];
  193. } else {
  194. usage(argv[0]);
  195. }
  196. } else if (strcmp(argv[arg_idx], "--include-weights") == 0) {
  197. if (arg_idx < argc-1) {
  198. included_weights.push_back(argv[++arg_idx]);
  199. } else {
  200. usage(argv[0]);
  201. }
  202. } else if (strcmp(argv[arg_idx], "--exclude-weights") == 0) {
  203. if (arg_idx < argc-1) {
  204. excluded_weights.push_back(argv[++arg_idx]);
  205. } else {
  206. usage(argv[0]);
  207. }
  208. } else {
  209. usage(argv[0]);
  210. }
  211. }
  212. if (argc - arg_idx < 2) {
  213. printf("%s: bad arguments\n", argv[0]);
  214. usage(argv[0]);
  215. }
  216. if (!included_weights.empty() && !excluded_weights.empty()) {
  217. usage(argv[0]);
  218. }
  219. std::unordered_map<std::string, std::vector<float>> imatrix_data;
  220. prepare_imatrix(imatrix_file, included_weights, excluded_weights, imatrix_data);
  221. if (!imatrix_data.empty()) {
  222. params.imatrix = &imatrix_data;
  223. }
  224. llama_backend_init(false);
  225. // parse command line arguments
  226. const std::string fname_inp = argv[arg_idx];
  227. arg_idx++;
  228. std::string fname_out;
  229. std::string ftype_str;
  230. if (try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) {
  231. std::string fpath;
  232. const size_t pos = fname_inp.find_last_of("/\\");
  233. if (pos != std::string::npos) {
  234. fpath = fname_inp.substr(0, pos + 1);
  235. }
  236. // export as [inp path]/ggml-model-[ftype].gguf
  237. fname_out = fpath + "ggml-model-" + ftype_str + ".gguf";
  238. arg_idx++;
  239. if (ftype_str == "COPY") {
  240. params.only_copy = true;
  241. }
  242. }
  243. else {
  244. fname_out = argv[arg_idx];
  245. arg_idx++;
  246. if (argc <= arg_idx) {
  247. fprintf(stderr, "%s: missing ftype\n", __func__);
  248. return 1;
  249. }
  250. if (!try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) {
  251. fprintf(stderr, "%s: invalid ftype '%s'\n", __func__, argv[3]);
  252. return 1;
  253. }
  254. if (ftype_str == "COPY") {
  255. params.only_copy = true;
  256. }
  257. arg_idx++;
  258. }
  259. // parse nthreads
  260. if (argc > arg_idx) {
  261. try {
  262. params.nthread = std::stoi(argv[arg_idx]);
  263. }
  264. catch (const std::exception & e) {
  265. fprintf(stderr, "%s: invalid nthread '%s' (%s)\n", __func__, argv[arg_idx], e.what());
  266. return 1;
  267. }
  268. }
  269. if ((params.ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || params.ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || params.ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) && imatrix_data.empty()) {
  270. fprintf(stderr, "\n===============================================================================================\n");
  271. fprintf(stderr, "Please do not use IQ2_XXS, IQ2_XS or Q2_K_S quantization without an importance matrix\n");
  272. fprintf(stderr, "===============================================================================================\n\n\n");
  273. return 1;
  274. }
  275. print_build_info();
  276. fprintf(stderr, "%s: quantizing '%s' to '%s' as %s", __func__, fname_inp.c_str(), fname_out.c_str(), ftype_str.c_str());
  277. if (params.nthread > 0) {
  278. fprintf(stderr, " using %d threads", params.nthread);
  279. }
  280. fprintf(stderr, "\n");
  281. const int64_t t_main_start_us = llama_time_us();
  282. int64_t t_quantize_us = 0;
  283. // load the model
  284. {
  285. const int64_t t_start_us = llama_time_us();
  286. if (llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), &params)) {
  287. fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str());
  288. return 1;
  289. }
  290. t_quantize_us = llama_time_us() - t_start_us;
  291. }
  292. // report timing
  293. {
  294. const int64_t t_main_end_us = llama_time_us();
  295. printf("\n");
  296. printf("%s: quantize time = %8.2f ms\n", __func__, t_quantize_us/1000.0);
  297. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0);
  298. }
  299. llama_backend_free();
  300. return 0;
  301. }