llama-quant.cpp 42 KB

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