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