1
0

imatrix.cpp 22 KB

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