quantize.cpp 17 KB

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