perplexity.cpp 5.6 KB

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