perplexity.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. int count = 0;
  31. const int n_chunk = tokens.size() / params.n_ctx;
  32. const int n_vocab = llama_n_vocab(ctx);
  33. const int n_batch = params.n_batch;
  34. double nll = 0.0;
  35. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  36. for (int i = 0; i < n_chunk; ++i) {
  37. const int start = i * params.n_ctx;
  38. const int end = start + params.n_ctx;
  39. const int num_batches = (params.n_ctx + n_batch - 1) / n_batch;
  40. std::vector<float> logits;
  41. const auto t_start = std::chrono::high_resolution_clock::now();
  42. for (int j = 0; j < num_batches; ++j) {
  43. const int batch_start = start + j * n_batch;
  44. const int batch_size = std::min(end - batch_start, n_batch);
  45. // save original token and restore it after eval
  46. const auto token_org = tokens[batch_start];
  47. // add BOS token for the first batch of each chunk
  48. if (j == 0) {
  49. tokens[batch_start] = llama_token_bos();
  50. }
  51. if (llama_eval(ctx, tokens.data() + batch_start, batch_size, j * n_batch, params.n_threads)) {
  52. fprintf(stderr, "%s : failed to eval\n", __func__);
  53. return;
  54. }
  55. // restore the original token in case it was set to BOS
  56. tokens[batch_start] = token_org;
  57. const auto batch_logits = llama_get_logits(ctx);
  58. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  59. }
  60. const auto t_end = std::chrono::high_resolution_clock::now();
  61. if (i == 0) {
  62. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  63. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  64. int total_seconds = (int)(t_total * n_chunk);
  65. if (total_seconds >= 60*60) {
  66. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  67. total_seconds = total_seconds % (60*60);
  68. }
  69. fprintf(stderr, "%d minutes\n", total_seconds / 60);
  70. }
  71. // We get the logits for all the tokens in the context window (params.n_ctx)
  72. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  73. // calculate the perplexity over the last half of the window (so the model always has
  74. // some context to predict the token).
  75. //
  76. // We rely on the fact that attention in the forward pass only looks at previous
  77. // tokens here, so the logits returned for each token are an accurate representation
  78. // of what the model would have predicted at that point.
  79. //
  80. // Example, we have a context window of 512, we will compute perplexity for each of the
  81. // last 256 tokens. Then, we split the input up into context window size chunks to
  82. // process the entire prompt.
  83. for (int j = std::min(512, params.n_ctx / 2); j < params.n_ctx - 1; ++j) {
  84. // Calculate probability of next token, given the previous ones.
  85. const std::vector<float> tok_logits(
  86. logits.begin() + (j + 0) * n_vocab,
  87. logits.begin() + (j + 1) * n_vocab);
  88. const float prob = softmax(tok_logits)[tokens[start + j + 1]];
  89. nll += -std::log(prob);
  90. ++count;
  91. }
  92. // perplexity is e^(average negative log-likelihood)
  93. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  94. fflush(stdout);
  95. }
  96. printf("\n");
  97. }
  98. int main(int argc, char ** argv) {
  99. gpt_params params;
  100. params.n_batch = 512;
  101. if (gpt_params_parse(argc, argv, params) == false) {
  102. return 1;
  103. }
  104. params.perplexity = true;
  105. params.n_batch = std::min(params.n_batch, params.n_ctx);
  106. if (params.n_ctx > 2048) {
  107. fprintf(stderr, "%s: warning: model might not support context sizes greater than 2048 tokens (%d specified);"
  108. "expect poor results\n", __func__, params.n_ctx);
  109. }
  110. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  111. if (params.seed == LLAMA_DEFAULT_SEED) {
  112. params.seed = time(NULL);
  113. }
  114. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  115. std::mt19937 rng(params.seed);
  116. if (params.random_prompt) {
  117. params.prompt = gpt_random_prompt(rng);
  118. }
  119. llama_init_backend(params.numa);
  120. llama_model * model;
  121. llama_context * ctx;
  122. // load the model and apply lora adapter, if any
  123. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  124. if (model == NULL) {
  125. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  126. return 1;
  127. }
  128. // print system information
  129. {
  130. fprintf(stderr, "\n");
  131. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  132. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  133. }
  134. perplexity(ctx, params);
  135. llama_print_timings(ctx);
  136. llama_free(ctx);
  137. llama_free_model(model);
  138. return 0;
  139. }