quantize.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 <cctype>
  11. #include <algorithm>
  12. struct quant_option {
  13. std::string name;
  14. llama_ftype ftype;
  15. std::string desc;
  16. };
  17. static const std::vector<quant_option> QUANT_OPTIONS = {
  18. { "Q4_0", LLAMA_FTYPE_MOSTLY_Q4_0, " 4.34G, +0.4685 ppl @ Llama-3-8B", },
  19. { "Q4_1", LLAMA_FTYPE_MOSTLY_Q4_1, " 4.78G, +0.4511 ppl @ Llama-3-8B", },
  20. { "Q5_0", LLAMA_FTYPE_MOSTLY_Q5_0, " 5.21G, +0.1316 ppl @ Llama-3-8B", },
  21. { "Q5_1", LLAMA_FTYPE_MOSTLY_Q5_1, " 5.65G, +0.1062 ppl @ Llama-3-8B", },
  22. { "IQ2_XXS", LLAMA_FTYPE_MOSTLY_IQ2_XXS, " 2.06 bpw quantization", },
  23. { "IQ2_XS", LLAMA_FTYPE_MOSTLY_IQ2_XS, " 2.31 bpw quantization", },
  24. { "IQ2_S", LLAMA_FTYPE_MOSTLY_IQ2_S, " 2.5 bpw quantization", },
  25. { "IQ2_M", LLAMA_FTYPE_MOSTLY_IQ2_M, " 2.7 bpw quantization", },
  26. { "IQ1_S", LLAMA_FTYPE_MOSTLY_IQ1_S, " 1.56 bpw quantization", },
  27. { "IQ1_M", LLAMA_FTYPE_MOSTLY_IQ1_M, " 1.75 bpw quantization", },
  28. { "TQ1_0", LLAMA_FTYPE_MOSTLY_TQ1_0, " 1.69 bpw ternarization", },
  29. { "TQ2_0", LLAMA_FTYPE_MOSTLY_TQ2_0, " 2.06 bpw ternarization", },
  30. { "Q2_K", LLAMA_FTYPE_MOSTLY_Q2_K, " 2.96G, +3.5199 ppl @ Llama-3-8B", },
  31. { "Q2_K_S", LLAMA_FTYPE_MOSTLY_Q2_K_S, " 2.96G, +3.1836 ppl @ Llama-3-8B", },
  32. { "IQ3_XXS", LLAMA_FTYPE_MOSTLY_IQ3_XXS, " 3.06 bpw quantization", },
  33. { "IQ3_S", LLAMA_FTYPE_MOSTLY_IQ3_S, " 3.44 bpw quantization", },
  34. { "IQ3_M", LLAMA_FTYPE_MOSTLY_IQ3_M, " 3.66 bpw quantization mix", },
  35. { "Q3_K", LLAMA_FTYPE_MOSTLY_Q3_K_M, "alias for Q3_K_M" },
  36. { "IQ3_XS", LLAMA_FTYPE_MOSTLY_IQ3_XS, " 3.3 bpw quantization", },
  37. { "Q3_K_S", LLAMA_FTYPE_MOSTLY_Q3_K_S, " 3.41G, +1.6321 ppl @ Llama-3-8B", },
  38. { "Q3_K_M", LLAMA_FTYPE_MOSTLY_Q3_K_M, " 3.74G, +0.6569 ppl @ Llama-3-8B", },
  39. { "Q3_K_L", LLAMA_FTYPE_MOSTLY_Q3_K_L, " 4.03G, +0.5562 ppl @ Llama-3-8B", },
  40. { "IQ4_NL", LLAMA_FTYPE_MOSTLY_IQ4_NL, " 4.50 bpw non-linear quantization", },
  41. { "IQ4_XS", LLAMA_FTYPE_MOSTLY_IQ4_XS, " 4.25 bpw non-linear quantization", },
  42. { "Q4_K", LLAMA_FTYPE_MOSTLY_Q4_K_M, "alias for Q4_K_M", },
  43. { "Q4_K_S", LLAMA_FTYPE_MOSTLY_Q4_K_S, " 4.37G, +0.2689 ppl @ Llama-3-8B", },
  44. { "Q4_K_M", LLAMA_FTYPE_MOSTLY_Q4_K_M, " 4.58G, +0.1754 ppl @ Llama-3-8B", },
  45. { "Q5_K", LLAMA_FTYPE_MOSTLY_Q5_K_M, "alias for Q5_K_M", },
  46. { "Q5_K_S", LLAMA_FTYPE_MOSTLY_Q5_K_S, " 5.21G, +0.1049 ppl @ Llama-3-8B", },
  47. { "Q5_K_M", LLAMA_FTYPE_MOSTLY_Q5_K_M, " 5.33G, +0.0569 ppl @ Llama-3-8B", },
  48. { "Q6_K", LLAMA_FTYPE_MOSTLY_Q6_K, " 6.14G, +0.0217 ppl @ Llama-3-8B", },
  49. { "Q8_0", LLAMA_FTYPE_MOSTLY_Q8_0, " 7.96G, +0.0026 ppl @ Llama-3-8B", },
  50. { "F16", LLAMA_FTYPE_MOSTLY_F16, "14.00G, +0.0020 ppl @ Mistral-7B", },
  51. { "BF16", LLAMA_FTYPE_MOSTLY_BF16, "14.00G, -0.0050 ppl @ Mistral-7B", },
  52. { "F32", LLAMA_FTYPE_ALL_F32, "26.00G @ 7B", },
  53. // Note: Ensure COPY comes after F32 to avoid ftype 0 from matching.
  54. { "COPY", LLAMA_FTYPE_ALL_F32, "only copy tensors, no quantizing", },
  55. };
  56. static const char * const LLM_KV_QUANTIZE_IMATRIX_FILE = "quantize.imatrix.file";
  57. static const char * const LLM_KV_QUANTIZE_IMATRIX_DATASET = "quantize.imatrix.dataset";
  58. static const char * const LLM_KV_QUANTIZE_IMATRIX_N_ENTRIES = "quantize.imatrix.entries_count";
  59. static const char * const LLM_KV_QUANTIZE_IMATRIX_N_CHUNKS = "quantize.imatrix.chunks_count";
  60. static bool striequals(const char * a, const char * b) {
  61. while (*a && *b) {
  62. if (std::tolower(*a) != std::tolower(*b)) {
  63. return false;
  64. }
  65. a++; b++;
  66. }
  67. return *a == *b;
  68. }
  69. static bool try_parse_ftype(const std::string & ftype_str_in, llama_ftype & ftype, std::string & ftype_str_out) {
  70. std::string ftype_str;
  71. for (auto ch : ftype_str_in) {
  72. ftype_str.push_back(std::toupper(ch));
  73. }
  74. for (auto & it : QUANT_OPTIONS) {
  75. if (striequals(it.name.c_str(), ftype_str.c_str())) {
  76. ftype = it.ftype;
  77. ftype_str_out = it.name;
  78. return true;
  79. }
  80. }
  81. try {
  82. int ftype_int = std::stoi(ftype_str);
  83. for (auto & it : QUANT_OPTIONS) {
  84. if (it.ftype == ftype_int) {
  85. ftype = it.ftype;
  86. ftype_str_out = it.name;
  87. return true;
  88. }
  89. }
  90. }
  91. catch (...) {
  92. // stoi failed
  93. }
  94. return false;
  95. }
  96. // usage:
  97. // ./llama-quantize [--allow-requantize] [--leave-output-tensor] [--pure] models/llama/ggml-model.gguf [models/llama/ggml-model-quant.gguf] type [nthreads]
  98. //
  99. [[noreturn]]
  100. static void usage(const char * executable) {
  101. printf("usage: %s [--help] [--allow-requantize] [--leave-output-tensor] [--pure] [--imatrix] [--include-weights] [--exclude-weights] [--output-tensor-type]\n", executable);
  102. printf(" [--token-embedding-type] [--tensor-type] [--keep-split] [--override-kv] model-f32.gguf [model-quant.gguf] type [nthreads]\n\n");
  103. 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");
  104. printf(" --leave-output-tensor: Will leave output.weight un(re)quantized. Increases model size but may also increase quality, especially when requantizing\n");
  105. printf(" --pure: Disable k-quant mixtures and quantize all tensors to the same type\n");
  106. printf(" --imatrix file_name: use data in file_name as importance matrix for quant optimizations\n");
  107. printf(" --include-weights tensor_name: use importance matrix for this/these tensor(s)\n");
  108. printf(" --exclude-weights tensor_name: use importance matrix for this/these tensor(s)\n");
  109. printf(" --output-tensor-type ggml_type: use this ggml_type for the output.weight tensor\n");
  110. printf(" --token-embedding-type ggml_type: use this ggml_type for the token embeddings tensor\n");
  111. printf(" --tensor-type TENSOR=TYPE: quantize this tensor to this ggml_type. example: --tensor-type attn_q=q8_0\n");
  112. printf(" Advanced option to selectively quantize tensors. May be specified multiple times.\n");
  113. printf(" --keep-split: will generate quantized model in the same shards as input\n");
  114. printf(" --override-kv KEY=TYPE:VALUE\n");
  115. printf(" Advanced option to override model metadata by key in the quantized model. May be specified multiple times.\n");
  116. printf("Note: --include-weights and --exclude-weights cannot be used together\n");
  117. printf("\nAllowed quantization types:\n");
  118. for (auto & it : QUANT_OPTIONS) {
  119. if (it.name != "COPY") {
  120. printf(" %2d or ", it.ftype);
  121. } else {
  122. printf(" ");
  123. }
  124. printf("%-7s : %s\n", it.name.c_str(), it.desc.c_str());
  125. }
  126. exit(1);
  127. }
  128. static int load_imatrix(const std::string & imatrix_file, std::string & imatrix_dataset, std::unordered_map<std::string, std::vector<float>> & imatrix_data) {
  129. std::ifstream in(imatrix_file.c_str(), std::ios::binary);
  130. if (!in) {
  131. printf("%s: failed to open %s\n",__func__, imatrix_file.c_str());
  132. exit(1);
  133. }
  134. int n_entries;
  135. in.read((char *)&n_entries, sizeof(n_entries));
  136. if (in.fail() || n_entries < 1) {
  137. printf("%s: no data in file %s\n", __func__, imatrix_file.c_str());
  138. exit(1);
  139. }
  140. for (int i = 0; i < n_entries; ++i) {
  141. int len; in.read((char *)&len, sizeof(len));
  142. std::vector<char> name_as_vec(len+1);
  143. in.read((char *)name_as_vec.data(), len);
  144. if (in.fail()) {
  145. printf("%s: failed reading name for entry %d from %s\n", __func__, i+1, imatrix_file.c_str());
  146. exit(1);
  147. }
  148. name_as_vec[len] = 0;
  149. std::string name{name_as_vec.data()};
  150. auto & e = imatrix_data[name];
  151. int ncall;
  152. in.read((char *)&ncall, sizeof(ncall));
  153. int nval;
  154. in.read((char *)&nval, sizeof(nval));
  155. if (in.fail() || nval < 1) {
  156. printf("%s: failed reading number of values for entry %d\n", __func__, i);
  157. imatrix_data = {};
  158. exit(1);
  159. }
  160. e.resize(nval);
  161. in.read((char *)e.data(), nval*sizeof(float));
  162. if (in.fail()) {
  163. printf("%s: failed reading data for entry %d\n", __func__, i);
  164. imatrix_data = {};
  165. exit(1);
  166. }
  167. if (ncall > 0) {
  168. for (auto& v : e) v /= ncall;
  169. }
  170. if (getenv("LLAMA_TRACE")) {
  171. printf("%s: loaded data (size = %6d, ncall = %6d) for '%s'\n", __func__, int(e.size()), ncall, name.c_str());
  172. }
  173. }
  174. // latest imatrix version contains the dataset filename at the end of the file
  175. int m_last_call = 0;
  176. if (in.peek() != EOF) {
  177. in.read((char *)&m_last_call, sizeof(m_last_call));
  178. int dataset_len;
  179. in.read((char *)&dataset_len, sizeof(dataset_len));
  180. std::vector<char> dataset_as_vec(dataset_len);
  181. in.read(dataset_as_vec.data(), dataset_len);
  182. imatrix_dataset.assign(dataset_as_vec.begin(), dataset_as_vec.end());
  183. printf("%s: imatrix dataset='%s'\n", __func__, imatrix_dataset.c_str());
  184. }
  185. 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);
  186. return m_last_call;
  187. }
  188. static int prepare_imatrix(const std::string & imatrix_file,
  189. std::string & imatrix_dataset,
  190. const std::vector<std::string> & included_weights,
  191. const std::vector<std::string> & excluded_weights,
  192. std::unordered_map<std::string, std::vector<float>> & imatrix_data) {
  193. int m_last_call = -1;
  194. if (!imatrix_file.empty()) {
  195. m_last_call = load_imatrix(imatrix_file, imatrix_dataset, imatrix_data);
  196. }
  197. if (imatrix_data.empty()) {
  198. return m_last_call;
  199. }
  200. if (!excluded_weights.empty()) {
  201. for (auto& name : excluded_weights) {
  202. for (auto it = imatrix_data.begin(); it != imatrix_data.end(); ) {
  203. auto pos = it->first.find(name);
  204. if (pos != std::string::npos) it = imatrix_data.erase(it);
  205. else ++it;
  206. }
  207. }
  208. }
  209. if (!included_weights.empty()) {
  210. std::unordered_map<std::string, std::vector<float>> tmp;
  211. for (auto& name : included_weights) {
  212. for (auto& e : imatrix_data) {
  213. auto pos = e.first.find(name);
  214. if (pos != std::string::npos) {
  215. tmp.emplace(std::move(e));
  216. }
  217. }
  218. }
  219. imatrix_data = std::move(tmp);
  220. }
  221. if (!imatrix_data.empty()) {
  222. printf("%s: have %d importance matrix entries\n", __func__, int(imatrix_data.size()));
  223. }
  224. return m_last_call;
  225. }
  226. static ggml_type parse_ggml_type(const char * arg) {
  227. for (int i = 0; i < GGML_TYPE_COUNT; ++i) {
  228. auto type = (ggml_type)i;
  229. const auto * name = ggml_type_name(type);
  230. if (name && striequals(name, arg)) {
  231. return type;
  232. }
  233. }
  234. fprintf(stderr, "%s: invalid ggml_type '%s'\n", __func__, arg);
  235. return GGML_TYPE_COUNT;
  236. }
  237. // Allowed tensors for arbitrary quantization with --tensor-type option
  238. static const std::vector<std::string> ALLOWED_TENSOR_TYPE = {
  239. "attn_k",
  240. "attn_kv_a_mqa",
  241. "attn_kv_b",
  242. "attn_o",
  243. "attn_output",
  244. "attn_q",
  245. "attn_q_a",
  246. "attn_q_b",
  247. "attn_qkv",
  248. "attn_v",
  249. "channel_mix_key",
  250. "channel_mix_receptance",
  251. "channel_mix_value",
  252. "cls",
  253. "cls.output",
  254. "cross_attn_k",
  255. "cross_attn_o",
  256. "cross_attn_q",
  257. "cross_attn_v",
  258. "ffn_act",
  259. "ffn_down",
  260. "ffn_down_exps",
  261. "ffn_down_shexp",
  262. "ffn_gate",
  263. "ffn_gate_exps",
  264. "ffn_gate_shexp",
  265. "ffn_up",
  266. "ffn_up_exps",
  267. "ffn_up_shexp",
  268. "ssm_in",
  269. "ssm_out",
  270. "time_mix_gate",
  271. "time_mix_key",
  272. "time_mix_output",
  273. "time_mix_receptance",
  274. "time_mix_value",
  275. };
  276. // changes to this struct must be replicated in llama-quant.cpp
  277. struct tensor_quantization {
  278. std::string name;
  279. ggml_type quant = GGML_TYPE_COUNT;
  280. };
  281. static bool parse_tensor_type(const char * data, std::vector<tensor_quantization> & tensor_type) {
  282. const char * sep = strchr(data, '=');
  283. if (sep == nullptr) {
  284. printf("\n%s: malformed tensor type '%s'\n\n", __func__, data);
  285. return false;
  286. }
  287. const size_t tn_len = sep - data;
  288. if (tn_len == 0) {
  289. printf("\n%s: missing tensor name\n\n", __func__);
  290. return false;
  291. }
  292. if (const size_t qt_len = strlen(sep); qt_len == 1) {
  293. printf("\n%s: missing quantization type\n\n", __func__);
  294. return false;
  295. }
  296. std::string tn(data, tn_len);
  297. std::transform(tn.begin(), tn.end(), tn.begin(), tolower);
  298. sep++;
  299. const std::string qt(sep);
  300. bool found = false;
  301. for (const auto & allowed : ALLOWED_TENSOR_TYPE) {
  302. std::string tensor;
  303. tensor = tn.rfind('.') != std::string::npos ? tn.substr(tn.rfind('.') + 1) : tn;
  304. // handle special case of cls.output
  305. std::string cls_output = "cls.output";
  306. if (tn.find(cls_output) != std::string::npos) {
  307. tensor = "cls.output";
  308. }
  309. // check if an allowed tensor exists and it's at the end of the kv string
  310. if (tensor == allowed) {
  311. found = true;
  312. break;
  313. }
  314. }
  315. if (!found) {
  316. printf("\n%s: invalid tensor name '%s'\n\n", __func__, tn.c_str());
  317. return false;
  318. }
  319. if (parse_ggml_type(qt.c_str()) == GGML_TYPE_COUNT) {
  320. printf("\n%s: invalid quantization type '%s'\n\n", __func__, qt.c_str());
  321. return false;
  322. }
  323. tensor_quantization tqz;
  324. tqz.name = tn;
  325. tqz.quant = parse_ggml_type(qt.c_str());
  326. tensor_type.emplace_back(std::move(tqz));
  327. return true;
  328. }
  329. int main(int argc, char ** argv) {
  330. if (argc < 3) {
  331. usage(argv[0]);
  332. }
  333. llama_model_quantize_params params = llama_model_quantize_default_params();
  334. int arg_idx = 1;
  335. std::string imatrix_file;
  336. std::vector<std::string> included_weights, excluded_weights;
  337. std::vector<llama_model_kv_override> kv_overrides;
  338. std::vector<tensor_quantization> tensor_types;
  339. for (; arg_idx < argc && strncmp(argv[arg_idx], "--", 2) == 0; arg_idx++) {
  340. if (strcmp(argv[arg_idx], "--leave-output-tensor") == 0) {
  341. params.quantize_output_tensor = false;
  342. } else if (strcmp(argv[arg_idx], "--output-tensor-type") == 0) {
  343. if (arg_idx < argc-1) {
  344. params.output_tensor_type = parse_ggml_type(argv[++arg_idx]);
  345. if (params.output_tensor_type == GGML_TYPE_COUNT) {
  346. usage(argv[0]);
  347. }
  348. } else {
  349. usage(argv[0]);
  350. }
  351. } else if (strcmp(argv[arg_idx], "--token-embedding-type") == 0) {
  352. if (arg_idx < argc-1) {
  353. params.token_embedding_type = parse_ggml_type(argv[++arg_idx]);
  354. if (params.token_embedding_type == GGML_TYPE_COUNT) {
  355. usage(argv[0]);
  356. }
  357. } else {
  358. usage(argv[0]);
  359. }
  360. } else if (strcmp(argv[arg_idx], "--tensor-type") == 0) {
  361. if (arg_idx == argc-1 || !parse_tensor_type(argv[++arg_idx], tensor_types)) {
  362. usage(argv[0]);
  363. }
  364. } else if (strcmp(argv[arg_idx], "--override-kv") == 0) {
  365. if (arg_idx == argc-1 || !string_parse_kv_override(argv[++arg_idx], kv_overrides)) {
  366. usage(argv[0]);
  367. }
  368. } else if (strcmp(argv[arg_idx], "--allow-requantize") == 0) {
  369. params.allow_requantize = true;
  370. } else if (strcmp(argv[arg_idx], "--pure") == 0) {
  371. params.pure = true;
  372. } else if (strcmp(argv[arg_idx], "--imatrix") == 0) {
  373. if (arg_idx < argc-1) {
  374. imatrix_file = argv[++arg_idx];
  375. } else {
  376. usage(argv[0]);
  377. }
  378. } else if (strcmp(argv[arg_idx], "--include-weights") == 0) {
  379. if (arg_idx < argc-1) {
  380. included_weights.emplace_back(argv[++arg_idx]);
  381. } else {
  382. usage(argv[0]);
  383. }
  384. } else if (strcmp(argv[arg_idx], "--exclude-weights") == 0) {
  385. if (arg_idx < argc-1) {
  386. excluded_weights.emplace_back(argv[++arg_idx]);
  387. } else {
  388. usage(argv[0]);
  389. }
  390. } else if (strcmp(argv[arg_idx], "--keep-split") == 0) {
  391. params.keep_split = true;
  392. } else {
  393. usage(argv[0]);
  394. }
  395. }
  396. if (argc - arg_idx < 2) {
  397. printf("%s: bad arguments\n", argv[0]);
  398. usage(argv[0]);
  399. }
  400. if (!included_weights.empty() && !excluded_weights.empty()) {
  401. usage(argv[0]);
  402. }
  403. std::string imatrix_dataset;
  404. std::unordered_map<std::string, std::vector<float>> imatrix_data;
  405. int m_last_call = prepare_imatrix(imatrix_file, imatrix_dataset, included_weights, excluded_weights, imatrix_data);
  406. if (!imatrix_data.empty()) {
  407. params.imatrix = &imatrix_data;
  408. {
  409. llama_model_kv_override kvo;
  410. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_FILE);
  411. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  412. strncpy(kvo.val_str, imatrix_file.c_str(), 127);
  413. kvo.val_str[127] = '\0';
  414. kv_overrides.emplace_back(std::move(kvo));
  415. }
  416. if (!imatrix_dataset.empty()) {
  417. llama_model_kv_override kvo;
  418. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_DATASET);
  419. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  420. strncpy(kvo.val_str, imatrix_dataset.c_str(), 127);
  421. kvo.val_str[127] = '\0';
  422. kv_overrides.emplace_back(std::move(kvo));
  423. }
  424. {
  425. llama_model_kv_override kvo;
  426. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_N_ENTRIES);
  427. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  428. kvo.val_i64 = imatrix_data.size();
  429. kv_overrides.emplace_back(std::move(kvo));
  430. }
  431. if (m_last_call > 0) {
  432. llama_model_kv_override kvo;
  433. std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_N_CHUNKS);
  434. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  435. kvo.val_i64 = m_last_call;
  436. kv_overrides.emplace_back(std::move(kvo));
  437. }
  438. }
  439. if (!kv_overrides.empty()) {
  440. kv_overrides.emplace_back();
  441. kv_overrides.back().key[0] = 0;
  442. params.kv_overrides = &kv_overrides;
  443. }
  444. if (!tensor_types.empty()) {
  445. params.tensor_types = &tensor_types;
  446. }
  447. llama_backend_init();
  448. // parse command line arguments
  449. const std::string fname_inp = argv[arg_idx];
  450. arg_idx++;
  451. std::string fname_out;
  452. std::string ftype_str;
  453. std::string suffix = ".gguf";
  454. if (try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) {
  455. std::string fpath;
  456. const size_t pos = fname_inp.find_last_of("/\\");
  457. if (pos != std::string::npos) {
  458. fpath = fname_inp.substr(0, pos + 1);
  459. }
  460. // export as [inp path]/ggml-model-[ftype]. Only add extension if there is no splitting
  461. fname_out = fpath + "ggml-model-" + ftype_str;
  462. if (!params.keep_split) {
  463. fname_out += suffix;
  464. }
  465. arg_idx++;
  466. if (ftype_str == "COPY") {
  467. params.only_copy = true;
  468. }
  469. } else {
  470. fname_out = argv[arg_idx];
  471. if (params.keep_split && fname_out.find(suffix) != std::string::npos) {
  472. fname_out = fname_out.substr(0, fname_out.length() - suffix.length());
  473. }
  474. arg_idx++;
  475. if (argc <= arg_idx) {
  476. fprintf(stderr, "%s: missing ftype\n", __func__);
  477. return 1;
  478. }
  479. if (!try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) {
  480. fprintf(stderr, "%s: invalid ftype '%s'\n", __func__, argv[3]);
  481. return 1;
  482. }
  483. if (ftype_str == "COPY") {
  484. params.only_copy = true;
  485. }
  486. arg_idx++;
  487. }
  488. // parse nthreads
  489. if (argc > arg_idx) {
  490. try {
  491. params.nthread = std::stoi(argv[arg_idx]);
  492. }
  493. catch (const std::exception & e) {
  494. fprintf(stderr, "%s: invalid nthread '%s' (%s)\n", __func__, argv[arg_idx], e.what());
  495. return 1;
  496. }
  497. }
  498. if ((params.ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || params.ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS ||
  499. params.ftype == LLAMA_FTYPE_MOSTLY_IQ2_S ||
  500. params.ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S ||
  501. params.ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  502. params.ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) && imatrix_data.empty()) {
  503. fprintf(stderr, "\n==========================================================================================================\n");
  504. 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");
  505. fprintf(stderr, "==========================================================================================================\n\n\n");
  506. return 1;
  507. }
  508. print_build_info();
  509. fprintf(stderr, "%s: quantizing '%s' to '%s' as %s", __func__, fname_inp.c_str(), fname_out.c_str(), ftype_str.c_str());
  510. if (params.nthread > 0) {
  511. fprintf(stderr, " using %d threads", params.nthread);
  512. }
  513. fprintf(stderr, "\n");
  514. const int64_t t_main_start_us = llama_time_us();
  515. int64_t t_quantize_us = 0;
  516. // load the model
  517. {
  518. const int64_t t_start_us = llama_time_us();
  519. if (llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), &params)) {
  520. fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str());
  521. return 1;
  522. }
  523. t_quantize_us = llama_time_us() - t_start_us;
  524. }
  525. // report timing
  526. {
  527. const int64_t t_main_end_us = llama_time_us();
  528. printf("\n");
  529. printf("%s: quantize time = %8.2f ms\n", __func__, t_quantize_us/1000.0);
  530. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0);
  531. }
  532. llama_backend_free();
  533. return 0;
  534. }