perplexity.cpp 6.1 KB

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