perplexity.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. #include <cmath>
  5. #include <ctime>
  6. #if defined(_MSC_VER)
  7. #pragma warning(disable: 4244 4267) // possible loss of data
  8. #endif
  9. std::vector<float> softmax(const std::vector<float>& logits) {
  10. std::vector<float> probs(logits.size());
  11. float max_logit = logits[0];
  12. for (float v : logits) max_logit = std::max(max_logit, v);
  13. double sum_exp = 0.0;
  14. for (size_t i = 0; i < logits.size(); i++) {
  15. // Subtract the maximum logit value from the current logit value for numerical stability
  16. const float logit = logits[i] - max_logit;
  17. const float exp_logit = expf(logit);
  18. sum_exp += exp_logit;
  19. probs[i] = exp_logit;
  20. }
  21. for (size_t i = 0; i < probs.size(); i++) probs[i] /= sum_exp;
  22. return probs;
  23. }
  24. void perplexity(llama_context * ctx, const gpt_params & params) {
  25. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  26. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  27. // Output: `perplexity: 13.5106 [114/114]`
  28. // BOS tokens will be added for each chunk before eval
  29. auto tokens = ::llama_tokenize(ctx, params.prompt, true);
  30. const int n_chunk_max = tokens.size() / params.n_ctx;
  31. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  32. const int n_vocab = llama_n_vocab(ctx);
  33. const int n_batch = params.n_batch;
  34. int count = 0;
  35. double nll = 0.0;
  36. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  37. for (int i = 0; i < n_chunk; ++i) {
  38. const int start = i * params.n_ctx;
  39. const int end = start + params.n_ctx;
  40. const int num_batches = (params.n_ctx + n_batch - 1) / n_batch;
  41. std::vector<float> logits;
  42. const auto t_start = std::chrono::high_resolution_clock::now();
  43. for (int j = 0; j < num_batches; ++j) {
  44. const int batch_start = start + j * n_batch;
  45. const int batch_size = std::min(end - batch_start, n_batch);
  46. // save original token and restore it after eval
  47. const auto token_org = tokens[batch_start];
  48. // add BOS token for the first batch of each chunk
  49. if (j == 0) {
  50. tokens[batch_start] = llama_token_bos();
  51. }
  52. if (llama_eval(ctx, tokens.data() + batch_start, batch_size, j * n_batch, params.n_threads)) {
  53. fprintf(stderr, "%s : failed to eval\n", __func__);
  54. return;
  55. }
  56. // restore the original token in case it was set to BOS
  57. tokens[batch_start] = token_org;
  58. const auto batch_logits = llama_get_logits(ctx);
  59. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  60. }
  61. const auto t_end = std::chrono::high_resolution_clock::now();
  62. if (i == 0) {
  63. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  64. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  65. int total_seconds = (int)(t_total * n_chunk);
  66. if (total_seconds >= 60*60) {
  67. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  68. total_seconds = total_seconds % (60*60);
  69. }
  70. fprintf(stderr, "%d minutes\n", total_seconds / 60);
  71. }
  72. // We get the logits for all the tokens in the context window (params.n_ctx)
  73. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  74. // calculate the perplexity over the last half of the window (so the model always has
  75. // some context to predict the token).
  76. //
  77. // We rely on the fact that attention in the forward pass only looks at previous
  78. // tokens here, so the logits returned for each token are an accurate representation
  79. // of what the model would have predicted at that point.
  80. //
  81. // Example, we have a context window of 512, we will compute perplexity for each of the
  82. // last 256 tokens. Then, we split the input up into context window size chunks to
  83. // process the entire prompt.
  84. for (int j = std::min(512, params.n_ctx / 2); j < params.n_ctx - 1; ++j) {
  85. // Calculate probability of next token, given the previous ones.
  86. const std::vector<float> tok_logits(
  87. logits.begin() + (j + 0) * n_vocab,
  88. logits.begin() + (j + 1) * n_vocab);
  89. const float prob = softmax(tok_logits)[tokens[start + j + 1]];
  90. nll += -std::log(prob);
  91. ++count;
  92. }
  93. // perplexity is e^(average negative log-likelihood)
  94. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  95. fflush(stdout);
  96. }
  97. printf("\n");
  98. }
  99. int main(int argc, char ** argv) {
  100. gpt_params params;
  101. params.n_batch = 512;
  102. if (gpt_params_parse(argc, argv, params) == false) {
  103. return 1;
  104. }
  105. params.perplexity = true;
  106. params.n_batch = std::min(params.n_batch, params.n_ctx);
  107. if (params.n_ctx > 2048) {
  108. fprintf(stderr, "%s: warning: model might not support context sizes greater than 2048 tokens (%d specified);"
  109. "expect poor results\n", __func__, params.n_ctx);
  110. }
  111. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  112. if (params.seed == LLAMA_DEFAULT_SEED) {
  113. params.seed = time(NULL);
  114. }
  115. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  116. std::mt19937 rng(params.seed);
  117. if (params.random_prompt) {
  118. params.prompt = gpt_random_prompt(rng);
  119. }
  120. llama_backend_init(params.numa);
  121. llama_model * model;
  122. llama_context * ctx;
  123. // load the model and apply lora adapter, if any
  124. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  125. if (model == NULL) {
  126. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  127. return 1;
  128. }
  129. // print system information
  130. {
  131. fprintf(stderr, "\n");
  132. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  133. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  134. }
  135. perplexity(ctx, params);
  136. llama_print_timings(ctx);
  137. llama_free(ctx);
  138. llama_free_model(model);
  139. llama_backend_free();
  140. return 0;
  141. }