imatrix.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "log.h"
  4. #include "llama.h"
  5. #include <chrono>
  6. #include <cmath>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <ctime>
  10. #include <thread>
  11. #include <mutex>
  12. #include <vector>
  13. #include <fstream>
  14. #include <unordered_map>
  15. #include <algorithm>
  16. #if defined(_MSC_VER)
  17. #pragma warning(disable: 4244 4267) // possible loss of data
  18. #endif
  19. static void print_usage(int, char ** argv) {
  20. LOG("\nexample usage:\n");
  21. LOG("\n %s \\\n"
  22. " -m model.gguf -f some-text.txt [-o imatrix.dat] [--process-output] \\\n"
  23. " [--no-ppl] [--chunk 123] [--output-frequency 10] [--save-frequency 0] \\\n"
  24. " [--in-file imatrix-prev-0.dat --in-file imatrix-prev-1.dat ...]\n" , argv[0]);
  25. LOG("\n");
  26. }
  27. struct Stats {
  28. std::vector<float> values;
  29. std::vector<int> counts;
  30. int ncall = 0;
  31. };
  32. class IMatrixCollector {
  33. public:
  34. IMatrixCollector() = default;
  35. void set_params(common_params params) { m_params = std::move(params); }
  36. bool collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data);
  37. void save_imatrix(int ncall = -1) const;
  38. bool load_imatrix(const char * fname);
  39. private:
  40. std::unordered_map<std::string, Stats> m_stats;
  41. common_params m_params;
  42. std::mutex m_mutex;
  43. int m_last_call = 0;
  44. std::vector<char> m_src1_data;
  45. std::vector<char> m_ids; // the expert ids from ggml_mul_mat_id
  46. };
  47. // remove any prefix and suffixes from the name
  48. // CUDA0#blk.0.attn_k.weight#0 => blk.0.attn_k.weight
  49. static std::string filter_tensor_name(const char * name) {
  50. std::string wname;
  51. const char * p = strchr(name, '#');
  52. if (p != NULL) {
  53. p = p + 1;
  54. const char * q = strchr(p, '#');
  55. if (q != NULL) {
  56. wname = std::string(p, q - p);
  57. } else {
  58. wname = p;
  59. }
  60. } else {
  61. wname = name;
  62. }
  63. return wname;
  64. }
  65. bool IMatrixCollector::collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  66. GGML_UNUSED(user_data);
  67. const struct ggml_tensor * src0 = t->src[0];
  68. const struct ggml_tensor * src1 = t->src[1];
  69. std::string wname = filter_tensor_name(src0->name);
  70. // when ask is true, the scheduler wants to know if we are interested in data from this tensor
  71. // if we return true, a follow-up call will be made with ask=false in which we can do the actual collection
  72. if (ask) {
  73. if (t->op == GGML_OP_MUL_MAT_ID) return true; // collect all indirect matrix multiplications
  74. if (t->op != GGML_OP_MUL_MAT) return false;
  75. // why are small batches ignored (<16 tokens)?
  76. if (src1->ne[1] < 16 || src1->type != GGML_TYPE_F32) return false;
  77. if (!(wname.substr(0, 4) == "blk." || (m_params.process_output && wname == "output.weight"))) return false;
  78. return true;
  79. }
  80. std::lock_guard<std::mutex> lock(m_mutex);
  81. // copy the data from the GPU memory if needed
  82. const bool is_host = ggml_backend_buffer_is_host(src1->buffer);
  83. if (!is_host) {
  84. const size_t src1_nbytes = ggml_nbytes(src1);
  85. m_src1_data.resize(src1_nbytes);
  86. ggml_backend_tensor_get(src1, m_src1_data.data(), 0, src1_nbytes);
  87. }
  88. const char * data = is_host ? (const char *) src1->data : m_src1_data.data();
  89. GGML_ASSERT(src1->nb[0] == ggml_element_size(src1));
  90. // this has been adapted to the new format of storing merged experts in a single 3d tensor
  91. // ref: https://github.com/ggml-org/llama.cpp/pull/6387
  92. if (t->op == GGML_OP_MUL_MAT_ID) {
  93. // ids -> [n_experts_used, n_tokens]
  94. // src1 -> [cols, n_expert_used, n_tokens]
  95. const ggml_tensor * ids = t->src[2];
  96. const int n_as = src0->ne[2];
  97. const int n_ids = ids->ne[0];
  98. // the top-k selected expert ids are stored in the ids tensor
  99. // for simplicity, always copy ids to host, because it is small
  100. // take into account that ids is not contiguous!
  101. GGML_ASSERT(ids->ne[1] == src1->ne[2]);
  102. m_ids.resize(ggml_nbytes(ids));
  103. ggml_backend_tensor_get(ids, m_ids.data(), 0, ggml_nbytes(ids));
  104. auto & e = m_stats[wname];
  105. ++e.ncall;
  106. if (e.values.empty()) {
  107. e.values.resize(src1->ne[0]*n_as, 0);
  108. e.counts.resize(src1->ne[0]*n_as, 0);
  109. }
  110. else if (e.values.size() != (size_t)src1->ne[0]*n_as) {
  111. LOG_ERR("%s: inconsistent size for %s (%d vs %d)\n", __func__, wname.c_str(), (int)e.values.size(), (int)src1->ne[0]*n_as);
  112. exit(1); //GGML_ABORT("fatal error");
  113. }
  114. LOG_DBGV(2, "%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);
  115. // loop over all possible experts, regardless if they are used or not in the batch
  116. for (int ex = 0; ex < n_as; ++ex) {
  117. size_t e_start = ex*src1->ne[0];
  118. for (int idx = 0; idx < n_ids; ++idx) {
  119. for (int row = 0; row < (int)src1->ne[2]; ++row) {
  120. const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);
  121. GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check
  122. if (excur != ex) continue;
  123. const int64_t i11 = idx % src1->ne[1];
  124. const int64_t i12 = row;
  125. const float * x = (const float *)(data + i11*src1->nb[1] + i12*src1->nb[2]);
  126. for (int j = 0; j < (int)src1->ne[0]; ++j) {
  127. e.values[e_start + j] += x[j]*x[j];
  128. e.counts[e_start + j]++;
  129. if (!std::isfinite(e.values[e_start + j])) {
  130. LOG("\n");
  131. LOG_ERR("%f detected in %s\n", e.values[e_start + j], wname.c_str());
  132. exit(1);
  133. }
  134. }
  135. }
  136. }
  137. if (e.ncall > m_last_call) {
  138. m_last_call = e.ncall;
  139. if (m_last_call % m_params.n_out_freq == 0) {
  140. save_imatrix();
  141. }
  142. if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {
  143. save_imatrix(m_last_call);
  144. }
  145. }
  146. }
  147. } else {
  148. auto & e = m_stats[wname];
  149. if (e.values.empty()) {
  150. e.values.resize(src1->ne[0], 0);
  151. e.counts.resize(src1->ne[0], 0);
  152. }
  153. else if (e.values.size() != (size_t)src1->ne[0]) {
  154. LOG_ERR("%s: inconsistent size for %s (%d vs %d)\n", __func__, wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);
  155. exit(1); //GGML_ABORT("fatal error");
  156. }
  157. ++e.ncall;
  158. LOG_DBGV(2, "%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);
  159. for (int row = 0; row < (int)src1->ne[1]; ++row) {
  160. const float * x = (const float *) (data + row * src1->nb[1]);
  161. for (int j = 0; j < (int)src1->ne[0]; ++j) {
  162. e.values[j] += x[j]*x[j];
  163. e.counts[j]++;
  164. if (!std::isfinite(e.values[j])) {
  165. LOG_ERR("%f detected in %s\n", e.values[j], wname.c_str());
  166. exit(1);
  167. }
  168. }
  169. }
  170. if (e.ncall > m_last_call) {
  171. m_last_call = e.ncall;
  172. if (m_last_call % m_params.n_out_freq == 0) {
  173. save_imatrix();
  174. }
  175. if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {
  176. save_imatrix(m_last_call);
  177. }
  178. }
  179. }
  180. return true;
  181. }
  182. void IMatrixCollector::save_imatrix(int ncall) const {
  183. auto fname = m_params.out_file;
  184. if (ncall > 0) {
  185. fname += ".at_";
  186. fname += std::to_string(ncall);
  187. }
  188. // avoid writing imatrix entries that do not have full data
  189. // this can happen with MoE models where some of the experts end up not being exercised by the provided training data
  190. int n_entries = 0;
  191. std::vector<std::string> to_store;
  192. bool is_first = true; // for printing
  193. for (const auto & kv : m_stats) {
  194. const int n_all = kv.second.counts.size();
  195. if (n_all == 0) {
  196. continue;
  197. }
  198. int n_zeros = 0;
  199. for (const int c : kv.second.counts) {
  200. if (c == 0) {
  201. n_zeros++;
  202. }
  203. }
  204. if (n_zeros != 0 && is_first) {
  205. LOG_INF("\n");
  206. is_first = false;
  207. }
  208. if (n_zeros == n_all) {
  209. LOG_WRN("%s: entry '%40s' has no data - skipping\n", __func__, kv.first.c_str());
  210. continue;
  211. }
  212. if (n_zeros > 0) {
  213. LOG_WRN("%s: entry '%40s' has partial data (%.2f%%) - skipping\n", __func__, kv.first.c_str(), 100.0f * (n_all - n_zeros) / n_all);
  214. continue;
  215. }
  216. n_entries++;
  217. to_store.push_back(kv.first);
  218. }
  219. if (to_store.size() < m_stats.size()) {
  220. LOG_WRN("%s: storing only %zu out of %zu entries\n", __func__, to_store.size(), m_stats.size());
  221. }
  222. std::ofstream out(fname, std::ios::binary);
  223. out.write((const char *) &n_entries, sizeof(n_entries));
  224. for (const auto & name : to_store) {
  225. const auto & stat = m_stats.at(name);
  226. int len = name.size();
  227. out.write((const char *) &len, sizeof(len));
  228. out.write(name.c_str(), len);
  229. out.write((const char *) &stat.ncall, sizeof(stat.ncall));
  230. int nval = stat.values.size();
  231. out.write((const char *) &nval, sizeof(nval));
  232. if (nval > 0) {
  233. std::vector<float> tmp(nval);
  234. for (int i = 0; i < nval; i++) {
  235. tmp[i] = (stat.values[i] / static_cast<float>(stat.counts[i])) * static_cast<float>(stat.ncall);
  236. }
  237. out.write((const char*)tmp.data(), nval*sizeof(float));
  238. }
  239. }
  240. // Write the number of call the matrix was computed with
  241. out.write((const char *) &m_last_call, sizeof(m_last_call));
  242. // Write the input filename at the end of the file to later on specify it in quantize
  243. {
  244. int len = m_params.prompt_file.size();
  245. out.write((const char *) &len, sizeof(len));
  246. out.write(m_params.prompt_file.c_str(), len);
  247. }
  248. LOGV(1, "\n");
  249. LOG_DBGV(1, "%s: stored collected data after %d chunks in %s\n", __func__, m_last_call, fname.c_str());
  250. }
  251. bool IMatrixCollector::load_imatrix(const char * fname) {
  252. std::ifstream in(fname, std::ios::binary);
  253. if (!in) {
  254. LOG_ERR("%s: failed to open %s\n",__func__, fname);
  255. return false;
  256. }
  257. int n_entries;
  258. in.read((char*)&n_entries, sizeof(n_entries));
  259. if (in.fail() || n_entries < 1) {
  260. LOG_ERR("%s: no data in file %s\n", __func__, fname);
  261. return false;
  262. }
  263. for (int i = 0; i < n_entries; ++i) {
  264. int len; in.read((char *)&len, sizeof(len));
  265. std::vector<char> name_as_vec(len+1);
  266. in.read((char *)name_as_vec.data(), len);
  267. if (in.fail()) {
  268. LOG_ERR("%s: failed reading name for entry %d from %s\n",__func__,i+1, fname);
  269. return false;
  270. }
  271. name_as_vec[len] = 0;
  272. std::string name{name_as_vec.data()};
  273. auto & e = m_stats[std::move(name)];
  274. int ncall;
  275. in.read((char*)&ncall, sizeof(ncall));
  276. int nval;
  277. in.read((char *)&nval, sizeof(nval));
  278. if (in.fail() || nval < 1) {
  279. LOG_ERR("%s: failed reading number of values for entry %d\n",__func__,i);
  280. m_stats = {};
  281. return false;
  282. }
  283. if (e.values.empty()) {
  284. e.values.resize(nval, 0);
  285. e.counts.resize(nval, 0);
  286. }
  287. std::vector<float> tmp(nval);
  288. in.read((char*)tmp.data(), nval*sizeof(float));
  289. if (in.fail()) {
  290. LOG_ERR("%s: failed reading data for entry %d\n",__func__,i);
  291. m_stats = {};
  292. return false;
  293. }
  294. // Recreate the state as expected by save_imatrix(), and corerct for weighted sum.
  295. for (int i = 0; i < nval; i++) {
  296. e.values[i] += tmp[i];
  297. e.counts[i] += ncall;
  298. }
  299. e.ncall += ncall;
  300. }
  301. return true;
  302. }
  303. static IMatrixCollector g_collector;
  304. static bool ik_collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  305. return g_collector.collect_imatrix(t, ask, user_data);
  306. }
  307. struct results_log_softmax {
  308. double log_softmax;
  309. float logit;
  310. float prob;
  311. };
  312. static std::vector<float> softmax(const std::vector<float> & logits) {
  313. std::vector<float> probs(logits.size());
  314. float max_logit = logits[0];
  315. for (float v : logits) {
  316. max_logit = std::max(max_logit, v);
  317. }
  318. double sum_exp = 0.0;
  319. for (size_t i = 0; i < logits.size(); i++) {
  320. // Subtract the maximum logit value from the current logit value for numerical stability
  321. const float logit = logits[i] - max_logit;
  322. const float exp_logit = expf(logit);
  323. sum_exp += exp_logit;
  324. probs[i] = exp_logit;
  325. }
  326. for (size_t i = 0; i < probs.size(); i++) {
  327. probs[i] /= sum_exp;
  328. }
  329. return probs;
  330. }
  331. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  332. float max_logit = logits[0];
  333. for (int i = 1; i < n_vocab; ++i) {
  334. max_logit = std::max(max_logit, logits[i]);
  335. }
  336. double sum_exp = 0.0;
  337. for (int i = 0; i < n_vocab; ++i) {
  338. sum_exp += expf(logits[i] - max_logit);
  339. }
  340. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  341. }
  342. static void process_logits(
  343. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  344. double & nll, double & nll2, float * logit_history, float * prob_history) {
  345. std::mutex mutex;
  346. int counter = 0;
  347. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  348. double local_nll = 0;
  349. double local_nll2 = 0;
  350. while (true) {
  351. std::unique_lock<std::mutex> lock(mutex);
  352. int i = counter++;
  353. if (i >= n_token) {
  354. nll += local_nll; nll2 += local_nll2;
  355. break;
  356. }
  357. lock.unlock();
  358. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  359. const double v = -results.log_softmax;
  360. local_nll += v;
  361. local_nll2 += v*v;
  362. logit_history[i] = results.logit;
  363. prob_history[i] = results.prob;
  364. }
  365. };
  366. for (auto & w : workers) {
  367. w = std::thread(compute);
  368. }
  369. compute();
  370. for (auto & w : workers) {
  371. w.join();
  372. }
  373. }
  374. static bool compute_imatrix(llama_context * ctx, const common_params & params) {
  375. const llama_model * model = llama_get_model(ctx);
  376. const llama_vocab * vocab = llama_model_get_vocab(model);
  377. const bool add_bos = llama_vocab_get_add_bos(vocab);
  378. const int n_ctx = llama_n_ctx(ctx);
  379. GGML_ASSERT(!llama_vocab_get_add_eos(vocab));
  380. auto tim1 = std::chrono::high_resolution_clock::now();
  381. LOG_INF("%s: tokenizing the input ..\n", __func__);
  382. std::vector<llama_token> tokens = common_tokenize(ctx, params.prompt, true);
  383. auto tim2 = std::chrono::high_resolution_clock::now();
  384. LOG_INF("%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  385. if (params.i_chunk > 0) {
  386. if (size_t((params.i_chunk + 2)*n_ctx) >= tokens.size()) {
  387. LOG_ERR("%s: there will be not enough tokens left after removing %d chunks\n", __func__, params.i_chunk);
  388. return false;
  389. }
  390. LOG_INF("%s: removing initial %d chunks (%d tokens)\n", __func__, params.i_chunk, params.i_chunk*n_ctx);
  391. tokens.erase(tokens.begin(), tokens.begin() + params.i_chunk*n_ctx);
  392. }
  393. if (int(tokens.size()) < 2*n_ctx) {
  394. LOG_ERR("%s: you need at least %d tokens for a context of %d tokens\n", __func__, 2*n_ctx, n_ctx);
  395. LOG_ERR("%s: the data file you provided tokenizes to only %zu tokens\n", __func__, tokens.size());
  396. return false;
  397. }
  398. std::vector<float> logit_history;
  399. std::vector<float> prob_history;
  400. if (params.compute_ppl) {
  401. logit_history.resize(tokens.size());
  402. prob_history.resize(tokens.size());
  403. }
  404. const int n_chunk_max = tokens.size() / n_ctx;
  405. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  406. const int n_vocab = llama_vocab_n_tokens(vocab);
  407. const int n_batch = params.n_batch;
  408. int count = 0;
  409. double nll = 0.0;
  410. double nll2 = 0.0;
  411. LOG_INF("%s: computing over %d chunks with batch_size %d\n", __func__, n_chunk, n_batch);
  412. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  413. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  414. std::vector<float> logits;
  415. if (params.compute_ppl && num_batches > 1) {
  416. logits.reserve((size_t)n_ctx * n_vocab);
  417. }
  418. for (int i = 0; i < n_chunk; ++i) {
  419. const int start = i * n_ctx;
  420. const int end = start + n_ctx;
  421. std::vector<float> logits;
  422. const auto t_start = std::chrono::high_resolution_clock::now();
  423. // clear the KV cache
  424. llama_kv_self_clear(ctx);
  425. llama_batch batch = llama_batch_init(n_batch, 0, 1);
  426. for (int j = 0; j < num_batches; ++j) {
  427. const int batch_start = start + j * n_batch;
  428. const int batch_size = std::min(end - batch_start, n_batch);
  429. // save original token and restore it after eval
  430. const auto token_org = tokens[batch_start];
  431. // add BOS token for the first batch of each chunk
  432. if (add_bos && j == 0) {
  433. tokens[batch_start] = llama_vocab_bos(vocab);
  434. }
  435. common_batch_clear(batch);
  436. for (int i = 0; i < batch_size; i++) {
  437. common_batch_add(batch, tokens[batch_start + i], j*n_batch + i, {0}, true);
  438. }
  439. if (llama_decode(ctx, batch)) {
  440. LOG_ERR("%s : failed to eval\n", __func__);
  441. llama_batch_free(batch);
  442. return false;
  443. }
  444. // restore the original token in case it was set to BOS
  445. tokens[batch_start] = token_org;
  446. if (params.compute_ppl && num_batches > 1) {
  447. const auto * batch_logits = llama_get_logits(ctx);
  448. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  449. }
  450. }
  451. llama_batch_free(batch);
  452. const auto t_end = std::chrono::high_resolution_clock::now();
  453. if (i == 0) {
  454. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  455. LOG_INF("%s: %.2f seconds per pass - ETA ", __func__, t_total);
  456. int total_seconds = (int)(t_total * n_chunk);
  457. if (total_seconds >= 60*60) {
  458. LOG("%d hours ", total_seconds / (60*60));
  459. total_seconds = total_seconds % (60*60);
  460. }
  461. LOG("%.2f minutes\n", total_seconds / 60.0);
  462. }
  463. if (params.compute_ppl) {
  464. const int first = n_ctx/2;
  465. const auto * all_logits = num_batches > 1 ? logits.data() : llama_get_logits(ctx);
  466. process_logits(n_vocab, all_logits + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
  467. workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
  468. count += n_ctx - first - 1;
  469. LOG("[%d]%.4lf,", i + 1, std::exp(nll / count));
  470. fflush(stdout);
  471. logits.clear();
  472. }
  473. }
  474. LOG("\n");
  475. if (params.compute_ppl) {
  476. nll2 /= count;
  477. nll /= count;
  478. const double ppl = exp(nll);
  479. nll2 -= nll * nll;
  480. if (nll2 > 0) {
  481. nll2 = sqrt(nll2/(count-1));
  482. LOG("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  483. } else {
  484. LOG("Unexpected negative standard deviation of log(prob)\n");
  485. }
  486. }
  487. return true;
  488. }
  489. int main(int argc, char ** argv) {
  490. common_params params;
  491. params.out_file = "imatrix.dat" ;
  492. params.n_ctx = 512;
  493. params.logits_all = true;
  494. params.escape = false;
  495. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_IMATRIX, print_usage)) {
  496. return 1;
  497. }
  498. common_init();
  499. params.n_batch = std::min(params.n_batch, params.n_ctx);
  500. g_collector.set_params(params);
  501. for (const auto & in_file : params.in_files) {
  502. LOG_INF("%s : loading imatrix from '%s'\n", __func__, in_file.c_str());
  503. if (!g_collector.load_imatrix(in_file.c_str())) {
  504. LOG_ERR("%s : failed to load %s\n", __func__, in_file.c_str());
  505. return 1;
  506. }
  507. }
  508. if (params.in_files.size() > 1) {
  509. LOG_INF("%s : saving combined imatrix to '%s'\n", __func__, params.out_file.c_str());
  510. g_collector.save_imatrix();
  511. }
  512. llama_backend_init();
  513. llama_numa_init(params.numa);
  514. // pass the callback to the backend scheduler
  515. // it will be executed for each node during the graph computation
  516. params.cb_eval = ik_collect_imatrix;
  517. params.cb_eval_user_data = NULL;
  518. params.warmup = false;
  519. // init
  520. common_init_result llama_init = common_init_from_params(params);
  521. llama_model * model = llama_init.model.get();
  522. llama_context * ctx = llama_init.context.get();
  523. if (model == nullptr || ctx == nullptr) {
  524. LOG_ERR("%s : failed to init\n", __func__);
  525. return 1;
  526. }
  527. const int n_ctx_train = llama_model_n_ctx_train(model);
  528. if (params.n_ctx > n_ctx_train) {
  529. LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n",
  530. __func__, n_ctx_train, params.n_ctx);
  531. }
  532. // print system information
  533. {
  534. LOG_INF("\n");
  535. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  536. }
  537. if (params.prompt.empty()) {
  538. if (params.in_files.empty()) {
  539. LOG_ERR("Error: No prompt provided and no precomputed matrices (--in-file) to combine.\n");
  540. return 1;
  541. }
  542. LOG_INF("No prompt provided; combining precomputed matrices only.\n");
  543. } else {
  544. if (!compute_imatrix(ctx, params)) {
  545. return 1;
  546. }
  547. }
  548. g_collector.save_imatrix();
  549. LOG("\n");
  550. llama_perf_context_print(ctx);
  551. llama_backend_free();
  552. return 0;
  553. }