imatrix.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <ctime>
  7. #include <sstream>
  8. #include <thread>
  9. #include <mutex>
  10. #include <vector>
  11. #include <fstream>
  12. #include <unordered_map>
  13. #include <algorithm>
  14. #if defined(_MSC_VER)
  15. #pragma warning(disable: 4244 4267) // possible loss of data
  16. #endif
  17. struct Stats {
  18. std::vector<float> values;
  19. int ncall = 0;
  20. };
  21. struct StatParams {
  22. std::string ofile = "imatrix.dat";
  23. int n_output_frequency = 10;
  24. int verbosity = 1;
  25. int keep_every = 0;
  26. bool collect_output_weight = false;
  27. };
  28. class IMatrixCollector {
  29. public:
  30. IMatrixCollector() = default;
  31. void set_parameters(StatParams&& params) { m_params = std::move(params); }
  32. bool collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data);
  33. void save_imatrix() const;
  34. bool load_imatrix(const char * file_name, bool add);
  35. static bool load_imatrix(const char * file_name, std::unordered_map<std::string, Stats>& imatrix);
  36. private:
  37. std::unordered_map<std::string, Stats> m_stats;
  38. StatParams m_params;
  39. std::mutex m_mutex;
  40. int m_last_call = 0;
  41. std::vector<float> m_src1_data;
  42. std::vector<int> m_ids; // the expert ids from ggml_mul_mat_id
  43. //
  44. void save_imatrix(const char * file_name) const;
  45. void keep_imatrix(int ncall) const;
  46. };
  47. bool IMatrixCollector::collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  48. GGML_UNUSED(user_data);
  49. const struct ggml_tensor * src0 = t->src[0];
  50. const struct ggml_tensor * src1 = t->src[1];
  51. // when ask is true, the scheduler wants to know if we are interested in data from this tensor
  52. // if we return true, a follow-up call will be made with ask=false in which we can do the actual collection
  53. if (ask) {
  54. if (t->op == GGML_OP_MUL_MAT_ID) return true; // collect all indirect matrix multiplications
  55. if (t->op != GGML_OP_MUL_MAT) return false;
  56. if (src1->ne[1] < 16 || src1->type != GGML_TYPE_F32) return false;
  57. if (!(strncmp(src0->name, "blk.", 4) == 0 || (m_params.collect_output_weight && strcmp(src0->name, "output.weight") == 0))) return false;
  58. return true;
  59. }
  60. std::lock_guard<std::mutex> lock(m_mutex);
  61. // copy the data from the GPU memory if needed
  62. const bool is_host = ggml_backend_buffer_is_host(src1->buffer);
  63. if (!is_host) {
  64. m_src1_data.resize(ggml_nelements(src1));
  65. ggml_backend_tensor_get(src1, m_src1_data.data(), 0, ggml_nbytes(src1));
  66. }
  67. const float * data = is_host ? (const float *) src1->data : m_src1_data.data();
  68. if (t->op == GGML_OP_MUL_MAT_ID) {
  69. const int idx = ((int32_t *) t->op_params)[0];
  70. const int n_as = ((int32_t *) t->op_params)[1];
  71. // the top-k selected expert ids are stored in the src0 tensor
  72. // for simplicity, always copy src0 to host, because it is small
  73. // take into account that src0 is not contiguous!
  74. GGML_ASSERT(src0->ne[1] == src1->ne[1]);
  75. GGML_ASSERT(n_as*ggml_nrows(src0)*sizeof(int) == GGML_PAD(ggml_nbytes(src0), n_as*sizeof(int)));
  76. m_ids.resize(ggml_nbytes(src0)/sizeof(int));
  77. ggml_backend_tensor_get(src0, m_ids.data(), 0, ggml_nbytes(src0));
  78. // loop over all possible experts, regardless if they are used or not in the batch
  79. // this is necessary to guarantee equal number of "ncall" for each tensor
  80. for (int ex = 0; ex < n_as; ++ex) {
  81. src0 = t->src[2 + ex];
  82. auto& e = m_stats[src0->name];
  83. if (e.values.empty()) {
  84. e.values.resize(src1->ne[0], 0);
  85. }
  86. else if (e.values.size() != (size_t)src1->ne[0]) {
  87. fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", src0->name, (int)e.values.size(), (int)src1->ne[0]);
  88. exit(1); //GGML_ASSERT(false);
  89. }
  90. // NOTE: since we select top-k experts, the number of calls for the expert tensors will be k times larger
  91. // using the following line, we can correct for that if needed
  92. //if (idx == t->src[0]->ne[0] - 1) ++e.ncall;
  93. ++e.ncall;
  94. if (m_params.verbosity > 1) {
  95. printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, src0->name, ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);
  96. }
  97. for (int row = 0; row < (int)src1->ne[1]; ++row) {
  98. const int excur = m_ids[row*n_as + idx];
  99. GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check
  100. if (excur != ex) continue;
  101. const float * x = data + row * src1->ne[0];
  102. for (int j = 0; j < (int)src1->ne[0]; ++j) {
  103. e.values[j] += x[j]*x[j];
  104. }
  105. }
  106. if (e.ncall > m_last_call) {
  107. m_last_call = e.ncall;
  108. if (m_last_call % m_params.n_output_frequency == 0) {
  109. save_imatrix();
  110. }
  111. if (m_params.keep_every > 0 && m_last_call%m_params.keep_every == 0) {
  112. keep_imatrix(m_last_call);
  113. }
  114. }
  115. }
  116. } else {
  117. auto& e = m_stats[src0->name];
  118. if (e.values.empty()) {
  119. e.values.resize(src1->ne[0], 0);
  120. }
  121. else if (e.values.size() != (size_t)src1->ne[0]) {
  122. fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", src0->name, (int)e.values.size(), (int)src1->ne[0]);
  123. exit(1); //GGML_ASSERT(false);
  124. }
  125. ++e.ncall;
  126. if (m_params.verbosity > 1) {
  127. printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, src0->name, ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);
  128. }
  129. for (int row = 0; row < (int)src1->ne[1]; ++row) {
  130. const float * x = data + row * src1->ne[0];
  131. for (int j = 0; j < (int)src1->ne[0]; ++j) {
  132. e.values[j] += x[j]*x[j];
  133. }
  134. }
  135. if (e.ncall > m_last_call) {
  136. m_last_call = e.ncall;
  137. if (m_last_call % m_params.n_output_frequency == 0) {
  138. save_imatrix();
  139. }
  140. if (m_params.keep_every > 0 && m_last_call%m_params.keep_every == 0) {
  141. keep_imatrix(m_last_call);
  142. }
  143. }
  144. }
  145. return true;
  146. }
  147. void IMatrixCollector::save_imatrix() const {
  148. save_imatrix(m_params.ofile.empty() ? "imatrix.dat" : m_params.ofile.c_str());
  149. }
  150. void IMatrixCollector::keep_imatrix(int ncall) const {
  151. auto file_name = m_params.ofile;
  152. if (file_name.empty()) file_name = "imatrix.dat";
  153. file_name += ".at_";
  154. file_name += std::to_string(ncall);
  155. save_imatrix(file_name.c_str());
  156. }
  157. void IMatrixCollector::save_imatrix(const char * fname) const {
  158. std::ofstream out(fname, std::ios::binary);
  159. int n_entries = m_stats.size();
  160. out.write((const char*)&n_entries, sizeof(n_entries));
  161. for (auto& p : m_stats) {
  162. int len = p.first.size();
  163. out.write((const char*)&len, sizeof(len));
  164. out.write(p.first.c_str(), len);
  165. out.write((const char*)&p.second.ncall, sizeof(p.second.ncall));
  166. int nval = p.second.values.size();
  167. out.write((const char*)&nval, sizeof(nval));
  168. if (nval > 0) out.write((const char*)p.second.values.data(), nval*sizeof(float));
  169. }
  170. if (m_params.verbosity > 0) {
  171. fprintf(stderr, "\n%s: stored collected data after %d chunks in %s\n",__func__,m_last_call,fname);
  172. }
  173. }
  174. bool IMatrixCollector::load_imatrix(const char * imatrix_file, std::unordered_map<std::string, Stats>& imatrix_data) {
  175. std::ifstream in(imatrix_file, std::ios::binary);
  176. if (!in) {
  177. printf("%s: failed to open %s\n",__func__,imatrix_file);
  178. return false;
  179. }
  180. int n_entries;
  181. in.read((char*)&n_entries, sizeof(n_entries));
  182. if (in.fail() || n_entries < 1) {
  183. printf("%s: no data in file %s\n", __func__, imatrix_file);
  184. return false;
  185. }
  186. for (int i = 0; i < n_entries; ++i) {
  187. int len; in.read((char *)&len, sizeof(len));
  188. std::vector<char> name_as_vec(len+1);
  189. in.read((char *)name_as_vec.data(), len);
  190. if (in.fail()) {
  191. printf("%s: failed reading name for entry %d from %s\n",__func__,i+1,imatrix_file);
  192. return false;
  193. }
  194. name_as_vec[len] = 0;
  195. std::string name{name_as_vec.data()};
  196. auto& e = imatrix_data[std::move(name)];
  197. int ncall;
  198. in.read((char*)&ncall, sizeof(ncall));
  199. int nval;
  200. in.read((char *)&nval, sizeof(nval));
  201. if (in.fail() || nval < 1) {
  202. printf("%s: failed reading number of values for entry %d\n",__func__,i);
  203. imatrix_data = {};
  204. return false;
  205. }
  206. e.values.resize(nval);
  207. in.read((char*)e.values.data(), nval*sizeof(float));
  208. if (in.fail()) {
  209. printf("%s: failed reading data for entry %d\n",__func__,i);
  210. imatrix_data = {};
  211. return false;
  212. }
  213. e.ncall = ncall;
  214. }
  215. return true;
  216. }
  217. bool IMatrixCollector::load_imatrix(const char * file_name, bool add) {
  218. if (!add) {
  219. m_stats.clear();
  220. }
  221. return load_imatrix(file_name, m_stats);
  222. }
  223. static IMatrixCollector g_collector;
  224. static bool ik_collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  225. return g_collector.collect_imatrix(t, ask, user_data);
  226. }
  227. struct results_log_softmax {
  228. double log_softmax;
  229. float logit;
  230. float prob;
  231. };
  232. static std::vector<float> softmax(const std::vector<float>& logits) {
  233. std::vector<float> probs(logits.size());
  234. float max_logit = logits[0];
  235. for (float v : logits) {
  236. max_logit = std::max(max_logit, v);
  237. }
  238. double sum_exp = 0.0;
  239. for (size_t i = 0; i < logits.size(); i++) {
  240. // Subtract the maximum logit value from the current logit value for numerical stability
  241. const float logit = logits[i] - max_logit;
  242. const float exp_logit = expf(logit);
  243. sum_exp += exp_logit;
  244. probs[i] = exp_logit;
  245. }
  246. for (size_t i = 0; i < probs.size(); i++) {
  247. probs[i] /= sum_exp;
  248. }
  249. return probs;
  250. }
  251. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  252. float max_logit = logits[0];
  253. for (int i = 1; i < n_vocab; ++i) {
  254. max_logit = std::max(max_logit, logits[i]);
  255. }
  256. double sum_exp = 0.0;
  257. for (int i = 0; i < n_vocab; ++i) {
  258. sum_exp += expf(logits[i] - max_logit);
  259. }
  260. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  261. }
  262. static void process_logits(
  263. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  264. double & nll, double & nll2, float * logit_history, float * prob_history
  265. ) {
  266. std::mutex mutex;
  267. int counter = 0;
  268. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  269. double local_nll = 0;
  270. double local_nll2 = 0;
  271. while (true) {
  272. std::unique_lock<std::mutex> lock(mutex);
  273. int i = counter++;
  274. if (i >= n_token) {
  275. nll += local_nll; nll2 += local_nll2;
  276. break;
  277. }
  278. lock.unlock();
  279. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  280. const double v = -results.log_softmax;
  281. local_nll += v;
  282. local_nll2 += v*v;
  283. logit_history[i] = results.logit;
  284. prob_history[i] = results.prob;
  285. }
  286. };
  287. for (auto & w : workers) {
  288. w = std::thread(compute);
  289. }
  290. compute();
  291. for (auto & w : workers) {
  292. w.join();
  293. }
  294. }
  295. static bool compute_imatrix(llama_context * ctx, const gpt_params & params, bool compute_ppl, int from_chunk) {
  296. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  297. const int n_ctx = llama_n_ctx(ctx);
  298. auto tim1 = std::chrono::high_resolution_clock::now();
  299. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  300. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  301. auto tim2 = std::chrono::high_resolution_clock::now();
  302. fprintf(stderr, "%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  303. if (from_chunk > 0) {
  304. if (size_t((from_chunk + 2)*n_ctx) >= tokens.size()) {
  305. fprintf(stderr, "%s: there will be not enough tokens left after removing %d chunks\n", __func__, from_chunk);
  306. return false;
  307. }
  308. fprintf(stderr, "%s: removing initial %d chunks (%d tokens)\n", __func__, from_chunk, from_chunk*n_ctx);
  309. tokens.erase(tokens.begin(), tokens.begin() + from_chunk*n_ctx);
  310. }
  311. if (int(tokens.size()) < 2*n_ctx) {
  312. fprintf(stderr, "%s: you need at least %d tokens for a context of %d tokens\n",__func__,2*n_ctx,
  313. n_ctx);
  314. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  315. return false;
  316. }
  317. std::vector<float> logit_history;
  318. std::vector<float> prob_history;
  319. if (compute_ppl) {
  320. logit_history.resize(tokens.size());
  321. prob_history.resize(tokens.size());
  322. }
  323. const int n_chunk_max = tokens.size() / n_ctx;
  324. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  325. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  326. const int n_batch = params.n_batch;
  327. int count = 0;
  328. double nll = 0.0;
  329. double nll2 = 0.0;
  330. fprintf(stderr, "%s: computing over %d chunks with batch_size %d\n", __func__, n_chunk, n_batch);
  331. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  332. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  333. std::vector<float> logits;
  334. if (compute_ppl && num_batches > 1) {
  335. logits.reserve((size_t)n_ctx * n_vocab);
  336. }
  337. for (int i = 0; i < n_chunk; ++i) {
  338. const int start = i * n_ctx;
  339. const int end = start + n_ctx;
  340. std::vector<float> logits;
  341. const auto t_start = std::chrono::high_resolution_clock::now();
  342. // clear the KV cache
  343. llama_kv_cache_clear(ctx);
  344. for (int j = 0; j < num_batches; ++j) {
  345. const int batch_start = start + j * n_batch;
  346. const int batch_size = std::min(end - batch_start, n_batch);
  347. // save original token and restore it after eval
  348. const auto token_org = tokens[batch_start];
  349. // add BOS token for the first batch of each chunk
  350. if (add_bos && j == 0) {
  351. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  352. }
  353. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  354. fprintf(stderr, "%s : failed to eval\n", __func__);
  355. return false;
  356. }
  357. // restore the original token in case it was set to BOS
  358. tokens[batch_start] = token_org;
  359. if (compute_ppl && num_batches > 1) {
  360. const auto * batch_logits = llama_get_logits(ctx);
  361. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  362. }
  363. }
  364. const auto t_end = std::chrono::high_resolution_clock::now();
  365. if (i == 0) {
  366. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  367. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  368. int total_seconds = (int)(t_total * n_chunk);
  369. if (total_seconds >= 60*60) {
  370. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  371. total_seconds = total_seconds % (60*60);
  372. }
  373. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  374. }
  375. if (compute_ppl) {
  376. const int first = n_ctx/2;
  377. const auto all_logits = num_batches > 1 ? logits.data() : llama_get_logits(ctx);
  378. process_logits(n_vocab, all_logits + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
  379. workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
  380. count += n_ctx - first - 1;
  381. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  382. fflush(stdout);
  383. logits.clear();
  384. }
  385. }
  386. printf("\n");
  387. if (compute_ppl) {
  388. nll2 /= count;
  389. nll /= count;
  390. const double ppl = exp(nll);
  391. nll2 -= nll * nll;
  392. if (nll2 > 0) {
  393. nll2 = sqrt(nll2/(count-1));
  394. printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  395. } else {
  396. printf("Unexpected negative standard deviation of log(prob)\n");
  397. }
  398. }
  399. return true;
  400. }
  401. int main(int argc, char ** argv) {
  402. StatParams sparams;
  403. std::string prev_result_file;
  404. std::string combine_files;
  405. bool compute_ppl = true;
  406. int from_chunk = 0;
  407. std::vector<char*> args;
  408. args.push_back(argv[0]);
  409. int iarg = 1;
  410. for (; iarg < argc-1; ++iarg) {
  411. std::string arg{argv[iarg]};
  412. if (arg == "-o" || arg == "--output-file") {
  413. sparams.ofile = argv[++iarg];
  414. }
  415. else if (arg == "-ofreq" || arg == "--output-frequency") {
  416. sparams.n_output_frequency = std::stoi(argv[++iarg]);
  417. }
  418. else if (arg == "-ow" || arg == "--output-weight") {
  419. sparams.collect_output_weight = std::stoi(argv[++iarg]);
  420. }
  421. else if (arg == "--verbosity") {
  422. sparams.verbosity = std::stoi(argv[++iarg]);
  423. } else if (arg == "--no-ppl") {
  424. compute_ppl = false;
  425. } else if (arg == "--keep-imatrix") {
  426. sparams.keep_every = std::stoi(argv[++iarg]);
  427. } else if (arg == "--continue-from") {
  428. prev_result_file = argv[++iarg];
  429. } else if (arg == "--combine") {
  430. combine_files = argv[++iarg];
  431. }
  432. else if (arg == "--from-chunk") {
  433. from_chunk = std::stoi(argv[++iarg]);
  434. } else {
  435. args.push_back(argv[iarg]);
  436. }
  437. }
  438. if (iarg < argc) {
  439. std::string arg{argv[iarg]};
  440. if (arg == "--no-ppl") {
  441. compute_ppl = false;
  442. } else {
  443. args.push_back(argv[iarg]);
  444. }
  445. }
  446. g_collector.set_parameters(std::move(sparams));
  447. if (!combine_files.empty()) {
  448. std::vector<std::string> files;
  449. size_t pos = 0;
  450. while (true) {
  451. auto new_pos = combine_files.find(',', pos);
  452. if (new_pos != std::string::npos) {
  453. files.emplace_back(combine_files.substr(pos, new_pos - pos));
  454. pos = new_pos + 1;
  455. } else {
  456. files.emplace_back(combine_files.substr(pos));
  457. break;
  458. }
  459. }
  460. if (files.size() < 2) {
  461. fprintf(stderr, "You must provide at least two comma separated files to use --combine\n");
  462. return 1;
  463. }
  464. printf("Combining the following %d files\n", int(files.size()));
  465. for (auto& file : files) {
  466. printf(" %s\n", file.c_str());
  467. if (!g_collector.load_imatrix(file.c_str(), true)) {
  468. fprintf(stderr, "Failed to load %s\n", file.c_str());
  469. return 1;
  470. }
  471. }
  472. g_collector.save_imatrix();
  473. return 0;
  474. }
  475. if (!prev_result_file.empty()) {
  476. if (!g_collector.load_imatrix(prev_result_file.c_str(), false)) {
  477. fprintf(stderr, "=============== Failed to load %s\n", prev_result_file.c_str());
  478. return 1;
  479. }
  480. }
  481. gpt_params params;
  482. params.n_batch = 512;
  483. if (!gpt_params_parse(args.size(), args.data(), params)) {
  484. return 1;
  485. }
  486. params.logits_all = true;
  487. params.n_batch = std::min(params.n_batch, params.n_ctx);
  488. print_build_info();
  489. if (params.seed == LLAMA_DEFAULT_SEED) {
  490. params.seed = time(NULL);
  491. }
  492. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  493. std::mt19937 rng(params.seed);
  494. if (params.random_prompt) {
  495. params.prompt = gpt_random_prompt(rng);
  496. }
  497. llama_backend_init(params.numa);
  498. llama_model_params mparams = llama_model_params_from_gpt_params(params);
  499. llama_model * model = llama_load_model_from_file(params.model.c_str(), mparams);
  500. if (model == NULL) {
  501. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  502. return 1;
  503. }
  504. llama_context_params cparams = llama_context_params_from_gpt_params(params);
  505. // pass the callback to the backend scheduler
  506. // it will be executed for each node during the graph computation
  507. cparams.cb_eval = ik_collect_imatrix;
  508. cparams.cb_eval_user_data = NULL;
  509. llama_context * ctx = llama_new_context_with_model(model, cparams);
  510. if (ctx == NULL) {
  511. fprintf(stderr, "%s: error: unable to create context\n", __func__);
  512. return 1;
  513. }
  514. const int n_ctx_train = llama_n_ctx_train(model);
  515. if (params.n_ctx > n_ctx_train) {
  516. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  517. __func__, n_ctx_train, params.n_ctx);
  518. }
  519. // print system information
  520. {
  521. fprintf(stderr, "\n");
  522. fprintf(stderr, "%s\n", get_system_info(params).c_str());
  523. }
  524. bool OK = compute_imatrix(ctx, params, compute_ppl, from_chunk);
  525. if (!OK) {
  526. return 1;
  527. }
  528. g_collector.save_imatrix();
  529. llama_print_timings(ctx);
  530. llama_free(ctx);
  531. llama_free_model(model);
  532. llama_backend_free();
  533. return 0;
  534. }