imatrix.cpp 23 KB

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