1
0

perplexity.cpp 6.3 KB

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