1
0

perplexity.cpp 5.2 KB

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