quantize.cpp 27 KB

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