quantize.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. struct quant_option {
  11. std::string name;
  12. llama_ftype ftype;
  13. std::string desc;
  14. };
  15. static const std::vector<struct quant_option> QUANT_OPTIONS = {
  16. { "Q4_0", LLAMA_FTYPE_MOSTLY_Q4_0, " 3.56G, +0.2166 ppl @ LLaMA-v1-7B", },
  17. { "Q4_1", LLAMA_FTYPE_MOSTLY_Q4_1, " 3.90G, +0.1585 ppl @ LLaMA-v1-7B", },
  18. { "Q5_0", LLAMA_FTYPE_MOSTLY_Q5_0, " 4.33G, +0.0683 ppl @ LLaMA-v1-7B", },
  19. { "Q5_1", LLAMA_FTYPE_MOSTLY_Q5_1, " 4.70G, +0.0349 ppl @ LLaMA-v1-7B", },
  20. { "IQ2_XXS",LLAMA_FTYPE_MOSTLY_IQ2_XXS," 2.06 bpw quantization", },
  21. { "IQ2_XS", LLAMA_FTYPE_MOSTLY_IQ2_XS, " 2.31 bpw quantization", },
  22. { "IQ2_S", LLAMA_FTYPE_MOSTLY_IQ2_S, " 2.5 bpw quantization", },
  23. { "IQ2_M", LLAMA_FTYPE_MOSTLY_IQ2_M, " 2.7 bpw quantization", },
  24. { "IQ1_S", LLAMA_FTYPE_MOSTLY_IQ1_S, " 1.56 bpw quantization", },
  25. { "IQ1_M", LLAMA_FTYPE_MOSTLY_IQ1_M, " 1.75 bpw quantization", },
  26. { "Q2_K", LLAMA_FTYPE_MOSTLY_Q2_K, " 2.63G, +0.6717 ppl @ LLaMA-v1-7B", },
  27. { "Q2_K_S", LLAMA_FTYPE_MOSTLY_Q2_K_S, " 2.16G, +9.0634 ppl @ LLaMA-v1-7B", },
  28. { "IQ3_XXS",LLAMA_FTYPE_MOSTLY_IQ3_XXS," 3.06 bpw quantization", },
  29. { "IQ3_S", LLAMA_FTYPE_MOSTLY_IQ3_S, " 3.44 bpw quantization", },
  30. { "IQ3_M", LLAMA_FTYPE_MOSTLY_IQ3_M, " 3.66 bpw quantization mix", },
  31. { "Q3_K", LLAMA_FTYPE_MOSTLY_Q3_K_M, "alias for Q3_K_M" },
  32. { "IQ3_XS", LLAMA_FTYPE_MOSTLY_IQ3_XS, " 3.3 bpw quantization" , },
  33. { "Q3_K_S", LLAMA_FTYPE_MOSTLY_Q3_K_S, " 2.75G, +0.5551 ppl @ LLaMA-v1-7B", },
  34. { "Q3_K_M", LLAMA_FTYPE_MOSTLY_Q3_K_M, " 3.07G, +0.2496 ppl @ LLaMA-v1-7B", },
  35. { "Q3_K_L", LLAMA_FTYPE_MOSTLY_Q3_K_L, " 3.35G, +0.1764 ppl @ LLaMA-v1-7B", },
  36. { "IQ4_NL", LLAMA_FTYPE_MOSTLY_IQ4_NL, " 4.50 bpw non-linear quantization", },
  37. { "IQ4_XS", LLAMA_FTYPE_MOSTLY_IQ4_XS, " 4.25 bpw non-linear quantization", },
  38. { "Q4_K", LLAMA_FTYPE_MOSTLY_Q4_K_M, "alias for Q4_K_M", },
  39. { "Q4_K_S", LLAMA_FTYPE_MOSTLY_Q4_K_S, " 3.59G, +0.0992 ppl @ LLaMA-v1-7B", },
  40. { "Q4_K_M", LLAMA_FTYPE_MOSTLY_Q4_K_M, " 3.80G, +0.0532 ppl @ LLaMA-v1-7B", },
  41. { "Q5_K", LLAMA_FTYPE_MOSTLY_Q5_K_M, "alias for Q5_K_M", },
  42. { "Q5_K_S", LLAMA_FTYPE_MOSTLY_Q5_K_S, " 4.33G, +0.0400 ppl @ LLaMA-v1-7B", },
  43. { "Q5_K_M", LLAMA_FTYPE_MOSTLY_Q5_K_M, " 4.45G, +0.0122 ppl @ LLaMA-v1-7B", },
  44. { "Q6_K", LLAMA_FTYPE_MOSTLY_Q6_K, " 5.15G, +0.0008 ppl @ LLaMA-v1-7B", },
  45. { "Q8_0", LLAMA_FTYPE_MOSTLY_Q8_0, " 6.70G, +0.0004 ppl @ LLaMA-v1-7B", },
  46. { "F16", LLAMA_FTYPE_MOSTLY_F16, "13.00G @ 7B", },
  47. { "F32", LLAMA_FTYPE_ALL_F32, "26.00G @ 7B", },
  48. // Note: Ensure COPY comes after F32 to avoid ftype 0 from matching.
  49. { "COPY", LLAMA_FTYPE_ALL_F32, "only copy tensors, no quantizing", },
  50. };
  51. static const char * const LLM_KV_QUANTIZE_IMATRIX_FILE = "quantize.imatrix.file";
  52. static const char * const LLM_KV_QUANTIZE_IMATRIX_DATASET = "quantize.imatrix.dataset";
  53. static const char * const LLM_KV_QUANTIZE_IMATRIX_N_ENTRIES = "quantize.imatrix.entries_count";
  54. static const char * const LLM_KV_QUANTIZE_IMATRIX_N_CHUNKS = "quantize.imatrix.chunks_count";
  55. static bool try_parse_ftype(const std::string & ftype_str_in, llama_ftype & ftype, std::string & ftype_str_out) {
  56. std::string ftype_str;
  57. for (auto ch : ftype_str_in) {
  58. ftype_str.push_back(std::toupper(ch));
  59. }
  60. for (auto & it : QUANT_OPTIONS) {
  61. if (it.name == ftype_str) {
  62. ftype = it.ftype;
  63. ftype_str_out = it.name;
  64. return true;
  65. }
  66. }
  67. try {
  68. int ftype_int = std::stoi(ftype_str);
  69. for (auto & it : QUANT_OPTIONS) {
  70. if (it.ftype == ftype_int) {
  71. ftype = it.ftype;
  72. ftype_str_out = it.name;
  73. return true;
  74. }
  75. }
  76. }
  77. catch (...) {
  78. // stoi failed
  79. }
  80. return false;
  81. }
  82. // usage:
  83. // ./quantize [--allow-requantize] [--leave-output-tensor] [--pure] models/llama/ggml-model.gguf [models/llama/ggml-model-quant.gguf] type [nthreads]
  84. //
  85. [[noreturn]]
  86. static void usage(const char * executable) {
  87. printf("usage: %s [--help] [--allow-requantize] [--leave-output-tensor] [--pure] [--imatrix] [--include-weights] [--exclude-weights] [--output-tensor-type] [--token-embedding-type] [--override-kv] model-f32.gguf [model-quant.gguf] type [nthreads]\n\n", executable);
  88. 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");
  89. printf(" --leave-output-tensor: Will leave output.weight un(re)quantized. Increases model size but may also increase quality, especially when requantizing\n");
  90. printf(" --pure: Disable k-quant mixtures and quantize all tensors to the same type\n");
  91. printf(" --imatrix file_name: use data in file_name as importance matrix for quant optimizations\n");
  92. printf(" --include-weights tensor_name: use importance matrix for this/these tensor(s)\n");
  93. printf(" --exclude-weights tensor_name: use importance matrix for this/these tensor(s)\n");
  94. printf(" --output-tensor-type ggml_type: use this ggml_type for the output.weight tensor\n");
  95. printf(" --token-embedding-type ggml_type: use this ggml_type for the token embeddings tensor\n");
  96. printf(" --keep-split: will generate quatized model in the same shards as input");
  97. printf(" --override-kv KEY=TYPE:VALUE\n");
  98. printf(" Advanced option to override model metadata by key in the quantized model. May be specified multiple times.\n");
  99. printf("Note: --include-weights and --exclude-weights cannot be used together\n");
  100. printf("\nAllowed quantization types:\n");
  101. for (auto & it : QUANT_OPTIONS) {
  102. if (it.name != "COPY") {
  103. printf(" %2d or ", it.ftype);
  104. } else {
  105. printf(" ");
  106. }
  107. printf("%-7s : %s\n", it.name.c_str(), it.desc.c_str());
  108. }
  109. exit(1);
  110. }
  111. static int load_imatrix(const std::string & imatrix_file, std::string & imatrix_dataset, std::unordered_map<std::string, std::vector<float>> & imatrix_data) {
  112. std::ifstream in(imatrix_file.c_str(), std::ios::binary);
  113. if (!in) {
  114. printf("%s: failed to open %s\n",__func__, imatrix_file.c_str());
  115. exit(1);
  116. }
  117. int n_entries;
  118. in.read((char *)&n_entries, sizeof(n_entries));
  119. if (in.fail() || n_entries < 1) {
  120. printf("%s: no data in file %s\n", __func__, imatrix_file.c_str());
  121. exit(1);
  122. }
  123. for (int i = 0; i < n_entries; ++i) {
  124. int len; in.read((char *)&len, sizeof(len));
  125. std::vector<char> name_as_vec(len+1);
  126. in.read((char *)name_as_vec.data(), len);
  127. if (in.fail()) {
  128. printf("%s: failed reading name for entry %d from %s\n", __func__, i+1, imatrix_file.c_str());
  129. exit(1);
  130. }
  131. name_as_vec[len] = 0;
  132. std::string name{name_as_vec.data()};
  133. auto & e = imatrix_data[name];
  134. int ncall;
  135. in.read((char *)&ncall, sizeof(ncall));
  136. int nval;
  137. in.read((char *)&nval, sizeof(nval));
  138. if (in.fail() || nval < 1) {
  139. printf("%s: failed reading number of values for entry %d\n", __func__, i);
  140. imatrix_data = {};
  141. exit(1);
  142. }
  143. e.resize(nval);
  144. in.read((char *)e.data(), nval*sizeof(float));
  145. if (in.fail()) {
  146. printf("%s: failed reading data for entry %d\n", __func__, i);
  147. imatrix_data = {};
  148. exit(1);
  149. }
  150. if (ncall > 0) {
  151. for (auto& v : e) v /= ncall;
  152. }
  153. if (getenv("LLAMA_TRACE")) {
  154. printf("%s: loaded data (size = %6d, ncall = %6d) for '%s'\n", __func__, int(e.size()), ncall, name.c_str());
  155. }
  156. }
  157. // latest imatrix version contains the dataset filename at the end of the file
  158. int m_last_call = 0;
  159. if (in.peek() != EOF) {
  160. in.read((char *)&m_last_call, sizeof(m_last_call));
  161. int dataset_len;
  162. in.read((char *)&dataset_len, sizeof(dataset_len));
  163. std::vector<char> dataset_as_vec(dataset_len);
  164. in.read(dataset_as_vec.data(), dataset_len);
  165. imatrix_dataset.assign(dataset_as_vec.begin(), dataset_as_vec.end());
  166. printf("%s: imatrix dataset='%s'\n", __func__, imatrix_dataset.c_str());
  167. }
  168. printf("%s: loaded %d importance matrix entries from %s computed on %d chunks\n", __func__, int(imatrix_data.size()), imatrix_file.c_str(), m_last_call);
  169. return m_last_call;
  170. }
  171. static int prepare_imatrix(const std::string & imatrix_file,
  172. std::string & imatrix_dataset,
  173. const std::vector<std::string> & included_weights,
  174. const std::vector<std::string> & excluded_weights,
  175. std::unordered_map<std::string, std::vector<float>> & imatrix_data) {
  176. int m_last_call = -1;
  177. if (!imatrix_file.empty()) {
  178. m_last_call = load_imatrix(imatrix_file, imatrix_dataset, imatrix_data);
  179. }
  180. if (imatrix_data.empty()) {
  181. return m_last_call;
  182. }
  183. if (!excluded_weights.empty()) {
  184. for (auto& name : excluded_weights) {
  185. for (auto it = imatrix_data.begin(); it != imatrix_data.end(); ) {
  186. auto pos = it->first.find(name);
  187. if (pos != std::string::npos) it = imatrix_data.erase(it);
  188. else ++it;
  189. }
  190. }
  191. }
  192. if (!included_weights.empty()) {
  193. std::unordered_map<std::string, std::vector<float>> tmp;
  194. for (auto& name : included_weights) {
  195. for (auto& e : imatrix_data) {
  196. auto pos = e.first.find(name);
  197. if (pos != std::string::npos) {
  198. tmp.emplace(std::move(e));
  199. }
  200. }
  201. }
  202. imatrix_data = std::move(tmp);
  203. }
  204. if (!imatrix_data.empty()) {
  205. printf("%s: have %d importance matrix entries\n", __func__, int(imatrix_data.size()));
  206. }
  207. return m_last_call;
  208. }
  209. static ggml_type parse_ggml_type(const char * arg) {
  210. ggml_type result = GGML_TYPE_COUNT;
  211. for (int j = 0; j < GGML_TYPE_COUNT; ++j) {
  212. auto type = ggml_type(j);
  213. const auto * name = ggml_type_name(type);
  214. if (name && strcmp(arg, name) == 0) {
  215. result = type; break;
  216. }
  217. }
  218. return result;
  219. }
  220. int main(int argc, char ** argv) {
  221. if (argc < 3) {
  222. usage(argv[0]);
  223. }
  224. llama_model_quantize_params params = llama_model_quantize_default_params();
  225. int arg_idx = 1;
  226. std::string imatrix_file;
  227. std::vector<std::string> included_weights, excluded_weights;
  228. std::vector<llama_model_kv_override> kv_overrides;
  229. for (; arg_idx < argc && strncmp(argv[arg_idx], "--", 2) == 0; arg_idx++) {
  230. if (strcmp(argv[arg_idx], "--leave-output-tensor") == 0) {
  231. params.quantize_output_tensor = false;
  232. } else if (strcmp(argv[arg_idx], "--output-tensor-type") == 0) {
  233. if (arg_idx < argc-1) {
  234. params.output_tensor_type = parse_ggml_type(argv[++arg_idx]);
  235. } else {
  236. usage(argv[0]);
  237. }
  238. } else if (strcmp(argv[arg_idx], "--token-embedding-type") == 0) {
  239. if (arg_idx < argc-1) {
  240. params.token_embedding_type = parse_ggml_type(argv[++arg_idx]);
  241. } else {
  242. usage(argv[0]);
  243. }
  244. } else if (strcmp(argv[arg_idx], "--override-kv") == 0) {
  245. if (arg_idx == argc-1 || !parse_kv_override(argv[++arg_idx], kv_overrides)) {
  246. usage(argv[0]);
  247. }
  248. } else if (strcmp(argv[arg_idx], "--allow-requantize") == 0) {
  249. params.allow_requantize = true;
  250. } else if (strcmp(argv[arg_idx], "--pure") == 0) {
  251. params.pure = true;
  252. } else if (strcmp(argv[arg_idx], "--imatrix") == 0) {
  253. if (arg_idx < argc-1) {
  254. imatrix_file = argv[++arg_idx];
  255. } else {
  256. usage(argv[0]);
  257. }
  258. } else if (strcmp(argv[arg_idx], "--include-weights") == 0) {
  259. if (arg_idx < argc-1) {
  260. included_weights.emplace_back(argv[++arg_idx]);
  261. } else {
  262. usage(argv[0]);
  263. }
  264. } else if (strcmp(argv[arg_idx], "--exclude-weights") == 0) {
  265. if (arg_idx < argc-1) {
  266. excluded_weights.emplace_back(argv[++arg_idx]);
  267. } else {
  268. usage(argv[0]);
  269. }
  270. } else if (strcmp(argv[arg_idx], "--keep-split")) {
  271. params.keep_split = true;
  272. } else {
  273. usage(argv[0]);
  274. }
  275. }
  276. if (argc - arg_idx < 2) {
  277. printf("%s: bad arguments\n", argv[0]);
  278. usage(argv[0]);
  279. }
  280. if (!included_weights.empty() && !excluded_weights.empty()) {
  281. usage(argv[0]);
  282. }
  283. std::string imatrix_dataset;
  284. std::unordered_map<std::string, std::vector<float>> imatrix_data;
  285. int m_last_call = prepare_imatrix(imatrix_file, imatrix_dataset, included_weights, excluded_weights, imatrix_data);
  286. if (!imatrix_data.empty()) {
  287. params.imatrix = &imatrix_data;
  288. {
  289. llama_model_kv_override kvo;
  290. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_FILE);
  291. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  292. strncpy(kvo.val_str, imatrix_file.c_str(), 127);
  293. kvo.val_str[127] = '\0';
  294. kv_overrides.emplace_back(std::move(kvo));
  295. }
  296. if (!imatrix_dataset.empty()) {
  297. llama_model_kv_override kvo;
  298. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_DATASET);
  299. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  300. strncpy(kvo.val_str, imatrix_dataset.c_str(), 127);
  301. kvo.val_str[127] = '\0';
  302. kv_overrides.emplace_back(std::move(kvo));
  303. }
  304. {
  305. llama_model_kv_override kvo;
  306. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_N_ENTRIES);
  307. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  308. kvo.val_i64 = imatrix_data.size();
  309. kv_overrides.emplace_back(std::move(kvo));
  310. }
  311. if (m_last_call > 0) {
  312. llama_model_kv_override kvo;
  313. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_N_CHUNKS);
  314. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  315. kvo.val_i64 = m_last_call;
  316. kv_overrides.emplace_back(std::move(kvo));
  317. }
  318. }
  319. if (!kv_overrides.empty()) {
  320. kv_overrides.emplace_back();
  321. kv_overrides.back().key[0] = 0;
  322. params.kv_overrides = &kv_overrides;
  323. }
  324. llama_backend_init();
  325. // parse command line arguments
  326. const std::string fname_inp = argv[arg_idx];
  327. arg_idx++;
  328. std::string fname_out;
  329. std::string ftype_str;
  330. std::string suffix = ".gguf";
  331. if (try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) {
  332. std::string fpath;
  333. const size_t pos = fname_inp.find_last_of("/\\");
  334. if (pos != std::string::npos) {
  335. fpath = fname_inp.substr(0, pos + 1);
  336. }
  337. // export as [inp path]/ggml-model-[ftype]. Only add extension if there is no splitting
  338. fname_out = fpath + "ggml-model-" + ftype_str;
  339. if (!params.keep_split) {
  340. fname_out += suffix;
  341. }
  342. arg_idx++;
  343. if (ftype_str == "COPY") {
  344. params.only_copy = true;
  345. }
  346. } else {
  347. fname_out = argv[arg_idx];
  348. if (params.keep_split && fname_out.find(suffix) != std::string::npos) {
  349. fname_out = fname_out.substr(0, fname_out.length() - suffix.length());
  350. }
  351. arg_idx++;
  352. if (argc <= arg_idx) {
  353. fprintf(stderr, "%s: missing ftype\n", __func__);
  354. return 1;
  355. }
  356. if (!try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) {
  357. fprintf(stderr, "%s: invalid ftype '%s'\n", __func__, argv[3]);
  358. return 1;
  359. }
  360. if (ftype_str == "COPY") {
  361. params.only_copy = true;
  362. }
  363. arg_idx++;
  364. }
  365. // parse nthreads
  366. if (argc > arg_idx) {
  367. try {
  368. params.nthread = std::stoi(argv[arg_idx]);
  369. }
  370. catch (const std::exception & e) {
  371. fprintf(stderr, "%s: invalid nthread '%s' (%s)\n", __func__, argv[arg_idx], e.what());
  372. return 1;
  373. }
  374. }
  375. if ((params.ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || params.ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS ||
  376. params.ftype == LLAMA_FTYPE_MOSTLY_IQ2_S ||
  377. params.ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S ||
  378. params.ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  379. params.ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) && imatrix_data.empty()) {
  380. fprintf(stderr, "\n==========================================================================================================\n");
  381. fprintf(stderr, "Please do not use IQ1_S, IQ1_M, IQ2_S, IQ2_XXS, IQ2_XS or Q2_K_S quantization without an importance matrix\n");
  382. fprintf(stderr, "==========================================================================================================\n\n\n");
  383. return 1;
  384. }
  385. print_build_info();
  386. fprintf(stderr, "%s: quantizing '%s' to '%s' as %s", __func__, fname_inp.c_str(), fname_out.c_str(), ftype_str.c_str());
  387. if (params.nthread > 0) {
  388. fprintf(stderr, " using %d threads", params.nthread);
  389. }
  390. fprintf(stderr, "\n");
  391. const int64_t t_main_start_us = llama_time_us();
  392. int64_t t_quantize_us = 0;
  393. // load the model
  394. {
  395. const int64_t t_start_us = llama_time_us();
  396. if (llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), &params)) {
  397. fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str());
  398. return 1;
  399. }
  400. t_quantize_us = llama_time_us() - t_start_us;
  401. }
  402. // report timing
  403. {
  404. const int64_t t_main_end_us = llama_time_us();
  405. printf("\n");
  406. printf("%s: quantize time = %8.2f ms\n", __func__, t_quantize_us/1000.0);
  407. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0);
  408. }
  409. llama_backend_free();
  410. return 0;
  411. }