llama-quant.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. /**
  2. * llama.cpp - commit 46e3556e01b824e52395fb050b29804b6cff2a7c - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #include "llama-quant.h"
  27. #include "llama-impl.h"
  28. #include "llama-model.h"
  29. #include "llama-model-loader.h"
  30. #include <algorithm>
  31. #include <cmath>
  32. #include <cstring>
  33. #include <fstream>
  34. #include <mutex>
  35. #include <thread>
  36. #include <unordered_map>
  37. // TODO: replace with ggml API call
  38. #define QK_K 256
  39. static void zeros(std::ofstream & file, size_t n) {
  40. char zero = 0;
  41. for (size_t i = 0; i < n; ++i) {
  42. file.write(&zero, 1);
  43. }
  44. }
  45. struct quantize_state_internal {
  46. const llama_model & model;
  47. const llama_model_quantize_params * params;
  48. int n_attention_wv = 0;
  49. int n_ffn_down = 0;
  50. int n_ffn_gate = 0;
  51. int n_ffn_up = 0;
  52. int i_attention_wv = 0;
  53. int i_ffn_down = 0;
  54. int i_ffn_gate = 0;
  55. int i_ffn_up = 0;
  56. int n_k_quantized = 0;
  57. int n_fallback = 0;
  58. bool has_imatrix = false;
  59. // used to figure out if a model shares tok_embd with the output weight
  60. bool has_output = false;
  61. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  62. : model(model)
  63. , params(params)
  64. {}
  65. };
  66. static void llama_tensor_dequantize_internal(
  67. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  68. const size_t nelements, const int nthread
  69. ) {
  70. if (output.size() < nelements) {
  71. output.resize(nelements);
  72. }
  73. float * f32_output = (float *) output.data();
  74. const ggml_type_traits * qtype = ggml_get_type_traits(tensor->type);
  75. if (ggml_is_quantized(tensor->type)) {
  76. if (qtype->to_float == NULL) {
  77. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  78. }
  79. } else if (tensor->type != GGML_TYPE_F16 &&
  80. tensor->type != GGML_TYPE_BF16) {
  81. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  82. }
  83. if (nthread < 2) {
  84. if (tensor->type == GGML_TYPE_F16) {
  85. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  86. } else if (tensor->type == GGML_TYPE_BF16) {
  87. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  88. } else if (ggml_is_quantized(tensor->type)) {
  89. qtype->to_float(tensor->data, f32_output, nelements);
  90. } else {
  91. GGML_ABORT("fatal error"); // unreachable
  92. }
  93. return;
  94. }
  95. size_t block_size;
  96. if (tensor->type == GGML_TYPE_F16 ||
  97. tensor->type == GGML_TYPE_BF16) {
  98. block_size = 1;
  99. } else {
  100. block_size = (size_t)ggml_blck_size(tensor->type);
  101. }
  102. size_t block_size_bytes = ggml_type_size(tensor->type);
  103. GGML_ASSERT(nelements % block_size == 0);
  104. size_t nblocks = nelements / block_size;
  105. size_t blocks_per_thread = nblocks / nthread;
  106. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  107. size_t in_buff_offs = 0;
  108. size_t out_buff_offs = 0;
  109. for (int tnum = 0; tnum < nthread; tnum++) {
  110. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  111. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  112. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  113. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  114. if (typ == GGML_TYPE_F16) {
  115. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  116. } else if (typ == GGML_TYPE_BF16) {
  117. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  118. } else {
  119. qtype->to_float(inbuf, outbuf, nels);
  120. }
  121. };
  122. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  123. in_buff_offs += thr_block_bytes;
  124. out_buff_offs += thr_elems;
  125. }
  126. for (auto & w : workers) { w.join(); }
  127. workers.clear();
  128. }
  129. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  130. const std::string name = ggml_get_name(tensor);
  131. // TODO: avoid hardcoded tensor names - use the TN_* constants
  132. const llm_arch arch = qs.model.arch;
  133. const auto tn = LLM_TN(arch);
  134. auto use_more_bits = [](int i_layer, int n_layers) -> bool {
  135. return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2;
  136. };
  137. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  138. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  139. if (n_expert > 1) {
  140. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but occasionally randomly
  141. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  142. // for getting the current layer as I initially thought, and we need to resort to parsing the
  143. // tensor name.
  144. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  145. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  146. }
  147. if (i_layer < 0 || i_layer >= n_layer) {
  148. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  149. }
  150. }
  151. return std::make_pair(i_layer, n_layer);
  152. };
  153. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  154. // with the quantization of the output tensor
  155. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  156. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  157. new_type = qs.params->output_tensor_type;
  158. } else {
  159. int nx = tensor->ne[0];
  160. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  161. new_type = GGML_TYPE_Q8_0;
  162. }
  163. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  164. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  165. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  166. new_type = GGML_TYPE_Q5_K;
  167. }
  168. else if (new_type != GGML_TYPE_Q8_0) {
  169. new_type = GGML_TYPE_Q6_K;
  170. }
  171. }
  172. } else if (name == "token_embd.weight") {
  173. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  174. new_type = qs.params->token_embedding_type;
  175. } else {
  176. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  177. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  178. new_type = GGML_TYPE_Q2_K;
  179. }
  180. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  181. new_type = GGML_TYPE_IQ3_S;
  182. }
  183. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  184. new_type = GGML_TYPE_IQ3_S;
  185. }
  186. else if (ftype == LLAMA_FTYPE_MOSTLY_TQ1_0 || ftype == LLAMA_FTYPE_MOSTLY_TQ2_0) {
  187. new_type = GGML_TYPE_Q4_K;
  188. }
  189. }
  190. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  191. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  192. if (name.find("attn_v.weight") != std::string::npos) {
  193. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  194. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  195. ++qs.i_attention_wv;
  196. }
  197. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  198. new_type = GGML_TYPE_Q4_K;
  199. }
  200. else if (name.find("ffn_down") != std::string::npos) {
  201. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  202. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  203. }
  204. ++qs.i_ffn_down;
  205. }
  206. else if (name.find("attn_output.weight") != std::string::npos) {
  207. if (qs.model.hparams.n_expert == 8) {
  208. new_type = GGML_TYPE_Q5_K;
  209. } else {
  210. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  211. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  212. }
  213. }
  214. } else if (name.find("attn_v.weight") != std::string::npos) {
  215. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  216. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  217. }
  218. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  219. new_type = GGML_TYPE_Q4_K;
  220. }
  221. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  222. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  223. }
  224. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  225. new_type = GGML_TYPE_Q4_K;
  226. }
  227. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  228. new_type = GGML_TYPE_Q4_K;
  229. }
  230. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  231. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  232. }
  233. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  234. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  235. new_type = GGML_TYPE_Q5_K;
  236. }
  237. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  238. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  239. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  240. if (qs.model.type == MODEL_70B) {
  241. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  242. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  243. // nearly negligible increase in model size by quantizing this tensor with more bits:
  244. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  245. }
  246. if (qs.model.hparams.n_expert == 8) {
  247. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  248. // TODO: explore better strategies
  249. new_type = GGML_TYPE_Q8_0;
  250. }
  251. ++qs.i_attention_wv;
  252. } else if (name.find("attn_k.weight") != std::string::npos) {
  253. if (qs.model.hparams.n_expert == 8) {
  254. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  255. // TODO: explore better strategies
  256. new_type = GGML_TYPE_Q8_0;
  257. }
  258. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  259. new_type = GGML_TYPE_IQ3_XXS;
  260. }
  261. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  262. new_type = GGML_TYPE_IQ2_S;
  263. }
  264. } else if (name.find("attn_q.weight") != std::string::npos) {
  265. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  266. new_type = GGML_TYPE_IQ3_XXS;
  267. }
  268. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  269. new_type = GGML_TYPE_IQ2_S;
  270. }
  271. } else if (name.find("ffn_down") != std::string::npos) {
  272. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  273. int i_layer = info.first, n_layer = info.second;
  274. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  275. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  276. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  277. }
  278. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  279. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  280. }
  281. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  282. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  283. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  284. : GGML_TYPE_Q3_K;
  285. }
  286. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  287. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  288. new_type = GGML_TYPE_Q4_K;
  289. }
  290. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  291. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  292. }
  293. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  294. if (arch == LLM_ARCH_FALCON) {
  295. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  296. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  297. } else {
  298. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  299. }
  300. }
  301. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  302. new_type = GGML_TYPE_Q5_K;
  303. }
  304. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  305. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  306. new_type = GGML_TYPE_Q5_K;
  307. }
  308. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  309. && qs.has_imatrix && i_layer < n_layer/8) {
  310. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  311. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  312. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  313. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  314. }
  315. ++qs.i_ffn_down;
  316. } else if (name.find("attn_output.weight") != std::string::npos) {
  317. if (arch != LLM_ARCH_FALCON) {
  318. if (qs.model.hparams.n_expert == 8) {
  319. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  320. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  321. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  322. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  323. new_type = GGML_TYPE_Q5_K;
  324. }
  325. } else {
  326. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  327. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  328. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  329. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  330. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  331. }
  332. } else {
  333. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  334. }
  335. }
  336. else if (name.find("attn_qkv.weight") != std::string::npos) {
  337. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  338. new_type = GGML_TYPE_Q4_K;
  339. }
  340. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  341. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  342. }
  343. else if (name.find("ffn_gate") != std::string::npos) {
  344. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  345. int i_layer = info.first, n_layer = info.second;
  346. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  347. new_type = GGML_TYPE_IQ3_XXS;
  348. }
  349. ++qs.i_ffn_gate;
  350. }
  351. else if (name.find("ffn_up") != std::string::npos) {
  352. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  353. int i_layer = info.first, n_layer = info.second;
  354. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  355. new_type = GGML_TYPE_IQ3_XXS;
  356. }
  357. ++qs.i_ffn_up;
  358. }
  359. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  360. //}
  361. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  362. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  363. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  364. //}
  365. // This can be used to reduce the size of the Q5_K_S model.
  366. // The associated PPL increase is fully in line with the size reduction
  367. //else {
  368. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  369. //}
  370. bool convert_incompatible_tensor = false;
  371. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  372. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  373. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  374. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  375. new_type == GGML_TYPE_IQ1_M) {
  376. int nx = tensor->ne[0];
  377. int ny = tensor->ne[1];
  378. if (nx % QK_K != 0) {
  379. LLAMA_LOG_WARN("\n\n%s : tensor cols %d x %d are not divisible by %d, required for %s", __func__, nx, ny, QK_K, ggml_type_name(new_type));
  380. convert_incompatible_tensor = true;
  381. } else {
  382. ++qs.n_k_quantized;
  383. }
  384. }
  385. if (convert_incompatible_tensor) {
  386. switch (new_type) {
  387. case GGML_TYPE_TQ1_0:
  388. case GGML_TYPE_TQ2_0: new_type = GGML_TYPE_Q4_0; break; // TODO: use a symmetric type instead
  389. case GGML_TYPE_IQ2_XXS:
  390. case GGML_TYPE_IQ2_XS:
  391. case GGML_TYPE_IQ2_S:
  392. case GGML_TYPE_IQ3_XXS:
  393. case GGML_TYPE_IQ3_S:
  394. case GGML_TYPE_IQ1_S:
  395. case GGML_TYPE_IQ1_M:
  396. case GGML_TYPE_Q2_K:
  397. case GGML_TYPE_Q3_K:
  398. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  399. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  400. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  401. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  402. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  403. }
  404. if (tensor->ne[0] % ggml_blck_size(new_type) != 0) {
  405. new_type = GGML_TYPE_F16;
  406. }
  407. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  408. ++qs.n_fallback;
  409. }
  410. return new_type;
  411. }
  412. static size_t llama_tensor_quantize_internal(enum ggml_type new_type, const float * f32_data, void * new_data, const int64_t chunk_size, int64_t nrows, int64_t n_per_row, const float * imatrix, std::vector<std::thread> & workers, const int nthread) {
  413. if (nthread < 2) {
  414. // single-thread
  415. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  416. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  417. throw std::runtime_error("quantized data validation failed");
  418. }
  419. return new_size;
  420. }
  421. std::mutex mutex;
  422. int64_t counter = 0;
  423. size_t new_size = 0;
  424. bool valid = true;
  425. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  426. nrows, n_per_row, imatrix]() {
  427. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  428. size_t local_size = 0;
  429. while (true) {
  430. std::unique_lock<std::mutex> lock(mutex);
  431. int64_t first_row = counter; counter += nrows_per_chunk;
  432. if (first_row >= nrows) {
  433. if (local_size > 0) {
  434. new_size += local_size;
  435. }
  436. break;
  437. }
  438. lock.unlock();
  439. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  440. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  441. local_size += this_size;
  442. // validate the quantized data
  443. const size_t row_size = ggml_row_size(new_type, n_per_row);
  444. void * this_data = (char *) new_data + first_row * row_size;
  445. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  446. std::unique_lock<std::mutex> lock(mutex);
  447. valid = false;
  448. break;
  449. }
  450. }
  451. };
  452. for (int it = 0; it < nthread - 1; ++it) {
  453. workers.emplace_back(compute);
  454. }
  455. compute();
  456. for (auto & w : workers) { w.join(); }
  457. workers.clear();
  458. if (!valid) {
  459. throw std::runtime_error("quantized data validation failed");
  460. }
  461. return new_size;
  462. }
  463. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  464. ggml_type default_type;
  465. llama_ftype ftype = params->ftype;
  466. switch (params->ftype) {
  467. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  468. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  469. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  470. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  471. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  472. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  473. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  474. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  475. // K-quants
  476. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  477. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  478. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  479. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  480. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  481. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  482. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  483. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  484. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  485. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  486. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  487. case LLAMA_FTYPE_MOSTLY_TQ1_0: default_type = GGML_TYPE_TQ1_0; break;
  488. case LLAMA_FTYPE_MOSTLY_TQ2_0: default_type = GGML_TYPE_TQ2_0; break;
  489. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  490. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  491. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  492. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  493. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  494. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  495. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  496. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  497. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  498. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  499. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  500. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  501. }
  502. int nthread = params->nthread;
  503. if (nthread <= 0) {
  504. nthread = std::thread::hardware_concurrency();
  505. }
  506. // mmap consistently increases speed Linux, and also increases speed on Windows with
  507. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  508. #if defined(__linux__) || defined(_WIN32)
  509. constexpr bool use_mmap = true;
  510. #else
  511. constexpr bool use_mmap = false;
  512. #endif
  513. llama_model_kv_override * kv_overrides = nullptr;
  514. if (params->kv_overrides) {
  515. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  516. kv_overrides = v->data();
  517. }
  518. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  519. ml.init_mappings(false); // no prefetching
  520. llama_model model;
  521. llm_load_arch (ml, model);
  522. llm_load_hparams(ml, model);
  523. llm_load_stats (ml, model);
  524. struct quantize_state_internal qs(model, params);
  525. if (params->only_copy) {
  526. ftype = model.ftype;
  527. }
  528. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  529. if (params->imatrix) {
  530. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  531. if (imatrix_data) {
  532. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  533. qs.has_imatrix = true;
  534. // check imatrix for nans or infs
  535. for (const auto & kv : *imatrix_data) {
  536. for (float f : kv.second) {
  537. if (!std::isfinite(f)) {
  538. throw std::runtime_error(format("imatrix contains non-finite value %f\n", f));
  539. }
  540. }
  541. }
  542. }
  543. }
  544. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  545. gguf_context_ptr ctx_out { gguf_init_empty() };
  546. // copy the KV pairs from the input file
  547. gguf_set_kv (ctx_out.get(), ml.meta.get());
  548. gguf_set_val_u32(ctx_out.get(), "general.quantization_version", GGML_QNT_VERSION); // TODO: use LLM_KV
  549. gguf_set_val_u32(ctx_out.get(), "general.file_type", ftype); // TODO: use LLM_KV
  550. // Remove split metadata
  551. gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  552. gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  553. gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  554. if (params->kv_overrides) {
  555. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  556. for (const auto & o : overrides) {
  557. if (o.key[0] == 0) break;
  558. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  559. gguf_set_val_f32(ctx_out.get(), o.key, o.val_f64);
  560. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  561. gguf_set_val_i32(ctx_out.get(), o.key, o.val_i64);
  562. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  563. gguf_set_val_bool(ctx_out.get(), o.key, o.val_bool);
  564. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  565. gguf_set_val_str(ctx_out.get(), o.key, o.val_str);
  566. } else {
  567. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  568. }
  569. }
  570. }
  571. // make a list of weights
  572. std::vector<const llama_model_loader::llama_tensor_weight *> tensors;
  573. tensors.reserve(ml.weights_map.size());
  574. for (const auto & it : ml.weights_map) {
  575. tensors.push_back(&it.second);
  576. }
  577. // keep_split requires that the weights are sorted by split index
  578. if (params->keep_split) {
  579. std::sort(tensors.begin(), tensors.end(), [](const llama_model_loader::llama_tensor_weight * a, const llama_model_loader::llama_tensor_weight * b) {
  580. if (a->idx == b->idx) {
  581. return a->offs < b->offs;
  582. }
  583. return a->idx < b->idx;
  584. });
  585. }
  586. for (const auto * it : tensors) {
  587. const struct ggml_tensor * tensor = it->tensor;
  588. const std::string name = ggml_get_name(tensor);
  589. // TODO: avoid hardcoded tensor names - use the TN_* constants
  590. if (name.find("attn_v.weight") != std::string::npos ||
  591. name.find("attn_qkv.weight") != std::string::npos ||
  592. name.find("attn_kv_b.weight")!= std::string::npos) {
  593. ++qs.n_attention_wv;
  594. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  595. qs.has_output = true;
  596. }
  597. }
  598. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  599. // sanity checks
  600. {
  601. const auto & n_head_kv_iter = model.hparams.n_head_kv_arr.begin();
  602. // attention layers have a non-zero number of kv heads
  603. int32_t n_attn_layer = model.hparams.n_layer - std::count(n_head_kv_iter, n_head_kv_iter + model.hparams.n_layer, 0);
  604. if (llama_model_has_encoder(&model)) {
  605. n_attn_layer *= 3;
  606. }
  607. if (qs.n_attention_wv != n_attn_layer) {
  608. LLAMA_LOG_WARN("%s: n_attention_wv is unexpected, expected: %d, found: %d\n", __func__, n_attn_layer, qs.n_attention_wv);
  609. }
  610. }
  611. size_t total_size_org = 0;
  612. size_t total_size_new = 0;
  613. std::vector<std::thread> workers;
  614. workers.reserve(nthread);
  615. int idx = 0;
  616. std::vector<no_init<uint8_t>> read_data;
  617. std::vector<no_init<uint8_t>> work;
  618. std::vector<no_init<float>> f32_conv_buf;
  619. uint16_t n_split = 1;
  620. // Assume split index is continuous
  621. if (params->keep_split) {
  622. for (const auto * it : tensors) {
  623. n_split = std::max(uint16_t(it->idx + 1), n_split);
  624. }
  625. }
  626. std::vector<gguf_context_ptr> ctx_outs(n_split);
  627. ctx_outs[0] = std::move(ctx_out);
  628. // populate the original tensors so we get an initial meta data
  629. for (const auto * it : tensors) {
  630. uint16_t i_split = params->keep_split ? it->idx : 0;
  631. struct ggml_tensor * tensor = it->tensor;
  632. if (!ctx_outs[i_split]) {
  633. ctx_outs[i_split].reset(gguf_init_empty());
  634. }
  635. gguf_add_tensor(ctx_outs[i_split].get(), tensor);
  636. }
  637. // Set split info if needed
  638. if (n_split > 1) {
  639. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  640. gguf_set_val_u16(ctx_outs[i].get(), ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  641. gguf_set_val_u16(ctx_outs[i].get(), ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  642. gguf_set_val_i32(ctx_outs[i].get(), ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  643. }
  644. }
  645. int cur_split = -1;
  646. std::ofstream fout;
  647. auto close_ofstream = [&]() {
  648. // Write metadata and close file handler
  649. if (fout.is_open()) {
  650. fout.seekp(0);
  651. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split].get()));
  652. gguf_get_meta_data(ctx_outs[cur_split].get(), data.data());
  653. fout.write((const char *) data.data(), data.size());
  654. fout.close();
  655. }
  656. };
  657. auto new_ofstream = [&](int index) {
  658. cur_split = index;
  659. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  660. std::string fname = fname_out;
  661. if (params->keep_split) {
  662. std::vector<char> split_path(llama_path_max(), 0);
  663. llama_split_path(split_path.data(), split_path.size(), fname_out.c_str(), cur_split, n_split);
  664. fname = std::string(split_path.data());
  665. }
  666. fout = std::ofstream(fname, std::ios::binary);
  667. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  668. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split].get());
  669. // placeholder for the meta data
  670. ::zeros(fout, meta_size);
  671. };
  672. const auto tn = LLM_TN(model.arch);
  673. new_ofstream(0);
  674. for (const auto * it : tensors) {
  675. const auto & weight = *it;
  676. struct ggml_tensor * tensor = weight.tensor;
  677. if (weight.idx != cur_split && params->keep_split) {
  678. close_ofstream();
  679. new_ofstream(weight.idx);
  680. }
  681. const std::string name = ggml_get_name(tensor);
  682. if (!ml.use_mmap) {
  683. if (read_data.size() < ggml_nbytes(tensor)) {
  684. read_data.resize(ggml_nbytes(tensor));
  685. }
  686. tensor->data = read_data.data();
  687. }
  688. ml.load_data_for(tensor);
  689. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  690. ++idx, ml.n_tensors,
  691. ggml_get_name(tensor),
  692. llama_format_tensor_shape(tensor).c_str(),
  693. ggml_type_name(tensor->type));
  694. // This used to be a regex, but <regex> has an extreme cost to compile times.
  695. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  696. // quantize only 2D and 3D tensors (experts)
  697. quantize &= (ggml_n_dims(tensor) >= 2);
  698. // do not quantize norm tensors
  699. quantize &= name.find("_norm.weight") == std::string::npos;
  700. quantize &= params->quantize_output_tensor || name != "output.weight";
  701. quantize &= !params->only_copy;
  702. // do not quantize expert gating tensors
  703. // NOTE: can't use LLM_TN here because the layer number is not known
  704. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  705. // do not quantize positional embeddings and token types (BERT)
  706. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  707. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  708. // do not quantize Mamba's small yet 2D weights
  709. // NOTE: can't use LLM_TN here because the layer number is not known
  710. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  711. // do not quantize RWKV's time_mix_first tensors
  712. quantize &= name.find("time_mix_first.weight") == std::string::npos;
  713. quantize &= name.find("time_mix_w1.weight") == std::string::npos;
  714. quantize &= name.find("time_mix_w2.weight") == std::string::npos;
  715. quantize &= name.find("time_mix_decay_w1.weight") == std::string::npos;
  716. quantize &= name.find("time_mix_decay_w2.weight") == std::string::npos;
  717. // do not quantize relative position bias (T5)
  718. quantize &= name.find("attn_rel_b.weight") == std::string::npos;
  719. enum ggml_type new_type;
  720. void * new_data;
  721. size_t new_size;
  722. if (quantize) {
  723. new_type = default_type;
  724. // get more optimal quantization type based on the tensor shape, layer, etc.
  725. if (!params->pure && ggml_is_quantized(default_type)) {
  726. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  727. }
  728. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  729. new_type = params->token_embedding_type;
  730. }
  731. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  732. new_type = params->output_tensor_type;
  733. }
  734. // If we've decided to quantize to the same type the tensor is already
  735. // in then there's nothing to do.
  736. quantize = tensor->type != new_type;
  737. }
  738. if (!quantize) {
  739. new_type = tensor->type;
  740. new_data = tensor->data;
  741. new_size = ggml_nbytes(tensor);
  742. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  743. } else {
  744. const int64_t nelements = ggml_nelements(tensor);
  745. const float * imatrix = nullptr;
  746. if (imatrix_data) {
  747. auto it = imatrix_data->find(tensor->name);
  748. if (it == imatrix_data->end()) {
  749. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  750. } else {
  751. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  752. imatrix = it->second.data();
  753. } else {
  754. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  755. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  756. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  757. // this is a significant error and it may be good idea to abort the process if this happens,
  758. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  759. // tok_embd should be ignored in this case, since it always causes this warning
  760. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  761. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  762. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  763. }
  764. }
  765. }
  766. }
  767. if ((new_type == GGML_TYPE_IQ2_XXS ||
  768. new_type == GGML_TYPE_IQ2_XS ||
  769. new_type == GGML_TYPE_IQ2_S ||
  770. new_type == GGML_TYPE_IQ1_S ||
  771. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  772. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  773. LLAMA_LOG_ERROR("\n\n============================================================\n");
  774. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  775. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  776. LLAMA_LOG_ERROR("============================================================\n\n");
  777. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  778. }
  779. float * f32_data;
  780. if (tensor->type == GGML_TYPE_F32) {
  781. f32_data = (float *) tensor->data;
  782. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  783. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  784. } else {
  785. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  786. f32_data = (float *) f32_conv_buf.data();
  787. }
  788. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  789. fflush(stdout);
  790. if (work.size() < (size_t)nelements * 4) {
  791. work.resize(nelements * 4); // upper bound on size
  792. }
  793. new_data = work.data();
  794. const int64_t n_per_row = tensor->ne[0];
  795. const int64_t nrows = tensor->ne[1];
  796. static const int64_t min_chunk_size = 32 * 512;
  797. const int64_t chunk_size = (n_per_row >= min_chunk_size ? n_per_row : n_per_row * ((min_chunk_size + n_per_row - 1)/n_per_row));
  798. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  799. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  800. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  801. // quantize each expert separately since they have different importance matrices
  802. new_size = 0;
  803. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  804. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  805. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  806. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  807. new_size += llama_tensor_quantize_internal(new_type, f32_data_03, new_data_03, chunk_size, nrows, n_per_row, imatrix_03, workers, nthread_use);
  808. }
  809. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  810. }
  811. total_size_org += ggml_nbytes(tensor);
  812. total_size_new += new_size;
  813. // update the gguf meta data as we go
  814. gguf_set_tensor_type(ctx_outs[cur_split].get(), name.c_str(), new_type);
  815. gguf_set_tensor_data(ctx_outs[cur_split].get(), name.c_str(), new_data, new_size);
  816. // write tensor data + padding
  817. fout.write((const char *) new_data, new_size);
  818. zeros(fout, GGML_PAD(new_size, align) - new_size);
  819. }
  820. close_ofstream();
  821. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  822. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  823. if (qs.n_fallback > 0) {
  824. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  825. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  826. }
  827. }
  828. //
  829. // interface implementation
  830. //
  831. struct llama_model_quantize_params llama_model_quantize_default_params() {
  832. struct llama_model_quantize_params result = {
  833. /*.nthread =*/ 0,
  834. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  835. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  836. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  837. /*.allow_requantize =*/ false,
  838. /*.quantize_output_tensor =*/ true,
  839. /*.only_copy =*/ false,
  840. /*.pure =*/ false,
  841. /*.keep_split =*/ false,
  842. /*.imatrix =*/ nullptr,
  843. /*.kv_overrides =*/ nullptr,
  844. };
  845. return result;
  846. }
  847. uint32_t llama_model_quantize(
  848. const char * fname_inp,
  849. const char * fname_out,
  850. const llama_model_quantize_params * params) {
  851. try {
  852. llama_model_quantize_internal(fname_inp, fname_out, params);
  853. } catch (const std::exception & err) {
  854. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  855. return 1;
  856. }
  857. return 0;
  858. }