imatrix.cpp 22 KB

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