imatrix.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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/ggerganov/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 (fname.empty()) {
  183. fname = "imatrix.dat";
  184. }
  185. if (ncall > 0) {
  186. fname += ".at_";
  187. fname += std::to_string(ncall);
  188. }
  189. // avoid writing imatrix entries that do not have full data
  190. // this can happen with MoE models where some of the experts end up not being exercised by the provided training data
  191. int n_entries = 0;
  192. std::vector<std::string> to_store;
  193. bool is_first = true; // for printing
  194. for (const auto & kv : m_stats) {
  195. const int n_all = kv.second.counts.size();
  196. if (n_all == 0) {
  197. continue;
  198. }
  199. int n_zeros = 0;
  200. for (const int c : kv.second.counts) {
  201. if (c == 0) {
  202. n_zeros++;
  203. }
  204. }
  205. if (n_zeros != 0 && is_first) {
  206. LOG_INF("\n");
  207. is_first = false;
  208. }
  209. if (n_zeros == n_all) {
  210. LOG_WRN("%s: entry '%40s' has no data - skipping\n", __func__, kv.first.c_str());
  211. continue;
  212. }
  213. if (n_zeros > 0) {
  214. LOG_WRN("%s: entry '%40s' has partial data (%.2f%%) - skipping\n", __func__, kv.first.c_str(), 100.0f * (n_all - n_zeros) / n_all);
  215. continue;
  216. }
  217. n_entries++;
  218. to_store.push_back(kv.first);
  219. }
  220. if (to_store.size() < m_stats.size()) {
  221. LOG_WRN("%s: storing only %zu out of %zu entries\n", __func__, to_store.size(), m_stats.size());
  222. }
  223. std::ofstream out(fname, std::ios::binary);
  224. out.write((const char *) &n_entries, sizeof(n_entries));
  225. for (const auto & name : to_store) {
  226. const auto & stat = m_stats.at(name);
  227. int len = name.size();
  228. out.write((const char *) &len, sizeof(len));
  229. out.write(name.c_str(), len);
  230. out.write((const char *) &stat.ncall, sizeof(stat.ncall));
  231. int nval = stat.values.size();
  232. out.write((const char *) &nval, sizeof(nval));
  233. if (nval > 0) {
  234. std::vector<float> tmp(nval);
  235. for (int i = 0; i < nval; i++) {
  236. tmp[i] = (stat.values[i] / static_cast<float>(stat.counts[i])) * static_cast<float>(stat.ncall);
  237. }
  238. out.write((const char*)tmp.data(), nval*sizeof(float));
  239. }
  240. }
  241. // Write the number of call the matrix was computed with
  242. out.write((const char *) &m_last_call, sizeof(m_last_call));
  243. // Write the input filename at the end of the file to later on specify it in quantize
  244. {
  245. int len = m_params.prompt_file.size();
  246. out.write((const char *) &len, sizeof(len));
  247. out.write(m_params.prompt_file.c_str(), len);
  248. }
  249. LOGV(1, "\n");
  250. LOG_DBGV(1, "%s: stored collected data after %d chunks in %s\n", __func__, m_last_call, fname.c_str());
  251. }
  252. bool IMatrixCollector::load_imatrix(const char * fname) {
  253. std::ifstream in(fname, std::ios::binary);
  254. if (!in) {
  255. LOG_ERR("%s: failed to open %s\n",__func__, fname);
  256. return false;
  257. }
  258. int n_entries;
  259. in.read((char*)&n_entries, sizeof(n_entries));
  260. if (in.fail() || n_entries < 1) {
  261. LOG_ERR("%s: no data in file %s\n", __func__, fname);
  262. return false;
  263. }
  264. for (int i = 0; i < n_entries; ++i) {
  265. int len; in.read((char *)&len, sizeof(len));
  266. std::vector<char> name_as_vec(len+1);
  267. in.read((char *)name_as_vec.data(), len);
  268. if (in.fail()) {
  269. LOG_ERR("%s: failed reading name for entry %d from %s\n",__func__,i+1, fname);
  270. return false;
  271. }
  272. name_as_vec[len] = 0;
  273. std::string name{name_as_vec.data()};
  274. auto & e = m_stats[std::move(name)];
  275. int ncall;
  276. in.read((char*)&ncall, sizeof(ncall));
  277. int nval;
  278. in.read((char *)&nval, sizeof(nval));
  279. if (in.fail() || nval < 1) {
  280. LOG_ERR("%s: failed reading number of values for entry %d\n",__func__,i);
  281. m_stats = {};
  282. return false;
  283. }
  284. if (e.values.empty()) {
  285. e.values.resize(nval, 0);
  286. e.counts.resize(nval, 0);
  287. }
  288. std::vector<float> tmp(nval);
  289. in.read((char*)tmp.data(), nval*sizeof(float));
  290. if (in.fail()) {
  291. LOG_ERR("%s: failed reading data for entry %d\n",__func__,i);
  292. m_stats = {};
  293. return false;
  294. }
  295. // Recreate the state as expected by save_imatrix(), and corerct for weighted sum.
  296. for (int i = 0; i < nval; i++) {
  297. e.values[i] += tmp[i];
  298. e.counts[i] += ncall;
  299. }
  300. e.ncall += ncall;
  301. }
  302. return true;
  303. }
  304. static IMatrixCollector g_collector;
  305. static bool ik_collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  306. return g_collector.collect_imatrix(t, ask, user_data);
  307. }
  308. struct results_log_softmax {
  309. double log_softmax;
  310. float logit;
  311. float prob;
  312. };
  313. static std::vector<float> softmax(const std::vector<float> & logits) {
  314. std::vector<float> probs(logits.size());
  315. float max_logit = logits[0];
  316. for (float v : logits) {
  317. max_logit = std::max(max_logit, v);
  318. }
  319. double sum_exp = 0.0;
  320. for (size_t i = 0; i < logits.size(); i++) {
  321. // Subtract the maximum logit value from the current logit value for numerical stability
  322. const float logit = logits[i] - max_logit;
  323. const float exp_logit = expf(logit);
  324. sum_exp += exp_logit;
  325. probs[i] = exp_logit;
  326. }
  327. for (size_t i = 0; i < probs.size(); i++) {
  328. probs[i] /= sum_exp;
  329. }
  330. return probs;
  331. }
  332. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  333. float max_logit = logits[0];
  334. for (int i = 1; i < n_vocab; ++i) {
  335. max_logit = std::max(max_logit, logits[i]);
  336. }
  337. double sum_exp = 0.0;
  338. for (int i = 0; i < n_vocab; ++i) {
  339. sum_exp += expf(logits[i] - max_logit);
  340. }
  341. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  342. }
  343. static void process_logits(
  344. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  345. double & nll, double & nll2, float * logit_history, float * prob_history) {
  346. std::mutex mutex;
  347. int counter = 0;
  348. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  349. double local_nll = 0;
  350. double local_nll2 = 0;
  351. while (true) {
  352. std::unique_lock<std::mutex> lock(mutex);
  353. int i = counter++;
  354. if (i >= n_token) {
  355. nll += local_nll; nll2 += local_nll2;
  356. break;
  357. }
  358. lock.unlock();
  359. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  360. const double v = -results.log_softmax;
  361. local_nll += v;
  362. local_nll2 += v*v;
  363. logit_history[i] = results.logit;
  364. prob_history[i] = results.prob;
  365. }
  366. };
  367. for (auto & w : workers) {
  368. w = std::thread(compute);
  369. }
  370. compute();
  371. for (auto & w : workers) {
  372. w.join();
  373. }
  374. }
  375. static bool compute_imatrix(llama_context * ctx, const common_params & params) {
  376. const llama_model * model = llama_get_model(ctx);
  377. const llama_vocab * vocab = llama_model_get_vocab(model);
  378. const bool add_bos = llama_vocab_get_add_bos(vocab);
  379. const int n_ctx = llama_n_ctx(ctx);
  380. GGML_ASSERT(!llama_vocab_get_add_eos(vocab));
  381. auto tim1 = std::chrono::high_resolution_clock::now();
  382. LOG_INF("%s: tokenizing the input ..\n", __func__);
  383. std::vector<llama_token> tokens = common_tokenize(ctx, params.prompt, true);
  384. auto tim2 = std::chrono::high_resolution_clock::now();
  385. LOG_INF("%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  386. if (params.i_chunk > 0) {
  387. if (size_t((params.i_chunk + 2)*n_ctx) >= tokens.size()) {
  388. LOG_ERR("%s: there will be not enough tokens left after removing %d chunks\n", __func__, params.i_chunk);
  389. return false;
  390. }
  391. LOG_INF("%s: removing initial %d chunks (%d tokens)\n", __func__, params.i_chunk, params.i_chunk*n_ctx);
  392. tokens.erase(tokens.begin(), tokens.begin() + params.i_chunk*n_ctx);
  393. }
  394. if (int(tokens.size()) < 2*n_ctx) {
  395. LOG_ERR("%s: you need at least %d tokens for a context of %d tokens\n", __func__, 2*n_ctx, n_ctx);
  396. LOG_ERR("%s: the data file you provided tokenizes to only %zu tokens\n", __func__, tokens.size());
  397. return false;
  398. }
  399. std::vector<float> logit_history;
  400. std::vector<float> prob_history;
  401. if (params.compute_ppl) {
  402. logit_history.resize(tokens.size());
  403. prob_history.resize(tokens.size());
  404. }
  405. const int n_chunk_max = tokens.size() / n_ctx;
  406. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  407. const int n_vocab = llama_vocab_n_tokens(vocab);
  408. const int n_batch = params.n_batch;
  409. int count = 0;
  410. double nll = 0.0;
  411. double nll2 = 0.0;
  412. LOG_INF("%s: computing over %d chunks with batch_size %d\n", __func__, n_chunk, n_batch);
  413. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  414. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  415. std::vector<float> logits;
  416. if (params.compute_ppl && num_batches > 1) {
  417. logits.reserve((size_t)n_ctx * n_vocab);
  418. }
  419. for (int i = 0; i < n_chunk; ++i) {
  420. const int start = i * n_ctx;
  421. const int end = start + n_ctx;
  422. std::vector<float> logits;
  423. const auto t_start = std::chrono::high_resolution_clock::now();
  424. // clear the KV cache
  425. llama_kv_cache_clear(ctx);
  426. llama_batch batch = llama_batch_init(n_batch, 0, 1);
  427. for (int j = 0; j < num_batches; ++j) {
  428. const int batch_start = start + j * n_batch;
  429. const int batch_size = std::min(end - batch_start, n_batch);
  430. // save original token and restore it after eval
  431. const auto token_org = tokens[batch_start];
  432. // add BOS token for the first batch of each chunk
  433. if (add_bos && j == 0) {
  434. tokens[batch_start] = llama_vocab_bos(vocab);
  435. }
  436. common_batch_clear(batch);
  437. for (int i = 0; i < batch_size; i++) {
  438. common_batch_add(batch, tokens[batch_start + i], j*n_batch + i, {0}, true);
  439. }
  440. if (llama_decode(ctx, batch)) {
  441. LOG_ERR("%s : failed to eval\n", __func__);
  442. llama_batch_free(batch);
  443. return false;
  444. }
  445. // restore the original token in case it was set to BOS
  446. tokens[batch_start] = token_org;
  447. if (params.compute_ppl && num_batches > 1) {
  448. const auto * batch_logits = llama_get_logits(ctx);
  449. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  450. }
  451. }
  452. llama_batch_free(batch);
  453. const auto t_end = std::chrono::high_resolution_clock::now();
  454. if (i == 0) {
  455. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  456. LOG_INF("%s: %.2f seconds per pass - ETA ", __func__, t_total);
  457. int total_seconds = (int)(t_total * n_chunk);
  458. if (total_seconds >= 60*60) {
  459. LOG("%d hours ", total_seconds / (60*60));
  460. total_seconds = total_seconds % (60*60);
  461. }
  462. LOG("%.2f minutes\n", total_seconds / 60.0);
  463. }
  464. if (params.compute_ppl) {
  465. const int first = n_ctx/2;
  466. const auto * all_logits = num_batches > 1 ? logits.data() : llama_get_logits(ctx);
  467. process_logits(n_vocab, all_logits + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
  468. workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
  469. count += n_ctx - first - 1;
  470. LOG("[%d]%.4lf,", i + 1, std::exp(nll / count));
  471. fflush(stdout);
  472. logits.clear();
  473. }
  474. }
  475. LOG("\n");
  476. if (params.compute_ppl) {
  477. nll2 /= count;
  478. nll /= count;
  479. const double ppl = exp(nll);
  480. nll2 -= nll * nll;
  481. if (nll2 > 0) {
  482. nll2 = sqrt(nll2/(count-1));
  483. LOG("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  484. } else {
  485. LOG("Unexpected negative standard deviation of log(prob)\n");
  486. }
  487. }
  488. return true;
  489. }
  490. int main(int argc, char ** argv) {
  491. common_params params;
  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. }