imatrix.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <ctime>
  7. #include <sstream>
  8. #include <thread>
  9. #include <mutex>
  10. #include <vector>
  11. #include <fstream>
  12. #include <unordered_map>
  13. #include <algorithm>
  14. #if defined(_MSC_VER)
  15. #pragma warning(disable: 4244 4267) // possible loss of data
  16. #endif
  17. struct Stats {
  18. std::vector<float> values;
  19. int ncall = 0;
  20. };
  21. struct StatParams {
  22. std::string ofile = "imatrix.dat";
  23. int n_output_frequency = 10;
  24. int verbosity = 1;
  25. int keep_every = 0;
  26. bool collect_output_weight = false;
  27. };
  28. class IMatrixCollector {
  29. public:
  30. IMatrixCollector() = default;
  31. void set_parameters(StatParams&& params) { m_params = std::move(params); }
  32. bool collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data);
  33. void save_imatrix() const;
  34. private:
  35. std::unordered_map<std::string, Stats> m_stats;
  36. StatParams m_params;
  37. std::mutex m_mutex;
  38. int m_last_call = 0;
  39. std::vector<float> m_src1_data;
  40. std::vector<int> m_ids; // the expert ids from ggml_mul_mat_id
  41. //
  42. void save_imatrix(const char * file_name) const;
  43. void keep_imatrix(int ncall) const;
  44. };
  45. bool IMatrixCollector::collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  46. GGML_UNUSED(user_data);
  47. const struct ggml_tensor * src0 = t->src[0];
  48. const struct ggml_tensor * src1 = t->src[1];
  49. // when ask is true, the scheduler wants to know if we are interested in data from this tensor
  50. // if we return true, a follow-up call will be made with ask=false in which we can do the actual collection
  51. if (ask) {
  52. if (t->op == GGML_OP_MUL_MAT_ID) return true; // collect all indirect matrix multiplications
  53. if (t->op != GGML_OP_MUL_MAT) return false;
  54. if (src1->ne[1] < 16 || src1->type != GGML_TYPE_F32) return false;
  55. if (!(strncmp(src0->name, "blk.", 4) == 0 || (m_params.collect_output_weight && strcmp(src0->name, "output.weight") == 0))) return false;
  56. return true;
  57. }
  58. std::lock_guard<std::mutex> lock(m_mutex);
  59. // copy the data from the GPU memory if needed
  60. const bool is_host = ggml_backend_buffer_is_host(src1->buffer);
  61. if (!is_host) {
  62. m_src1_data.resize(ggml_nelements(src1));
  63. ggml_backend_tensor_get(src1, m_src1_data.data(), 0, ggml_nbytes(src1));
  64. }
  65. const float * data = is_host ? (const float *) src1->data : m_src1_data.data();
  66. if (t->op == GGML_OP_MUL_MAT_ID) {
  67. const int idx = ((int32_t *) t->op_params)[0];
  68. const int n_as = ((int32_t *) t->op_params)[1];
  69. // the top-k selected expert ids are stored in the src0 tensor
  70. // for simplicity, always copy src0 to host, because it is small
  71. // take into account that src0 is not contiguous!
  72. GGML_ASSERT(src0->ne[1] == src1->ne[1]);
  73. GGML_ASSERT(n_as*ggml_nrows(src0)*sizeof(int) == GGML_PAD(ggml_nbytes(src0), n_as*sizeof(int)));
  74. m_ids.resize(ggml_nbytes(src0)/sizeof(int));
  75. ggml_backend_tensor_get(src0, m_ids.data(), 0, ggml_nbytes(src0));
  76. // loop over all possible experts, regardless if they are used or not in the batch
  77. // this is necessary to guarantee equal number of "ncall" for each tensor
  78. for (int ex = 0; ex < n_as; ++ex) {
  79. src0 = t->src[2 + ex];
  80. auto& e = m_stats[src0->name];
  81. if (e.values.empty()) {
  82. e.values.resize(src1->ne[0], 0);
  83. }
  84. else if (e.values.size() != (size_t)src1->ne[0]) {
  85. fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", src0->name, (int)e.values.size(), (int)src1->ne[0]);
  86. exit(1); //GGML_ASSERT(false);
  87. }
  88. // NOTE: since we select top-k experts, the number of calls for the expert tensors will be k times larger
  89. // using the following line, we can correct for that if needed
  90. //if (idx == t->src[0]->ne[0] - 1) ++e.ncall;
  91. ++e.ncall;
  92. if (m_params.verbosity > 1) {
  93. printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, src0->name, ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);
  94. }
  95. for (int row = 0; row < (int)src1->ne[1]; ++row) {
  96. const int excur = m_ids[row*n_as + idx];
  97. GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check
  98. if (excur != ex) continue;
  99. const float * x = data + row * src1->ne[0];
  100. for (int j = 0; j < (int)src1->ne[0]; ++j) {
  101. e.values[j] += x[j]*x[j];
  102. }
  103. }
  104. if (e.ncall > m_last_call) {
  105. m_last_call = e.ncall;
  106. if (m_last_call % m_params.n_output_frequency == 0) {
  107. save_imatrix();
  108. }
  109. if (m_params.keep_every > 0 && m_last_call%m_params.keep_every == 0) {
  110. keep_imatrix(m_last_call);
  111. }
  112. }
  113. }
  114. } else {
  115. auto& e = m_stats[src0->name];
  116. if (e.values.empty()) {
  117. e.values.resize(src1->ne[0], 0);
  118. }
  119. else if (e.values.size() != (size_t)src1->ne[0]) {
  120. fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", src0->name, (int)e.values.size(), (int)src1->ne[0]);
  121. exit(1); //GGML_ASSERT(false);
  122. }
  123. ++e.ncall;
  124. if (m_params.verbosity > 1) {
  125. printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, src0->name, ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);
  126. }
  127. for (int row = 0; row < (int)src1->ne[1]; ++row) {
  128. const float * x = data + row * src1->ne[0];
  129. for (int j = 0; j < (int)src1->ne[0]; ++j) {
  130. e.values[j] += x[j]*x[j];
  131. }
  132. }
  133. if (e.ncall > m_last_call) {
  134. m_last_call = e.ncall;
  135. if (m_last_call % m_params.n_output_frequency == 0) {
  136. save_imatrix();
  137. }
  138. if (m_params.keep_every > 0 && m_last_call%m_params.keep_every == 0) {
  139. keep_imatrix(m_last_call);
  140. }
  141. }
  142. }
  143. return true;
  144. }
  145. void IMatrixCollector::save_imatrix() const {
  146. save_imatrix(m_params.ofile.empty() ? "imatrix.dat" : m_params.ofile.c_str());
  147. }
  148. void IMatrixCollector::keep_imatrix(int ncall) const {
  149. auto file_name = m_params.ofile;
  150. if (file_name.empty()) file_name = "imatrix.dat";
  151. file_name += ".at_";
  152. file_name += std::to_string(ncall);
  153. save_imatrix(file_name.c_str());
  154. }
  155. void IMatrixCollector::save_imatrix(const char * fname) const {
  156. std::ofstream out(fname, std::ios::binary);
  157. int n_entries = m_stats.size();
  158. out.write((const char*)&n_entries, sizeof(n_entries));
  159. for (auto& p : m_stats) {
  160. int len = p.first.size();
  161. out.write((const char*)&len, sizeof(len));
  162. out.write(p.first.c_str(), len);
  163. out.write((const char*)&p.second.ncall, sizeof(p.second.ncall));
  164. int nval = p.second.values.size();
  165. out.write((const char*)&nval, sizeof(nval));
  166. if (nval > 0) out.write((const char*)p.second.values.data(), nval*sizeof(float));
  167. }
  168. if (m_params.verbosity > 0) {
  169. fprintf(stderr, "\n%s: stored collected data after %d chunks in %s\n",__func__,m_last_call,fname);
  170. }
  171. }
  172. static IMatrixCollector g_collector;
  173. static bool ik_collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
  174. return g_collector.collect_imatrix(t, ask, user_data);
  175. }
  176. struct results_log_softmax {
  177. double log_softmax;
  178. float logit;
  179. float prob;
  180. };
  181. static std::vector<float> softmax(const std::vector<float>& logits) {
  182. std::vector<float> probs(logits.size());
  183. float max_logit = logits[0];
  184. for (float v : logits) {
  185. max_logit = std::max(max_logit, v);
  186. }
  187. double sum_exp = 0.0;
  188. for (size_t i = 0; i < logits.size(); i++) {
  189. // Subtract the maximum logit value from the current logit value for numerical stability
  190. const float logit = logits[i] - max_logit;
  191. const float exp_logit = expf(logit);
  192. sum_exp += exp_logit;
  193. probs[i] = exp_logit;
  194. }
  195. for (size_t i = 0; i < probs.size(); i++) {
  196. probs[i] /= sum_exp;
  197. }
  198. return probs;
  199. }
  200. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  201. float max_logit = logits[0];
  202. for (int i = 1; i < n_vocab; ++i) {
  203. max_logit = std::max(max_logit, logits[i]);
  204. }
  205. double sum_exp = 0.0;
  206. for (int i = 0; i < n_vocab; ++i) {
  207. sum_exp += expf(logits[i] - max_logit);
  208. }
  209. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  210. }
  211. static void process_logits(
  212. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  213. double & nll, double & nll2, float * logit_history, float * prob_history
  214. ) {
  215. std::mutex mutex;
  216. int counter = 0;
  217. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  218. double local_nll = 0;
  219. double local_nll2 = 0;
  220. while (true) {
  221. std::unique_lock<std::mutex> lock(mutex);
  222. int i = counter++;
  223. if (i >= n_token) {
  224. nll += local_nll; nll2 += local_nll2;
  225. break;
  226. }
  227. lock.unlock();
  228. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  229. const double v = -results.log_softmax;
  230. local_nll += v;
  231. local_nll2 += v*v;
  232. logit_history[i] = results.logit;
  233. prob_history[i] = results.prob;
  234. }
  235. };
  236. for (auto & w : workers) {
  237. w = std::thread(compute);
  238. }
  239. compute();
  240. for (auto & w : workers) {
  241. w.join();
  242. }
  243. }
  244. static bool compute_imatrix(llama_context * ctx, const gpt_params & params, bool compute_ppl) {
  245. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  246. const int n_ctx = llama_n_ctx(ctx);
  247. auto tim1 = std::chrono::high_resolution_clock::now();
  248. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  249. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  250. auto tim2 = std::chrono::high_resolution_clock::now();
  251. fprintf(stderr, "%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  252. if (int(tokens.size()) < 2*n_ctx) {
  253. fprintf(stderr, "%s: you need at least %d tokens for a context of %d tokens\n",__func__,2*n_ctx,
  254. n_ctx);
  255. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  256. return false;
  257. }
  258. std::vector<float> logit_history;
  259. std::vector<float> prob_history;
  260. if (compute_ppl) {
  261. logit_history.resize(tokens.size());
  262. prob_history.resize(tokens.size());
  263. }
  264. const int n_chunk_max = tokens.size() / n_ctx;
  265. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  266. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  267. const int n_batch = params.n_batch;
  268. int count = 0;
  269. double nll = 0.0;
  270. double nll2 = 0.0;
  271. fprintf(stderr, "%s: computing over %d chunks with batch_size %d\n", __func__, n_chunk, n_batch);
  272. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  273. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  274. std::vector<float> logits;
  275. if (compute_ppl && num_batches > 1) {
  276. logits.reserve((size_t)n_ctx * n_vocab);
  277. }
  278. for (int i = 0; i < n_chunk; ++i) {
  279. const int start = i * n_ctx;
  280. const int end = start + n_ctx;
  281. std::vector<float> logits;
  282. const auto t_start = std::chrono::high_resolution_clock::now();
  283. // clear the KV cache
  284. llama_kv_cache_clear(ctx);
  285. for (int j = 0; j < num_batches; ++j) {
  286. const int batch_start = start + j * n_batch;
  287. const int batch_size = std::min(end - batch_start, n_batch);
  288. // save original token and restore it after eval
  289. const auto token_org = tokens[batch_start];
  290. // add BOS token for the first batch of each chunk
  291. if (add_bos && j == 0) {
  292. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  293. }
  294. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  295. fprintf(stderr, "%s : failed to eval\n", __func__);
  296. return false;
  297. }
  298. // restore the original token in case it was set to BOS
  299. tokens[batch_start] = token_org;
  300. if (compute_ppl && num_batches > 1) {
  301. const auto * batch_logits = llama_get_logits(ctx);
  302. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  303. }
  304. }
  305. const auto t_end = std::chrono::high_resolution_clock::now();
  306. if (i == 0) {
  307. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  308. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  309. int total_seconds = (int)(t_total * n_chunk);
  310. if (total_seconds >= 60*60) {
  311. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  312. total_seconds = total_seconds % (60*60);
  313. }
  314. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  315. }
  316. if (compute_ppl) {
  317. const int first = n_ctx/2;
  318. const auto all_logits = num_batches > 1 ? logits.data() : llama_get_logits(ctx);
  319. process_logits(n_vocab, all_logits + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
  320. workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
  321. count += n_ctx - first - 1;
  322. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  323. fflush(stdout);
  324. logits.clear();
  325. }
  326. }
  327. printf("\n");
  328. if (compute_ppl) {
  329. nll2 /= count;
  330. nll /= count;
  331. const double ppl = exp(nll);
  332. nll2 -= nll * nll;
  333. if (nll2 > 0) {
  334. nll2 = sqrt(nll2/(count-1));
  335. printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  336. } else {
  337. printf("Unexpected negative standard deviation of log(prob)\n");
  338. }
  339. }
  340. return true;
  341. }
  342. int main(int argc, char ** argv) {
  343. StatParams sparams;
  344. bool compute_ppl = true;
  345. std::vector<char*> args;
  346. args.push_back(argv[0]);
  347. int iarg = 1;
  348. for (; iarg < argc-1; ++iarg) {
  349. std::string arg{argv[iarg]};
  350. if (arg == "-o" || arg == "--output-file") {
  351. sparams.ofile = argv[++iarg];
  352. }
  353. else if (arg == "-ofreq" || arg == "--output-frequency") {
  354. sparams.n_output_frequency = std::stoi(argv[++iarg]);
  355. }
  356. else if (arg == "-ow" || arg == "--output-weight") {
  357. sparams.collect_output_weight = std::stoi(argv[++iarg]);
  358. }
  359. else if (arg == "--verbosity") {
  360. sparams.verbosity = std::stoi(argv[++iarg]);
  361. } else if (arg == "--no-ppl") {
  362. compute_ppl = false;
  363. } else if (arg == "--keep-imatrix") {
  364. sparams.keep_every = std::stoi(argv[++iarg]);
  365. } else {
  366. args.push_back(argv[iarg]);
  367. }
  368. }
  369. if (iarg < argc) {
  370. std::string arg{argv[iarg]};
  371. if (arg == "--no-ppl") {
  372. compute_ppl = false;
  373. } else {
  374. args.push_back(argv[iarg]);
  375. }
  376. }
  377. gpt_params params;
  378. params.n_batch = 512;
  379. if (!gpt_params_parse(args.size(), args.data(), params)) {
  380. return 1;
  381. }
  382. g_collector.set_parameters(std::move(sparams));
  383. params.logits_all = true;
  384. params.n_batch = std::min(params.n_batch, params.n_ctx);
  385. print_build_info();
  386. if (params.seed == LLAMA_DEFAULT_SEED) {
  387. params.seed = time(NULL);
  388. }
  389. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  390. std::mt19937 rng(params.seed);
  391. if (params.random_prompt) {
  392. params.prompt = gpt_random_prompt(rng);
  393. }
  394. llama_backend_init(params.numa);
  395. llama_model_params mparams = llama_model_params_from_gpt_params(params);
  396. llama_model * model = llama_load_model_from_file(params.model.c_str(), mparams);
  397. if (model == NULL) {
  398. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  399. return 1;
  400. }
  401. llama_context_params cparams = llama_context_params_from_gpt_params(params);
  402. // pass the callback to the backend scheduler
  403. // it will be executed for each node during the graph computation
  404. cparams.cb_eval = ik_collect_imatrix;
  405. cparams.cb_eval_user_data = NULL;
  406. llama_context * ctx = llama_new_context_with_model(model, cparams);
  407. if (ctx == NULL) {
  408. fprintf(stderr, "%s: error: unable to create context\n", __func__);
  409. return 1;
  410. }
  411. const int n_ctx_train = llama_n_ctx_train(model);
  412. if (params.n_ctx > n_ctx_train) {
  413. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  414. __func__, n_ctx_train, params.n_ctx);
  415. }
  416. // print system information
  417. {
  418. fprintf(stderr, "\n");
  419. fprintf(stderr, "%s\n", get_system_info(params).c_str());
  420. }
  421. bool OK = compute_imatrix(ctx, params, compute_ppl);
  422. if (!OK) {
  423. return 1;
  424. }
  425. g_collector.save_imatrix();
  426. llama_print_timings(ctx);
  427. llama_free(ctx);
  428. llama_free_model(model);
  429. llama_backend_free();
  430. return 0;
  431. }