perplexity.cpp 5.0 KB

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