imatrix.cpp 22 KB

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