imatrix.cpp 24 KB

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