imatrix.cpp 22 KB

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