imatrix.cpp 16 KB

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