imatrix.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. void collect_imatrix(const struct ggml_tensor * src0, const struct ggml_tensor * src1);
  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. };
  39. void IMatrixCollector::collect_imatrix(const struct ggml_tensor * src0, const struct ggml_tensor * src1) {
  40. if (src1->ne[1] < 16 || src1->type != GGML_TYPE_F32) return;
  41. if (!(strncmp(src0->name, "blk.", 4) == 0 || (m_params.collect_output_weight && strcmp(src0->name, "output.weight") == 0))) return;
  42. std::lock_guard<std::mutex> lock(m_mutex);
  43. auto& e = m_stats[src0->name];
  44. if (e.values.empty()) {
  45. e.values.resize(src1->ne[0], 0);
  46. }
  47. else if (e.values.size() != (size_t)src1->ne[0]) {
  48. fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", src0->name, (int)e.values.size(), (int)src1->ne[0]);
  49. exit(1); //GGML_ASSERT(false);
  50. }
  51. ++e.ncall;
  52. if (m_params.verbosity > 1) {
  53. printf("%s[%d]: %s, %d x %d, %d\n",__func__,m_last_call,src0->name,(int)src1->ne[0],(int)src1->ne[1],(int)src1->type);
  54. }
  55. for (int row = 0; row < (int)src1->ne[1]; ++row) {
  56. const float * x = (const float *)src1->data + row * src1->ne[0];
  57. for (int j = 0; j < (int)src1->ne[0]; ++j) {
  58. e.values[j] += x[j]*x[j];
  59. }
  60. }
  61. if (e.ncall > m_last_call) {
  62. m_last_call = e.ncall;
  63. if (m_last_call % m_params.n_output_frequency == 0) {
  64. save_imatrix();
  65. }
  66. }
  67. }
  68. void IMatrixCollector::save_imatrix() const {
  69. const char * fname = m_params.ofile.empty() ? "imatrix.dat" : m_params.ofile.c_str();
  70. std::ofstream out(fname, std::ios::binary);
  71. int n_entries = m_stats.size();
  72. out.write((const char*)&n_entries, sizeof(n_entries));
  73. for (auto& p : m_stats) {
  74. int len = p.first.size();
  75. out.write((const char*)&len, sizeof(len));
  76. out.write(p.first.c_str(), len);
  77. out.write((const char*)&p.second.ncall, sizeof(p.second.ncall));
  78. int nval = p.second.values.size();
  79. out.write((const char*)&nval, sizeof(nval));
  80. if (nval > 0) out.write((const char*)p.second.values.data(), nval*sizeof(float));
  81. }
  82. if (m_params.verbosity > 0) {
  83. fprintf(stderr, "\n%s: stored collected data after %d chunks in %s\n",__func__,m_last_call,fname);
  84. }
  85. }
  86. static IMatrixCollector g_collector;
  87. static void ik_collect_imatrix(const struct ggml_tensor * src0, const struct ggml_tensor * src1) {
  88. g_collector.collect_imatrix(src0, src1);
  89. }
  90. struct results_log_softmax {
  91. double log_softmax;
  92. float logit;
  93. float prob;
  94. };
  95. static std::vector<float> softmax(const std::vector<float>& logits) {
  96. std::vector<float> probs(logits.size());
  97. float max_logit = logits[0];
  98. for (float v : logits) {
  99. max_logit = std::max(max_logit, v);
  100. }
  101. double sum_exp = 0.0;
  102. for (size_t i = 0; i < logits.size(); i++) {
  103. // Subtract the maximum logit value from the current logit value for numerical stability
  104. const float logit = logits[i] - max_logit;
  105. const float exp_logit = expf(logit);
  106. sum_exp += exp_logit;
  107. probs[i] = exp_logit;
  108. }
  109. for (size_t i = 0; i < probs.size(); i++) {
  110. probs[i] /= sum_exp;
  111. }
  112. return probs;
  113. }
  114. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  115. float max_logit = logits[0];
  116. for (int i = 1; i < n_vocab; ++i) {
  117. max_logit = std::max(max_logit, logits[i]);
  118. }
  119. double sum_exp = 0.0;
  120. for (int i = 0; i < n_vocab; ++i) {
  121. sum_exp += expf(logits[i] - max_logit);
  122. }
  123. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  124. }
  125. static void process_logits(
  126. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  127. double & nll, double & nll2, float * logit_history, float * prob_history
  128. ) {
  129. std::mutex mutex;
  130. int counter = 0;
  131. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  132. double local_nll = 0;
  133. double local_nll2 = 0;
  134. while (true) {
  135. std::unique_lock<std::mutex> lock(mutex);
  136. int i = counter++;
  137. if (i >= n_token) {
  138. nll += local_nll; nll2 += local_nll2;
  139. break;
  140. }
  141. lock.unlock();
  142. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  143. const double v = -results.log_softmax;
  144. local_nll += v;
  145. local_nll2 += v*v;
  146. logit_history[i] = results.logit;
  147. prob_history[i] = results.prob;
  148. }
  149. };
  150. for (auto & w : workers) {
  151. w = std::thread(compute);
  152. }
  153. compute();
  154. for (auto & w : workers) {
  155. w.join();
  156. }
  157. }
  158. static bool compute_imatrix(llama_context * ctx, const gpt_params & params) {
  159. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  160. const int n_ctx = llama_n_ctx(ctx);
  161. auto tim1 = std::chrono::high_resolution_clock::now();
  162. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  163. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  164. auto tim2 = std::chrono::high_resolution_clock::now();
  165. fprintf(stderr, "%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  166. if (int(tokens.size()) < 2*n_ctx) {
  167. fprintf(stderr, "%s: you need at least %d tokens for a context of %d tokens\n",__func__,2*n_ctx,
  168. n_ctx);
  169. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  170. return false;
  171. }
  172. std::vector<float> logit_history;
  173. logit_history.resize(tokens.size());
  174. std::vector<float> prob_history;
  175. prob_history.resize(tokens.size());
  176. const int n_chunk_max = tokens.size() / n_ctx;
  177. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  178. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  179. const int n_batch = params.n_batch;
  180. int count = 0;
  181. double nll = 0.0;
  182. double nll2 = 0.0;
  183. fprintf(stderr, "%s: computing over %d chunks with batch_size %d\n", __func__, n_chunk, n_batch);
  184. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  185. for (int i = 0; i < n_chunk; ++i) {
  186. const int start = i * n_ctx;
  187. const int end = start + n_ctx;
  188. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  189. std::vector<float> logits;
  190. const auto t_start = std::chrono::high_resolution_clock::now();
  191. // clear the KV cache
  192. llama_kv_cache_clear(ctx);
  193. for (int j = 0; j < num_batches; ++j) {
  194. const int batch_start = start + j * n_batch;
  195. const int batch_size = std::min(end - batch_start, n_batch);
  196. // save original token and restore it after eval
  197. const auto token_org = tokens[batch_start];
  198. // add BOS token for the first batch of each chunk
  199. if (add_bos && j == 0) {
  200. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  201. }
  202. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  203. fprintf(stderr, "%s : failed to eval\n", __func__);
  204. return false;
  205. }
  206. // restore the original token in case it was set to BOS
  207. tokens[batch_start] = token_org;
  208. const auto * batch_logits = llama_get_logits(ctx);
  209. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  210. }
  211. const auto t_end = std::chrono::high_resolution_clock::now();
  212. if (i == 0) {
  213. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  214. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  215. int total_seconds = (int)(t_total * n_chunk);
  216. if (total_seconds >= 60*60) {
  217. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  218. total_seconds = total_seconds % (60*60);
  219. }
  220. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  221. }
  222. const int first = n_ctx/2;
  223. process_logits(n_vocab, logits.data() + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
  224. workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
  225. count += n_ctx - first - 1;
  226. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  227. fflush(stdout);
  228. }
  229. printf("\n");
  230. nll2 /= count;
  231. nll /= count;
  232. const double ppl = exp(nll);
  233. nll2 -= nll * nll;
  234. if (nll2 > 0) {
  235. nll2 = sqrt(nll2/(count-1));
  236. printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  237. } else {
  238. printf("Unexpected negative standard deviation of log(prob)\n");
  239. }
  240. return true;
  241. }
  242. int main(int argc, char ** argv) {
  243. StatParams sparams;
  244. std::vector<char*> args;
  245. args.push_back(argv[0]);
  246. int iarg = 1;
  247. for (; iarg < argc-1; ++iarg) {
  248. std::string arg{argv[iarg]};
  249. if (arg == "-o" || arg == "--output-file") {
  250. sparams.ofile = argv[++iarg];
  251. }
  252. else if (arg == "-ofreq" || arg == "--output-frequency") {
  253. sparams.n_output_frequency = std::stoi(argv[++iarg]);
  254. }
  255. else if (arg == "-ow" || arg == "--output-weight") {
  256. sparams.collect_output_weight = std::stoi(argv[++iarg]);
  257. }
  258. else if (arg == "--verbosity") {
  259. sparams.verbosity = std::stoi(argv[++iarg]);
  260. } else {
  261. args.push_back(argv[iarg]);
  262. }
  263. }
  264. if (iarg < argc) {
  265. args.push_back(argv[iarg]);
  266. }
  267. gpt_params params;
  268. params.n_batch = 512;
  269. if (!gpt_params_parse(args.size(), args.data(), params)) {
  270. return 1;
  271. }
  272. g_collector.set_parameters(std::move(sparams));
  273. ggml_set_imatrix_collection(ik_collect_imatrix);
  274. params.logits_all = true;
  275. params.n_batch = std::min(params.n_batch, params.n_ctx);
  276. print_build_info();
  277. if (params.seed == LLAMA_DEFAULT_SEED) {
  278. params.seed = time(NULL);
  279. }
  280. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  281. std::mt19937 rng(params.seed);
  282. if (params.random_prompt) {
  283. params.prompt = gpt_random_prompt(rng);
  284. }
  285. llama_backend_init(params.numa);
  286. llama_model * model;
  287. llama_context * ctx;
  288. // load the model and apply lora adapter, if any
  289. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  290. if (model == NULL) {
  291. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  292. return 1;
  293. }
  294. const int n_ctx_train = llama_n_ctx_train(model);
  295. if (params.n_ctx > n_ctx_train) {
  296. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  297. __func__, n_ctx_train, params.n_ctx);
  298. }
  299. // print system information
  300. {
  301. fprintf(stderr, "\n");
  302. fprintf(stderr, "%s\n", get_system_info(params).c_str());
  303. }
  304. bool OK = compute_imatrix(ctx, params);
  305. if (!OK) {
  306. return 1;
  307. }
  308. g_collector.save_imatrix();
  309. llama_print_timings(ctx);
  310. llama_free(ctx);
  311. llama_free_model(model);
  312. llama_backend_free();
  313. return 0;
  314. }