quantize.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "gguf.h"
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <vector>
  7. #include <string>
  8. #include <unordered_map>
  9. #include <map>
  10. #include <fstream>
  11. #include <cmath>
  12. #include <cctype>
  13. #include <algorithm>
  14. struct quant_option {
  15. std::string name;
  16. llama_ftype ftype;
  17. std::string desc;
  18. };
  19. static const std::vector<quant_option> QUANT_OPTIONS = {
  20. { "Q4_0", LLAMA_FTYPE_MOSTLY_Q4_0, " 4.34G, +0.4685 ppl @ Llama-3-8B", },
  21. { "Q4_1", LLAMA_FTYPE_MOSTLY_Q4_1, " 4.78G, +0.4511 ppl @ Llama-3-8B", },
  22. { "MXFP4_MOE",LLAMA_FTYPE_MOSTLY_MXFP4_MOE," MXFP4 MoE", },
  23. { "Q5_0", LLAMA_FTYPE_MOSTLY_Q5_0, " 5.21G, +0.1316 ppl @ Llama-3-8B", },
  24. { "Q5_1", LLAMA_FTYPE_MOSTLY_Q5_1, " 5.65G, +0.1062 ppl @ Llama-3-8B", },
  25. { "IQ2_XXS", LLAMA_FTYPE_MOSTLY_IQ2_XXS, " 2.06 bpw quantization", },
  26. { "IQ2_XS", LLAMA_FTYPE_MOSTLY_IQ2_XS, " 2.31 bpw quantization", },
  27. { "IQ2_S", LLAMA_FTYPE_MOSTLY_IQ2_S, " 2.5 bpw quantization", },
  28. { "IQ2_M", LLAMA_FTYPE_MOSTLY_IQ2_M, " 2.7 bpw quantization", },
  29. { "IQ1_S", LLAMA_FTYPE_MOSTLY_IQ1_S, " 1.56 bpw quantization", },
  30. { "IQ1_M", LLAMA_FTYPE_MOSTLY_IQ1_M, " 1.75 bpw quantization", },
  31. { "TQ1_0", LLAMA_FTYPE_MOSTLY_TQ1_0, " 1.69 bpw ternarization", },
  32. { "TQ2_0", LLAMA_FTYPE_MOSTLY_TQ2_0, " 2.06 bpw ternarization", },
  33. { "Q2_K", LLAMA_FTYPE_MOSTLY_Q2_K, " 2.96G, +3.5199 ppl @ Llama-3-8B", },
  34. { "Q2_K_S", LLAMA_FTYPE_MOSTLY_Q2_K_S, " 2.96G, +3.1836 ppl @ Llama-3-8B", },
  35. { "IQ3_XXS", LLAMA_FTYPE_MOSTLY_IQ3_XXS, " 3.06 bpw quantization", },
  36. { "IQ3_S", LLAMA_FTYPE_MOSTLY_IQ3_S, " 3.44 bpw quantization", },
  37. { "IQ3_M", LLAMA_FTYPE_MOSTLY_IQ3_M, " 3.66 bpw quantization mix", },
  38. { "Q3_K", LLAMA_FTYPE_MOSTLY_Q3_K_M, "alias for Q3_K_M" },
  39. { "IQ3_XS", LLAMA_FTYPE_MOSTLY_IQ3_XS, " 3.3 bpw quantization", },
  40. { "Q3_K_S", LLAMA_FTYPE_MOSTLY_Q3_K_S, " 3.41G, +1.6321 ppl @ Llama-3-8B", },
  41. { "Q3_K_M", LLAMA_FTYPE_MOSTLY_Q3_K_M, " 3.74G, +0.6569 ppl @ Llama-3-8B", },
  42. { "Q3_K_L", LLAMA_FTYPE_MOSTLY_Q3_K_L, " 4.03G, +0.5562 ppl @ Llama-3-8B", },
  43. { "IQ4_NL", LLAMA_FTYPE_MOSTLY_IQ4_NL, " 4.50 bpw non-linear quantization", },
  44. { "IQ4_XS", LLAMA_FTYPE_MOSTLY_IQ4_XS, " 4.25 bpw non-linear quantization", },
  45. { "Q4_K", LLAMA_FTYPE_MOSTLY_Q4_K_M, "alias for Q4_K_M", },
  46. { "Q4_K_S", LLAMA_FTYPE_MOSTLY_Q4_K_S, " 4.37G, +0.2689 ppl @ Llama-3-8B", },
  47. { "Q4_K_M", LLAMA_FTYPE_MOSTLY_Q4_K_M, " 4.58G, +0.1754 ppl @ Llama-3-8B", },
  48. { "Q5_K", LLAMA_FTYPE_MOSTLY_Q5_K_M, "alias for Q5_K_M", },
  49. { "Q5_K_S", LLAMA_FTYPE_MOSTLY_Q5_K_S, " 5.21G, +0.1049 ppl @ Llama-3-8B", },
  50. { "Q5_K_M", LLAMA_FTYPE_MOSTLY_Q5_K_M, " 5.33G, +0.0569 ppl @ Llama-3-8B", },
  51. { "Q6_K", LLAMA_FTYPE_MOSTLY_Q6_K, " 6.14G, +0.0217 ppl @ Llama-3-8B", },
  52. { "Q8_0", LLAMA_FTYPE_MOSTLY_Q8_0, " 7.96G, +0.0026 ppl @ Llama-3-8B", },
  53. { "F16", LLAMA_FTYPE_MOSTLY_F16, "14.00G, +0.0020 ppl @ Mistral-7B", },
  54. { "BF16", LLAMA_FTYPE_MOSTLY_BF16, "14.00G, -0.0050 ppl @ Mistral-7B", },
  55. { "F32", LLAMA_FTYPE_ALL_F32, "26.00G @ 7B", },
  56. // Note: Ensure COPY comes after F32 to avoid ftype 0 from matching.
  57. { "COPY", LLAMA_FTYPE_ALL_F32, "only copy tensors, no quantizing", },
  58. };
  59. // Quantization types. Changes to this struct must be replicated in llama-quantize.cpp
  60. struct tensor_quantization {
  61. std::string name;
  62. ggml_type quant = GGML_TYPE_COUNT;
  63. };
  64. static const char * const LLM_KV_QUANTIZE_IMATRIX_FILE = "quantize.imatrix.file";
  65. static const char * const LLM_KV_QUANTIZE_IMATRIX_DATASET = "quantize.imatrix.dataset";
  66. static const char * const LLM_KV_QUANTIZE_IMATRIX_N_ENTRIES = "quantize.imatrix.entries_count";
  67. static const char * const LLM_KV_QUANTIZE_IMATRIX_N_CHUNKS = "quantize.imatrix.chunks_count";
  68. // TODO: share with imatrix.cpp
  69. static const char * const LLM_KV_IMATRIX_DATASETS = "imatrix.datasets";
  70. static const char * const LLM_KV_IMATRIX_CHUNK_COUNT = "imatrix.chunk_count";
  71. static const char * const LLM_KV_IMATRIX_CHUNK_SIZE = "imatrix.chunk_size";
  72. static bool striequals(const char * a, const char * b) {
  73. while (*a && *b) {
  74. if (std::tolower(*a) != std::tolower(*b)) {
  75. return false;
  76. }
  77. a++; b++;
  78. }
  79. return *a == *b;
  80. }
  81. static bool try_parse_ftype(const std::string & ftype_str_in, llama_ftype & ftype, std::string & ftype_str_out) {
  82. std::string ftype_str;
  83. for (auto ch : ftype_str_in) {
  84. ftype_str.push_back(std::toupper(ch));
  85. }
  86. for (const auto & it : QUANT_OPTIONS) {
  87. if (striequals(it.name.c_str(), ftype_str.c_str())) {
  88. ftype = it.ftype;
  89. ftype_str_out = it.name;
  90. return true;
  91. }
  92. }
  93. try {
  94. int ftype_int = std::stoi(ftype_str);
  95. for (const auto & it : QUANT_OPTIONS) {
  96. if (it.ftype == ftype_int) {
  97. ftype = it.ftype;
  98. ftype_str_out = it.name;
  99. return true;
  100. }
  101. }
  102. }
  103. catch (...) {
  104. // stoi failed
  105. }
  106. return false;
  107. }
  108. [[noreturn]]
  109. static void usage(const char * executable) {
  110. printf("usage: %s [--help] [--allow-requantize] [--leave-output-tensor] [--pure] [--imatrix] [--include-weights]\n", executable);
  111. printf(" [--exclude-weights] [--output-tensor-type] [--token-embedding-type] [--tensor-type] [--prune-layers] [--keep-split] [--override-kv]\n");
  112. printf(" model-f32.gguf [model-quant.gguf] type [nthreads]\n\n");
  113. 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");
  114. printf(" --leave-output-tensor: Will leave output.weight un(re)quantized. Increases model size but may also increase quality, especially when requantizing\n");
  115. printf(" --pure: Disable k-quant mixtures and quantize all tensors to the same type\n");
  116. printf(" --imatrix file_name: use data in file_name as importance matrix for quant optimizations\n");
  117. printf(" --include-weights tensor_name: use importance matrix for this/these tensor(s)\n");
  118. printf(" --exclude-weights tensor_name: use importance matrix for this/these tensor(s)\n");
  119. printf(" --output-tensor-type ggml_type: use this ggml_type for the output.weight tensor\n");
  120. printf(" --token-embedding-type ggml_type: use this ggml_type for the token embeddings tensor\n");
  121. printf(" --tensor-type TENSOR=TYPE: quantize this tensor to this ggml_type. example: --tensor-type attn_q=q8_0\n");
  122. printf(" Advanced option to selectively quantize tensors. May be specified multiple times.\n");
  123. printf(" --prune-layers L0,L1,L2...comma-separated list of layer numbers to prune from the model\n");
  124. printf(" Advanced option to remove all tensors from the given layers\n");
  125. printf(" --keep-split: will generate quantized model in the same shards as input\n");
  126. printf(" --override-kv KEY=TYPE:VALUE\n");
  127. printf(" Advanced option to override model metadata by key in the quantized model. May be specified multiple times.\n");
  128. printf("Note: --include-weights and --exclude-weights cannot be used together\n");
  129. printf("\nAllowed quantization types:\n");
  130. for (const auto & it : QUANT_OPTIONS) {
  131. if (it.name != "COPY") {
  132. printf(" %2d or ", it.ftype);
  133. } else {
  134. printf(" ");
  135. }
  136. printf("%-7s : %s\n", it.name.c_str(), it.desc.c_str());
  137. }
  138. exit(1);
  139. }
  140. static int load_legacy_imatrix(const std::string & imatrix_file, std::vector<std::string> & imatrix_datasets, std::unordered_map<std::string, std::vector<float>> & imatrix_data) {
  141. std::ifstream in(imatrix_file.c_str(), std::ios::binary);
  142. if (!in) {
  143. printf("%s: failed to open %s\n",__func__, imatrix_file.c_str());
  144. exit(1);
  145. }
  146. int n_entries;
  147. in.read((char *)&n_entries, sizeof(n_entries));
  148. if (in.fail() || n_entries < 1) {
  149. printf("%s: no data in file %s\n", __func__, imatrix_file.c_str());
  150. exit(1);
  151. }
  152. for (int i = 0; i < n_entries; ++i) {
  153. int len; in.read((char *)&len, sizeof(len));
  154. std::vector<char> name_as_vec(len+1);
  155. in.read((char *)name_as_vec.data(), len);
  156. if (in.fail()) {
  157. printf("%s: failed reading name for entry %d from %s\n", __func__, i+1, imatrix_file.c_str());
  158. exit(1);
  159. }
  160. name_as_vec[len] = 0;
  161. std::string name{name_as_vec.data()};
  162. auto & e = imatrix_data[name];
  163. int ncall;
  164. in.read((char *)&ncall, sizeof(ncall));
  165. int nval;
  166. in.read((char *)&nval, sizeof(nval));
  167. if (in.fail() || nval < 1) {
  168. printf("%s: failed reading number of values for entry %d\n", __func__, i);
  169. imatrix_data = {};
  170. exit(1);
  171. }
  172. e.resize(nval);
  173. in.read((char *)e.data(), nval*sizeof(float));
  174. if (in.fail()) {
  175. printf("%s: failed reading data for entry %d\n", __func__, i);
  176. imatrix_data = {};
  177. exit(1);
  178. }
  179. if (ncall > 0) {
  180. for (auto & v : e) {
  181. v /= ncall;
  182. }
  183. }
  184. if (getenv("LLAMA_TRACE")) {
  185. printf("%s: loaded data (size = %6d, ncall = %6d) for '%s'\n", __func__, int(e.size()), ncall, name.c_str());
  186. }
  187. }
  188. // latest legacy imatrix version contains the dataset filename at the end of the file
  189. int m_last_call = 0;
  190. if (in.peek() != EOF) {
  191. in.read((char *)&m_last_call, sizeof(m_last_call));
  192. int dataset_len;
  193. in.read((char *)&dataset_len, sizeof(dataset_len));
  194. std::vector<char> dataset_as_vec(dataset_len);
  195. in.read(dataset_as_vec.data(), dataset_len);
  196. imatrix_datasets.resize(1);
  197. imatrix_datasets[0].assign(dataset_as_vec.begin(), dataset_as_vec.end());
  198. printf("%s: imatrix dataset='%s'\n", __func__, imatrix_datasets[0].c_str());
  199. }
  200. 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);
  201. return m_last_call;
  202. }
  203. static int load_imatrix(const std::string & imatrix_file, std::vector<std::string> & imatrix_datasets, std::unordered_map<std::string, std::vector<float>> & imatrix_data) {
  204. struct ggml_context * ctx = nullptr;
  205. struct gguf_init_params meta_gguf_params = {
  206. /* .no_alloc = */ false, // the data is needed
  207. /* .ctx = */ &ctx,
  208. };
  209. struct gguf_context * ctx_gguf = gguf_init_from_file(imatrix_file.c_str(), meta_gguf_params);
  210. if (!ctx_gguf) {
  211. fprintf(stderr, "%s: imatrix file '%s' is using old format\n", __func__, imatrix_file.c_str());
  212. return load_legacy_imatrix(imatrix_file, imatrix_datasets, imatrix_data);
  213. }
  214. const int32_t n_entries = gguf_get_n_tensors(ctx_gguf);
  215. if (n_entries < 1) {
  216. fprintf(stderr, "%s: no data in file %s\n", __func__, imatrix_file.c_str());
  217. gguf_free(ctx_gguf);
  218. ggml_free(ctx);
  219. exit(1);
  220. }
  221. const int dataset_idx = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_DATASETS);
  222. const int chunk_count_idx = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_CHUNK_COUNT);
  223. const int chunk_size_idx = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_CHUNK_SIZE);
  224. if (dataset_idx < 0 || chunk_count_idx < 0 || chunk_size_idx < 0) {
  225. fprintf(stderr, "%s: missing imatrix metadata in file %s\n", __func__, imatrix_file.c_str());
  226. gguf_free(ctx_gguf);
  227. ggml_free(ctx);
  228. exit(1);
  229. }
  230. const uint32_t chunk_size = gguf_get_val_u32(ctx_gguf, chunk_size_idx);
  231. const std::string sums_suffix{ ".in_sum2" };
  232. const std::string counts_suffix{ ".counts" };
  233. // Using an ordered map to get a deterministic iteration order.
  234. std::map<std::string, std::pair<struct ggml_tensor *, struct ggml_tensor *>> sums_counts_for;
  235. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  236. std::string name = cur->name;
  237. if (name.empty()) { continue; }
  238. if (string_remove_suffix(name, sums_suffix)) {
  239. // in_sum2
  240. sums_counts_for[std::move(name)].first = cur;
  241. } else if (string_remove_suffix(name, counts_suffix)) {
  242. // counts
  243. sums_counts_for[std::move(name)].second = cur;
  244. } else {
  245. // ignore other tensors
  246. }
  247. }
  248. for (const auto & sc : sums_counts_for) {
  249. const std::string & name = sc.first;
  250. const struct ggml_tensor * sums = sc.second.first;
  251. const struct ggml_tensor * counts = sc.second.second;
  252. if (!sums || !counts) {
  253. fprintf(stderr, "%s: mismatched sums and counts for %s\n", __func__, name.c_str());
  254. gguf_free(ctx_gguf);
  255. ggml_free(ctx);
  256. exit(1);
  257. }
  258. const int64_t ne0 = sums->ne[0];
  259. const int64_t ne1 = sums->ne[1];
  260. auto & e = imatrix_data[name];
  261. e.resize(ggml_nelements(sums));
  262. float max_count = 0.0f;
  263. for (int64_t j = 0; j < ne1; ++j) {
  264. const float count = ((const float *) counts->data)[j];
  265. if (count > 0.0f) {
  266. for (int64_t i = 0; i < ne0; ++i) {
  267. e[j*ne0 + i] = ((const float *) sums->data)[j*ne0 + i] / count;
  268. }
  269. } else {
  270. // Partial imatrix data, this tensor never got any input during calibration
  271. for (int64_t i = 0; i < ne0; ++i) {
  272. e[j*ne0 + i] = 1;
  273. }
  274. }
  275. if (count > max_count) {
  276. max_count = count;
  277. }
  278. }
  279. if (getenv("LLAMA_TRACE")) {
  280. printf("%s: loaded data (size = %6d, n_tokens = %6d, n_chunks = %6d) for '%s'\n", __func__, int(e.size()), int(max_count), int(max_count / chunk_size), name.c_str());
  281. }
  282. }
  283. int m_last_chunk = gguf_get_val_u32(ctx_gguf, chunk_count_idx);
  284. int64_t n_datasets = gguf_get_arr_n(ctx_gguf, dataset_idx);
  285. imatrix_datasets.reserve(n_datasets);
  286. for (int64_t i = 0; i < n_datasets; ++i) {
  287. imatrix_datasets.push_back(gguf_get_arr_str(ctx_gguf, dataset_idx, i));
  288. }
  289. printf("%s: imatrix datasets=['%s'", __func__, imatrix_datasets[0].c_str());
  290. for (size_t i = 1; i < imatrix_datasets.size(); ++i) {
  291. printf(", '%s'", imatrix_datasets[i].c_str());
  292. }
  293. printf("]\n");
  294. 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_chunk);
  295. gguf_free(ctx_gguf);
  296. ggml_free(ctx);
  297. return m_last_chunk;
  298. }
  299. static int prepare_imatrix(const std::string & imatrix_file,
  300. std::vector<std::string> & imatrix_dataset,
  301. const std::vector<std::string> & included_weights,
  302. const std::vector<std::string> & excluded_weights,
  303. std::unordered_map<std::string, std::vector<float>> & imatrix_data) {
  304. int m_last_call = -1;
  305. if (!imatrix_file.empty()) {
  306. m_last_call = load_imatrix(imatrix_file, imatrix_dataset, imatrix_data);
  307. }
  308. if (imatrix_data.empty()) {
  309. return m_last_call;
  310. }
  311. if (!excluded_weights.empty()) {
  312. for (const auto & name : excluded_weights) {
  313. for (auto it = imatrix_data.begin(); it != imatrix_data.end();) {
  314. auto pos = it->first.find(name);
  315. if (pos != std::string::npos) {
  316. it = imatrix_data.erase(it);
  317. } else {
  318. ++it;
  319. }
  320. }
  321. }
  322. }
  323. if (!included_weights.empty()) {
  324. std::unordered_map<std::string, std::vector<float>> tmp;
  325. for (const auto & name : included_weights) {
  326. for (auto & e : imatrix_data) {
  327. auto pos = e.first.find(name);
  328. if (pos != std::string::npos) {
  329. tmp.emplace(std::move(e));
  330. }
  331. }
  332. }
  333. imatrix_data = std::move(tmp);
  334. }
  335. if (!imatrix_data.empty()) {
  336. printf("%s: have %d importance matrix entries\n", __func__, int(imatrix_data.size()));
  337. }
  338. return m_last_call;
  339. }
  340. static ggml_type parse_ggml_type(const char * arg) {
  341. for (int i = 0; i < GGML_TYPE_COUNT; ++i) {
  342. auto type = (ggml_type)i;
  343. const auto * name = ggml_type_name(type);
  344. if (name && striequals(name, arg)) {
  345. return type;
  346. }
  347. }
  348. fprintf(stderr, "\n%s: invalid ggml_type '%s'\n\n", __func__, arg);
  349. return GGML_TYPE_COUNT;
  350. }
  351. static bool parse_tensor_type(const char * data, std::vector<tensor_quantization> & tensor_type) {
  352. const char * sep = strchr(data, '=');
  353. if (sep == nullptr) {
  354. printf("\n%s: malformed tensor type '%s'\n\n", __func__, data);
  355. return false;
  356. }
  357. const size_t tn_len = sep - data;
  358. if (tn_len == 0) {
  359. printf("\n%s: missing tensor name\n\n", __func__);
  360. return false;
  361. }
  362. if (const size_t qt_len = strlen(sep); qt_len == 1) {
  363. printf("\n%s: missing quantization type\n\n", __func__);
  364. return false;
  365. }
  366. std::string tn(data, tn_len);
  367. std::transform(tn.begin(), tn.end(), tn.begin(), tolower);
  368. sep++;
  369. tensor_quantization tqz;
  370. tqz.name = tn;
  371. tqz.quant = parse_ggml_type(sep);
  372. tensor_type.emplace_back(std::move(tqz));
  373. if (tqz.quant == GGML_TYPE_COUNT) {
  374. printf("\n%s: invalid quantization type '%s'\n\n", __func__, sep);
  375. return false;
  376. }
  377. return true;
  378. }
  379. static bool parse_layer_prune(const char * data, std::vector<int> & prune_layers) {
  380. if (!data) {
  381. printf("\n%s: no layer pruning ids provided\n\n", __func__);
  382. return false;
  383. }
  384. const auto block_ids = string_split<std::string>(data, ',');
  385. for (const auto & block_id : block_ids) {
  386. int id;
  387. try {
  388. id = std::stoi(block_id);
  389. } catch (...) {
  390. id = -1;
  391. }
  392. if (id < 0) {
  393. printf("\n%s: invalid layer id '%s'\n\n", __func__, block_id.c_str());
  394. return false;
  395. }
  396. prune_layers.emplace_back(id);
  397. }
  398. sort(prune_layers.begin(), prune_layers.end());
  399. prune_layers.erase(std::unique(prune_layers.begin(), prune_layers.end()), prune_layers.end());
  400. return true;
  401. }
  402. int main(int argc, char ** argv) {
  403. if (argc < 3) {
  404. usage(argv[0]);
  405. }
  406. llama_model_quantize_params params = llama_model_quantize_default_params();
  407. int arg_idx = 1;
  408. std::string imatrix_file;
  409. std::vector<std::string> included_weights, excluded_weights;
  410. std::vector<llama_model_kv_override> kv_overrides;
  411. std::vector<tensor_quantization> tensor_types;
  412. std::vector<int> prune_layers;
  413. for (; arg_idx < argc && strncmp(argv[arg_idx], "--", 2) == 0; arg_idx++) {
  414. if (strcmp(argv[arg_idx], "--leave-output-tensor") == 0) {
  415. params.quantize_output_tensor = false;
  416. } else if (strcmp(argv[arg_idx], "--output-tensor-type") == 0) {
  417. if (arg_idx < argc-1) {
  418. params.output_tensor_type = parse_ggml_type(argv[++arg_idx]);
  419. if (params.output_tensor_type == GGML_TYPE_COUNT) {
  420. usage(argv[0]);
  421. }
  422. } else {
  423. usage(argv[0]);
  424. }
  425. } else if (strcmp(argv[arg_idx], "--token-embedding-type") == 0) {
  426. if (arg_idx < argc-1) {
  427. params.token_embedding_type = parse_ggml_type(argv[++arg_idx]);
  428. if (params.token_embedding_type == GGML_TYPE_COUNT) {
  429. usage(argv[0]);
  430. }
  431. } else {
  432. usage(argv[0]);
  433. }
  434. } else if (strcmp(argv[arg_idx], "--tensor-type") == 0) {
  435. if (arg_idx == argc-1 || !parse_tensor_type(argv[++arg_idx], tensor_types)) {
  436. usage(argv[0]);
  437. }
  438. } else if (strcmp(argv[arg_idx], "--prune-layers") == 0) {
  439. if (arg_idx == argc-1 || !parse_layer_prune(argv[++arg_idx], prune_layers)) {
  440. usage(argv[0]);
  441. }
  442. } else if (strcmp(argv[arg_idx], "--override-kv") == 0) {
  443. if (arg_idx == argc-1 || !string_parse_kv_override(argv[++arg_idx], kv_overrides)) {
  444. usage(argv[0]);
  445. }
  446. } else if (strcmp(argv[arg_idx], "--allow-requantize") == 0) {
  447. params.allow_requantize = true;
  448. } else if (strcmp(argv[arg_idx], "--pure") == 0) {
  449. params.pure = true;
  450. } else if (strcmp(argv[arg_idx], "--imatrix") == 0) {
  451. if (arg_idx < argc-1) {
  452. imatrix_file = argv[++arg_idx];
  453. } else {
  454. usage(argv[0]);
  455. }
  456. } else if (strcmp(argv[arg_idx], "--include-weights") == 0) {
  457. if (arg_idx < argc-1) {
  458. included_weights.emplace_back(argv[++arg_idx]);
  459. } else {
  460. usage(argv[0]);
  461. }
  462. } else if (strcmp(argv[arg_idx], "--exclude-weights") == 0) {
  463. if (arg_idx < argc-1) {
  464. excluded_weights.emplace_back(argv[++arg_idx]);
  465. } else {
  466. usage(argv[0]);
  467. }
  468. } else if (strcmp(argv[arg_idx], "--keep-split") == 0) {
  469. params.keep_split = true;
  470. } else {
  471. usage(argv[0]);
  472. }
  473. }
  474. if (argc - arg_idx < 2) {
  475. printf("%s: bad arguments\n", argv[0]);
  476. usage(argv[0]);
  477. }
  478. if (!included_weights.empty() && !excluded_weights.empty()) {
  479. usage(argv[0]);
  480. }
  481. std::vector<std::string> imatrix_datasets;
  482. std::unordered_map<std::string, std::vector<float>> imatrix_data;
  483. int m_last_call = prepare_imatrix(imatrix_file, imatrix_datasets, included_weights, excluded_weights, imatrix_data);
  484. if (!imatrix_data.empty()) {
  485. params.imatrix = &imatrix_data;
  486. {
  487. llama_model_kv_override kvo;
  488. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_FILE);
  489. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  490. strncpy(kvo.val_str, imatrix_file.c_str(), 127);
  491. kvo.val_str[127] = '\0';
  492. kv_overrides.emplace_back(std::move(kvo));
  493. }
  494. if (!imatrix_datasets.empty()) {
  495. llama_model_kv_override kvo;
  496. // TODO: list multiple datasets when there are more than one
  497. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_DATASET);
  498. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  499. strncpy(kvo.val_str, imatrix_datasets[0].c_str(), 127);
  500. kvo.val_str[127] = '\0';
  501. kv_overrides.emplace_back(std::move(kvo));
  502. }
  503. {
  504. llama_model_kv_override kvo;
  505. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_N_ENTRIES);
  506. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  507. kvo.val_i64 = imatrix_data.size();
  508. kv_overrides.emplace_back(std::move(kvo));
  509. }
  510. if (m_last_call > 0) {
  511. llama_model_kv_override kvo;
  512. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_N_CHUNKS);
  513. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  514. kvo.val_i64 = m_last_call;
  515. kv_overrides.emplace_back(std::move(kvo));
  516. }
  517. }
  518. if (!kv_overrides.empty()) {
  519. kv_overrides.emplace_back();
  520. kv_overrides.back().key[0] = 0;
  521. params.kv_overrides = &kv_overrides;
  522. }
  523. if (!tensor_types.empty()) {
  524. params.tensor_types = &tensor_types;
  525. }
  526. if (!prune_layers.empty()) {
  527. params.prune_layers = &prune_layers;
  528. }
  529. llama_backend_init();
  530. // parse command line arguments
  531. const std::string fname_inp = argv[arg_idx];
  532. arg_idx++;
  533. std::string fname_out;
  534. std::string ftype_str;
  535. std::string suffix = ".gguf";
  536. if (try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) {
  537. std::string fpath;
  538. const size_t pos = fname_inp.find_last_of("/\\");
  539. if (pos != std::string::npos) {
  540. fpath = fname_inp.substr(0, pos + 1);
  541. }
  542. // export as [inp path]/ggml-model-[ftype]. Only add extension if there is no splitting
  543. fname_out = fpath + "ggml-model-" + ftype_str;
  544. if (!params.keep_split) {
  545. fname_out += suffix;
  546. }
  547. arg_idx++;
  548. if (ftype_str == "COPY") {
  549. params.only_copy = true;
  550. }
  551. } else {
  552. fname_out = argv[arg_idx];
  553. if (params.keep_split && fname_out.find(suffix) != std::string::npos) {
  554. fname_out = fname_out.substr(0, fname_out.length() - suffix.length());
  555. }
  556. arg_idx++;
  557. if (argc <= arg_idx) {
  558. fprintf(stderr, "%s: missing ftype\n", __func__);
  559. return 1;
  560. }
  561. if (!try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) {
  562. fprintf(stderr, "%s: invalid ftype '%s'\n", __func__, argv[arg_idx]);
  563. return 1;
  564. }
  565. if (ftype_str == "COPY") {
  566. params.only_copy = true;
  567. }
  568. arg_idx++;
  569. }
  570. // parse nthreads
  571. if (argc > arg_idx) {
  572. try {
  573. params.nthread = std::stoi(argv[arg_idx]);
  574. }
  575. catch (const std::exception & e) {
  576. fprintf(stderr, "%s: invalid nthread '%s' (%s)\n", __func__, argv[arg_idx], e.what());
  577. return 1;
  578. }
  579. }
  580. if ((params.ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || params.ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS ||
  581. params.ftype == LLAMA_FTYPE_MOSTLY_IQ2_S ||
  582. params.ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S ||
  583. params.ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  584. params.ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) && imatrix_data.empty()) {
  585. fprintf(stderr, "\n==========================================================================================================\n");
  586. 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");
  587. fprintf(stderr, "==========================================================================================================\n\n\n");
  588. return 1;
  589. }
  590. print_build_info();
  591. fprintf(stderr, "%s: quantizing '%s' to '%s' as %s", __func__, fname_inp.c_str(), fname_out.c_str(), ftype_str.c_str());
  592. if (params.nthread > 0) {
  593. fprintf(stderr, " using %d threads", params.nthread);
  594. }
  595. fprintf(stderr, "\n");
  596. const int64_t t_main_start_us = llama_time_us();
  597. int64_t t_quantize_us = 0;
  598. // load the model
  599. {
  600. const int64_t t_start_us = llama_time_us();
  601. if (llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), &params)) {
  602. fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str());
  603. return 1;
  604. }
  605. t_quantize_us = llama_time_us() - t_start_us;
  606. }
  607. // report timing
  608. {
  609. const int64_t t_main_end_us = llama_time_us();
  610. printf("\n");
  611. printf("%s: quantize time = %8.2f ms\n", __func__, t_quantize_us/1000.0);
  612. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0);
  613. }
  614. llama_backend_free();
  615. return 0;
  616. }