1
0

perplexity.cpp 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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. double nll = 0.0;
  27. fprintf(stderr, "%s : calculating perplexity over %d chunks\n", __func__, seq_count);
  28. for (int i = 0; i < seq_count; ++i) {
  29. int start = i * params.n_ctx;
  30. int end = start + params.n_ctx - 1; // TODO: this is not optimal, e.g. it makes the batch 511 instead of 512
  31. // it is better to always be power of 2 for better performance
  32. std::vector<llama_token> embd(tokens.begin() + start, tokens.begin() + end);
  33. auto start_t = std::chrono::high_resolution_clock::now();
  34. if (llama_eval(ctx, embd.data(), embd.size(), 0, params.n_threads)) {
  35. fprintf(stderr, "%s : failed to eval\n", __func__);
  36. return;
  37. }
  38. auto end_t = std::chrono::high_resolution_clock::now();
  39. if (i == 0) {
  40. const float seconds = std::chrono::duration<float>(end_t - start_t).count();
  41. printf("%.2f seconds per pass - ETA %.2f hours\n", seconds, (seconds * seq_count) / (60.0*60.0));
  42. }
  43. // We get the logits for all the tokens in the context window (params.n_ctx)
  44. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  45. // calculate the perplexity over the last half the window (so the model always has
  46. // some context to predict the token).
  47. //
  48. // We rely on the fact that attention in the forward pass only looks at previous
  49. // tokens here, so the logits returned for each token are an accurate representation
  50. // of what the model would have predicted at that point.
  51. //
  52. // Example, we have a context window of 512, we will compute perplexity for each of the
  53. // last 256 tokens. Then, we split the input up into context window size chunks to
  54. // process the entire prompt.
  55. auto logits = llama_get_logits(ctx);
  56. for (int j = params.n_ctx / 2; j < params.n_ctx - 1; ++j) {
  57. // Calculate probability of next token, given the previous ones.
  58. int n_vocab = llama_n_vocab(ctx);
  59. std::vector<float> tok_logits(
  60. logits + j * n_vocab,
  61. logits + (j + 1) * n_vocab);
  62. const float prob = softmax(tok_logits)[tokens[start + j + 1]];
  63. nll += -std::log(prob);
  64. ++count;
  65. }
  66. // perplexity is e^(average negative log-likelihood)
  67. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  68. fflush(stdout);
  69. }
  70. printf("\n");
  71. }
  72. int main(int argc, char ** argv) {
  73. gpt_params params;
  74. params.model = "models/llama-7B/ggml-model.bin";
  75. if (gpt_params_parse(argc, argv, params) == false) {
  76. return 1;
  77. }
  78. params.perplexity = true;
  79. if (params.n_ctx > 2048) {
  80. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  81. "expect poor results\n", __func__, params.n_ctx);
  82. }
  83. if (params.seed <= 0) {
  84. params.seed = time(NULL);
  85. }
  86. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  87. std::mt19937 rng(params.seed);
  88. if (params.random_prompt) {
  89. params.prompt = gpt_random_prompt(rng);
  90. }
  91. llama_context * ctx;
  92. // load the model
  93. {
  94. auto lparams = llama_context_default_params();
  95. lparams.n_ctx = params.n_ctx;
  96. lparams.n_parts = params.n_parts;
  97. lparams.seed = params.seed;
  98. lparams.f16_kv = params.memory_f16;
  99. lparams.logits_all = params.perplexity;
  100. lparams.use_mmap = params.use_mmap;
  101. lparams.use_mlock = params.use_mlock;
  102. lparams.embedding = params.embedding;
  103. ctx = llama_init_from_file(params.model.c_str(), lparams);
  104. if (ctx == NULL) {
  105. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  106. return 1;
  107. }
  108. }
  109. // print system information
  110. {
  111. fprintf(stderr, "\n");
  112. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  113. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  114. }
  115. perplexity(ctx, params);
  116. llama_print_timings(ctx);
  117. llama_free(ctx);
  118. return 0;
  119. }