imatrix.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. static void print_usage(int, char ** argv) {
  18. LOG_TEE("\nexample usage:\n");
  19. LOG_TEE("\n %s \\\n"
  20. " -m model.gguf -f some-text.txt [-o imatrix.dat] [--process-output] [--verbosity 1] \\\n"
  21. " [--no-ppl] [--chunk 123] [--output-frequency 10] [--save-frequency 0] \\\n"
  22. " [--in-file imatrix-prev-0.dat --in-file imatrix-prev-1.dat ...]\n" , argv[0]);
  23. LOG_TEE("\n");
  24. }
  25. struct Stats {
  26. std::vector<float> values;
  27. std::vector<int> counts;
  28. int ncall = 0;
  29. };
  30. class IMatrixCollector {
  31. public:
  32. IMatrixCollector() = default;
  33. void set_params(gpt_params params) { m_params = std::move(params); }
  34. bool collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data);
  35. void save_imatrix(int ncall = -1) const;
  36. bool load_imatrix(const char * file_name);
  37. private:
  38. std::unordered_map<std::string, Stats> m_stats;
  39. gpt_params m_params;
  40. std::mutex m_mutex;
  41. int m_last_call = 0;
  42. std::vector<float> m_src1_data;
  43. std::vector<char> m_ids; // the expert ids from ggml_mul_mat_id
  44. };
  45. // remove any prefix and suffixes from the name
  46. // CUDA0#blk.0.attn_k.weight#0 => blk.0.attn_k.weight
  47. static std::string filter_tensor_name(const char * name) {
  48. std::string wname;
  49. const char * p = strchr(name, '#');
  50. if (p != NULL) {
  51. p = p + 1;
  52. const char * q = strchr(p, '#');
  53. if (q != NULL) {
  54. wname = std::string(p, q - p);
  55. } else {
  56. wname = p;
  57. }
  58. } else {
  59. wname = name;
  60. }
  61. return wname;
  62. }
  63. bool IMatrixCollector::collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  64. GGML_UNUSED(user_data);
  65. const struct ggml_tensor * src0 = t->src[0];
  66. const struct ggml_tensor * src1 = t->src[1];
  67. std::string wname = filter_tensor_name(src0->name);
  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. // why are small batches ignored (<16 tokens)?
  74. if (src1->ne[1] < 16 || src1->type != GGML_TYPE_F32) return false;
  75. if (!(wname.substr(0, 4) == "blk." || (m_params.process_output && wname == "output.weight"))) return false;
  76. return true;
  77. }
  78. std::lock_guard<std::mutex> lock(m_mutex);
  79. // copy the data from the GPU memory if needed
  80. const bool is_host = ggml_backend_buffer_is_host(src1->buffer);
  81. if (!is_host) {
  82. m_src1_data.resize(ggml_nelements(src1));
  83. ggml_backend_tensor_get(src1, m_src1_data.data(), 0, ggml_nbytes(src1));
  84. }
  85. const float * data = is_host ? (const float *) src1->data : m_src1_data.data();
  86. // this has been adapted to the new format of storing merged experts in a single 3d tensor
  87. // ref: https://github.com/ggerganov/llama.cpp/pull/6387
  88. if (t->op == GGML_OP_MUL_MAT_ID) {
  89. // ids -> [n_experts_used, n_tokens]
  90. // src1 -> [cols, n_expert_used, n_tokens]
  91. const ggml_tensor * ids = t->src[2];
  92. const int n_as = src0->ne[2];
  93. const int n_ids = ids->ne[0];
  94. // the top-k selected expert ids are stored in the ids tensor
  95. // for simplicity, always copy ids to host, because it is small
  96. // take into account that ids is not contiguous!
  97. GGML_ASSERT(ids->ne[1] == src1->ne[2]);
  98. m_ids.resize(ggml_nbytes(ids));
  99. ggml_backend_tensor_get(ids, m_ids.data(), 0, ggml_nbytes(ids));
  100. auto & e = m_stats[wname];
  101. ++e.ncall;
  102. if (e.values.empty()) {
  103. e.values.resize(src1->ne[0]*n_as, 0);
  104. e.counts.resize(src1->ne[0]*n_as, 0);
  105. }
  106. else if (e.values.size() != (size_t)src1->ne[0]*n_as) {
  107. fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]*n_as);
  108. exit(1); //GGML_ABORT("fatal error");
  109. }
  110. if (m_params.verbosity > 1) {
  111. 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[2], (int)src1->type);
  112. }
  113. // loop over all possible experts, regardless if they are used or not in the batch
  114. for (int ex = 0; ex < n_as; ++ex) {
  115. size_t e_start = ex*src1->ne[0];
  116. for (int idx = 0; idx < n_ids; ++idx) {
  117. for (int row = 0; row < (int)src1->ne[2]; ++row) {
  118. const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);
  119. GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check
  120. if (excur != ex) continue;
  121. const int64_t i11 = idx % src1->ne[1];
  122. const int64_t i12 = row;
  123. const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);
  124. for (int j = 0; j < (int)src1->ne[0]; ++j) {
  125. e.values[e_start + j] += x[j]*x[j];
  126. e.counts[e_start + j]++;
  127. if (!std::isfinite(e.values[e_start + j])) {
  128. fprintf(stderr, "%f detected in %s\n", e.values[e_start + j], wname.c_str());
  129. exit(1);
  130. }
  131. }
  132. }
  133. }
  134. if (e.ncall > m_last_call) {
  135. m_last_call = e.ncall;
  136. if (m_last_call % m_params.n_out_freq == 0) {
  137. save_imatrix();
  138. }
  139. if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {
  140. save_imatrix(m_last_call);
  141. }
  142. }
  143. }
  144. } else {
  145. auto & e = m_stats[wname];
  146. if (e.values.empty()) {
  147. e.values.resize(src1->ne[0], 0);
  148. e.counts.resize(src1->ne[0], 0);
  149. }
  150. else if (e.values.size() != (size_t)src1->ne[0]) {
  151. fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);
  152. exit(1); //GGML_ABORT("fatal error");
  153. }
  154. ++e.ncall;
  155. if (m_params.verbosity > 1) {
  156. 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);
  157. }
  158. for (int row = 0; row < (int)src1->ne[1]; ++row) {
  159. const float * x = data + row * src1->ne[0];
  160. for (int j = 0; j < (int)src1->ne[0]; ++j) {
  161. e.values[j] += x[j]*x[j];
  162. e.counts[j]++;
  163. if (!std::isfinite(e.values[j])) {
  164. fprintf(stderr, "%f detected in %s\n", e.values[j], wname.c_str());
  165. exit(1);
  166. }
  167. }
  168. }
  169. if (e.ncall > m_last_call) {
  170. m_last_call = e.ncall;
  171. if (m_last_call % m_params.n_out_freq == 0) {
  172. save_imatrix();
  173. }
  174. if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {
  175. save_imatrix(m_last_call);
  176. }
  177. }
  178. }
  179. return true;
  180. }
  181. void IMatrixCollector::save_imatrix(int ncall) const {
  182. auto fname = m_params.out_file;
  183. if (fname.empty()) {
  184. fname = "imatrix.dat";
  185. }
  186. if (ncall > 0) {
  187. fname += ".at_";
  188. fname += std::to_string(ncall);
  189. }
  190. // avoid writing imatrix entries that do not have full data
  191. // this can happen with MoE models where some of the experts end up not being exercised by the provided training data
  192. int n_entries = 0;
  193. std::vector<std::string> to_store;
  194. bool is_first = true; // for printing
  195. for (const auto & kv : m_stats) {
  196. const int n_all = kv.second.counts.size();
  197. if (n_all == 0) {
  198. continue;
  199. }
  200. int n_zeros = 0;
  201. for (const int c : kv.second.counts) {
  202. if (c == 0) {
  203. n_zeros++;
  204. }
  205. }
  206. if (n_zeros != 0 && is_first) {
  207. fprintf(stderr, "\n");
  208. is_first = false;
  209. }
  210. if (n_zeros == n_all) {
  211. fprintf(stderr, "%s: entry '%40s' has no data - skipping\n", __func__, kv.first.c_str());
  212. continue;
  213. }
  214. if (n_zeros > 0) {
  215. fprintf(stderr, "%s: entry '%40s' has partial data (%.2f%%) - skipping\n", __func__, kv.first.c_str(), 100.0f * (n_all - n_zeros) / n_all);
  216. continue;
  217. }
  218. n_entries++;
  219. to_store.push_back(kv.first);
  220. }
  221. if (to_store.size() < m_stats.size()) {
  222. fprintf(stderr, "%s: warning: storing only %zu out of %zu entries\n", __func__, to_store.size(), m_stats.size());
  223. }
  224. std::ofstream out(fname, std::ios::binary);
  225. out.write((const char *) &n_entries, sizeof(n_entries));
  226. for (const auto & name : to_store) {
  227. const auto & stat = m_stats.at(name);
  228. int len = name.size();
  229. out.write((const char *) &len, sizeof(len));
  230. out.write(name.c_str(), len);
  231. out.write((const char *) &stat.ncall, sizeof(stat.ncall));
  232. int nval = stat.values.size();
  233. out.write((const char *) &nval, sizeof(nval));
  234. if (nval > 0) {
  235. std::vector<float> tmp(nval);
  236. for (int i = 0; i < nval; i++) {
  237. tmp[i] = (stat.values[i] / static_cast<float>(stat.counts[i])) * static_cast<float>(stat.ncall);
  238. }
  239. out.write((const char*)tmp.data(), nval*sizeof(float));
  240. }
  241. }
  242. // Write the number of call the matrix was computed with
  243. out.write((const char *) &m_last_call, sizeof(m_last_call));
  244. // Write the input filename at the end of the file to later on specify it in quantize
  245. {
  246. int len = m_params.prompt_file.size();
  247. out.write((const char *) &len, sizeof(len));
  248. out.write(m_params.prompt_file.c_str(), len);
  249. }
  250. if (m_params.verbosity > 0) {
  251. fprintf(stderr, "\n%s: stored collected data after %d chunks in %s\n", __func__, m_last_call, fname.c_str());
  252. }
  253. }
  254. bool IMatrixCollector::load_imatrix(const char * fname) {
  255. std::ifstream in(fname, std::ios::binary);
  256. if (!in) {
  257. printf("%s: failed to open %s\n",__func__, fname);
  258. return false;
  259. }
  260. int n_entries;
  261. in.read((char*)&n_entries, sizeof(n_entries));
  262. if (in.fail() || n_entries < 1) {
  263. printf("%s: no data in file %s\n", __func__, fname);
  264. return false;
  265. }
  266. for (int i = 0; i < n_entries; ++i) {
  267. int len; in.read((char *)&len, sizeof(len));
  268. std::vector<char> name_as_vec(len+1);
  269. in.read((char *)name_as_vec.data(), len);
  270. if (in.fail()) {
  271. printf("%s: failed reading name for entry %d from %s\n",__func__,i+1, fname);
  272. return false;
  273. }
  274. name_as_vec[len] = 0;
  275. std::string name{name_as_vec.data()};
  276. auto & e = m_stats[std::move(name)];
  277. int ncall;
  278. in.read((char*)&ncall, sizeof(ncall));
  279. int nval;
  280. in.read((char *)&nval, sizeof(nval));
  281. if (in.fail() || nval < 1) {
  282. printf("%s: failed reading number of values for entry %d\n",__func__,i);
  283. m_stats = {};
  284. return false;
  285. }
  286. if (e.values.empty()) {
  287. e.values.resize(nval, 0);
  288. e.counts.resize(nval, 0);
  289. }
  290. std::vector<float> tmp(nval);
  291. in.read((char*)tmp.data(), nval*sizeof(float));
  292. if (in.fail()) {
  293. printf("%s: failed reading data for entry %d\n",__func__,i);
  294. m_stats = {};
  295. return false;
  296. }
  297. // Recreate the state as expected by save_imatrix(), and corerct for weighted sum.
  298. for (int i = 0; i < nval; i++) {
  299. e.values[i] += tmp[i];
  300. e.counts[i] += ncall;
  301. }
  302. e.ncall += ncall;
  303. }
  304. return true;
  305. }
  306. static IMatrixCollector g_collector;
  307. static bool ik_collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  308. return g_collector.collect_imatrix(t, ask, user_data);
  309. }
  310. struct results_log_softmax {
  311. double log_softmax;
  312. float logit;
  313. float prob;
  314. };
  315. static std::vector<float> softmax(const std::vector<float> & logits) {
  316. std::vector<float> probs(logits.size());
  317. float max_logit = logits[0];
  318. for (float v : logits) {
  319. max_logit = std::max(max_logit, v);
  320. }
  321. double sum_exp = 0.0;
  322. for (size_t i = 0; i < logits.size(); i++) {
  323. // Subtract the maximum logit value from the current logit value for numerical stability
  324. const float logit = logits[i] - max_logit;
  325. const float exp_logit = expf(logit);
  326. sum_exp += exp_logit;
  327. probs[i] = exp_logit;
  328. }
  329. for (size_t i = 0; i < probs.size(); i++) {
  330. probs[i] /= sum_exp;
  331. }
  332. return probs;
  333. }
  334. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  335. float max_logit = logits[0];
  336. for (int i = 1; i < n_vocab; ++i) {
  337. max_logit = std::max(max_logit, logits[i]);
  338. }
  339. double sum_exp = 0.0;
  340. for (int i = 0; i < n_vocab; ++i) {
  341. sum_exp += expf(logits[i] - max_logit);
  342. }
  343. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  344. }
  345. static void process_logits(
  346. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  347. double & nll, double & nll2, float * logit_history, float * prob_history) {
  348. std::mutex mutex;
  349. int counter = 0;
  350. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  351. double local_nll = 0;
  352. double local_nll2 = 0;
  353. while (true) {
  354. std::unique_lock<std::mutex> lock(mutex);
  355. int i = counter++;
  356. if (i >= n_token) {
  357. nll += local_nll; nll2 += local_nll2;
  358. break;
  359. }
  360. lock.unlock();
  361. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  362. const double v = -results.log_softmax;
  363. local_nll += v;
  364. local_nll2 += v*v;
  365. logit_history[i] = results.logit;
  366. prob_history[i] = results.prob;
  367. }
  368. };
  369. for (auto & w : workers) {
  370. w = std::thread(compute);
  371. }
  372. compute();
  373. for (auto & w : workers) {
  374. w.join();
  375. }
  376. }
  377. static bool compute_imatrix(llama_context * ctx, const gpt_params & params) {
  378. const bool add_bos = llama_add_bos_token(llama_get_model(ctx));
  379. GGML_ASSERT(!llama_add_eos_token(llama_get_model(ctx)));
  380. const int n_ctx = llama_n_ctx(ctx);
  381. auto tim1 = std::chrono::high_resolution_clock::now();
  382. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  383. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, true);
  384. auto tim2 = std::chrono::high_resolution_clock::now();
  385. fprintf(stderr, "%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  386. if (params.i_chunk > 0) {
  387. if (size_t((params.i_chunk + 2)*n_ctx) >= tokens.size()) {
  388. fprintf(stderr, "%s: there will be not enough tokens left after removing %d chunks\n", __func__, params.i_chunk);
  389. return false;
  390. }
  391. fprintf(stderr, "%s: removing initial %d chunks (%d tokens)\n", __func__, params.i_chunk, params.i_chunk*n_ctx);
  392. tokens.erase(tokens.begin(), tokens.begin() + params.i_chunk*n_ctx);
  393. }
  394. if (int(tokens.size()) < 2*n_ctx) {
  395. fprintf(stderr, "%s: you need at least %d tokens for a context of %d tokens\n",__func__,2*n_ctx,
  396. n_ctx);
  397. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  398. return false;
  399. }
  400. std::vector<float> logit_history;
  401. std::vector<float> prob_history;
  402. if (params.compute_ppl) {
  403. logit_history.resize(tokens.size());
  404. prob_history.resize(tokens.size());
  405. }
  406. const int n_chunk_max = tokens.size() / n_ctx;
  407. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  408. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  409. const int n_batch = params.n_batch;
  410. int count = 0;
  411. double nll = 0.0;
  412. double nll2 = 0.0;
  413. fprintf(stderr, "%s: computing over %d chunks with batch_size %d\n", __func__, n_chunk, n_batch);
  414. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  415. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  416. std::vector<float> logits;
  417. if (params.compute_ppl && num_batches > 1) {
  418. logits.reserve((size_t)n_ctx * n_vocab);
  419. }
  420. for (int i = 0; i < n_chunk; ++i) {
  421. const int start = i * n_ctx;
  422. const int end = start + n_ctx;
  423. std::vector<float> logits;
  424. const auto t_start = std::chrono::high_resolution_clock::now();
  425. // clear the KV cache
  426. llama_kv_cache_clear(ctx);
  427. for (int j = 0; j < num_batches; ++j) {
  428. const int batch_start = start + j * n_batch;
  429. const int batch_size = std::min(end - batch_start, n_batch);
  430. // save original token and restore it after eval
  431. const auto token_org = tokens[batch_start];
  432. // add BOS token for the first batch of each chunk
  433. if (add_bos && j == 0) {
  434. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  435. }
  436. // TODO: use batch.logits to save computations instead of relying on logits_all == true
  437. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  438. fprintf(stderr, "%s : failed to eval\n", __func__);
  439. return false;
  440. }
  441. // restore the original token in case it was set to BOS
  442. tokens[batch_start] = token_org;
  443. if (params.compute_ppl && num_batches > 1) {
  444. const auto * batch_logits = llama_get_logits(ctx);
  445. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  446. }
  447. }
  448. const auto t_end = std::chrono::high_resolution_clock::now();
  449. if (i == 0) {
  450. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  451. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  452. int total_seconds = (int)(t_total * n_chunk);
  453. if (total_seconds >= 60*60) {
  454. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  455. total_seconds = total_seconds % (60*60);
  456. }
  457. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  458. }
  459. if (params.compute_ppl) {
  460. const int first = n_ctx/2;
  461. const auto all_logits = num_batches > 1 ? logits.data() : llama_get_logits(ctx);
  462. process_logits(n_vocab, all_logits + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
  463. workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
  464. count += n_ctx - first - 1;
  465. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  466. fflush(stdout);
  467. logits.clear();
  468. }
  469. }
  470. printf("\n");
  471. if (params.compute_ppl) {
  472. nll2 /= count;
  473. nll /= count;
  474. const double ppl = exp(nll);
  475. nll2 -= nll * nll;
  476. if (nll2 > 0) {
  477. nll2 = sqrt(nll2/(count-1));
  478. printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  479. } else {
  480. printf("Unexpected negative standard deviation of log(prob)\n");
  481. }
  482. }
  483. return true;
  484. }
  485. int main(int argc, char ** argv) {
  486. gpt_params params;
  487. params.n_ctx = 512;
  488. params.logits_all = true;
  489. params.verbosity = 1;
  490. auto options = gpt_params_parser_init(params, LLAMA_EXAMPLE_IMATRIX, print_usage);
  491. if (!gpt_params_parse(argc, argv, params, options)) {
  492. return 1;
  493. }
  494. params.n_batch = std::min(params.n_batch, params.n_ctx);
  495. g_collector.set_params(params);
  496. for (const auto & in_file : params.in_files) {
  497. printf("%s : loading imatrix from '%s'\n", __func__, in_file.c_str());
  498. if (!g_collector.load_imatrix(in_file.c_str())) {
  499. fprintf(stderr, "%s : failed to load %s\n", __func__, in_file.c_str());
  500. return 1;
  501. }
  502. }
  503. if (params.in_files.size() > 1) {
  504. printf("%s : saving combined imatrix to '%s'\n", __func__, params.out_file.c_str());
  505. g_collector.save_imatrix();
  506. }
  507. llama_backend_init();
  508. llama_numa_init(params.numa);
  509. // pass the callback to the backend scheduler
  510. // it will be executed for each node during the graph computation
  511. params.cb_eval = ik_collect_imatrix;
  512. params.cb_eval_user_data = NULL;
  513. params.warmup = false;
  514. // init
  515. llama_init_result llama_init = llama_init_from_gpt_params(params);
  516. llama_model * model = llama_init.model;
  517. llama_context * ctx = llama_init.context;
  518. if (model == nullptr || ctx == nullptr) {
  519. fprintf(stderr, "%s : failed to init\n", __func__);
  520. return 1;
  521. }
  522. const int n_ctx_train = llama_n_ctx_train(model);
  523. if (params.n_ctx > n_ctx_train) {
  524. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  525. __func__, n_ctx_train, params.n_ctx);
  526. }
  527. // print system information
  528. {
  529. fprintf(stderr, "\n");
  530. fprintf(stderr, "%s\n", gpt_params_get_system_info(params).c_str());
  531. }
  532. if (!compute_imatrix(ctx, params)) {
  533. return 1;
  534. }
  535. g_collector.save_imatrix();
  536. LOG_TEE("\n");
  537. llama_perf_print(ctx, LLAMA_PERF_TYPE_CONTEXT);
  538. llama_free(ctx);
  539. llama_free_model(model);
  540. llama_backend_free();
  541. return 0;
  542. }