perplexity.cpp 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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 %.2f hours\n", seconds, (seconds * seq_count) / (60.0*60.0));
  50. }
  51. // We get the logits for all the tokens in the context window (params.n_ctx)
  52. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  53. // calculate the perplexity over the last half the window (so the model always has
  54. // some context to predict the token).
  55. //
  56. // We rely on the fact that attention in the forward pass only looks at previous
  57. // tokens here, so the logits returned for each token are an accurate representation
  58. // of what the model would have predicted at that point.
  59. //
  60. // Example, we have a context window of 512, we will compute perplexity for each of the
  61. // last 256 tokens. Then, we split the input up into context window size chunks to
  62. // process the entire prompt.
  63. for (int j = std::min(512, params.n_ctx / 2); j < params.n_ctx - 1; ++j) {
  64. // Calculate probability of next token, given the previous ones.
  65. std::vector<float> tok_logits(
  66. logits.begin() + j * n_vocab,
  67. logits.begin() + (j + 1) * n_vocab);
  68. float prob = softmax(tok_logits)[tokens[start + j + 1]];
  69. nll += -std::log(prob);
  70. ++count;
  71. }
  72. // perplexity is e^(average negative log-likelihood)
  73. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  74. fflush(stdout);
  75. }
  76. printf("\n");
  77. }
  78. int main(int argc, char ** argv) {
  79. gpt_params params;
  80. params.model = "models/llama-7B/ggml-model.bin";
  81. params.n_batch = 512;
  82. if (gpt_params_parse(argc, argv, params) == false) {
  83. return 1;
  84. }
  85. params.perplexity = true;
  86. params.n_batch = std::min(params.n_batch, params.n_ctx);
  87. if (params.n_ctx > 2048) {
  88. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  89. "expect poor results\n", __func__, params.n_ctx);
  90. }
  91. if (params.seed <= 0) {
  92. params.seed = time(NULL);
  93. }
  94. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  95. std::mt19937 rng(params.seed);
  96. if (params.random_prompt) {
  97. params.prompt = gpt_random_prompt(rng);
  98. }
  99. llama_context * ctx;
  100. // load the model
  101. {
  102. auto lparams = llama_context_default_params();
  103. lparams.n_ctx = params.n_ctx;
  104. lparams.n_parts = params.n_parts;
  105. lparams.seed = params.seed;
  106. lparams.f16_kv = params.memory_f16;
  107. lparams.logits_all = params.perplexity;
  108. lparams.use_mmap = params.use_mmap;
  109. lparams.use_mlock = params.use_mlock;
  110. lparams.embedding = params.embedding;
  111. ctx = llama_init_from_file(params.model.c_str(), lparams);
  112. if (ctx == NULL) {
  113. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  114. return 1;
  115. }
  116. }
  117. if (!params.lora_adapter.empty()) {
  118. int err = llama_apply_lora_from_file(ctx,
  119. params.lora_adapter.c_str(),
  120. params.lora_base.empty() ? NULL : params.lora_base.c_str(),
  121. params.n_threads);
  122. if (err != 0) {
  123. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  124. return 1;
  125. }
  126. }
  127. // print system information
  128. {
  129. fprintf(stderr, "\n");
  130. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  131. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  132. }
  133. perplexity(ctx, params);
  134. llama_print_timings(ctx);
  135. llama_free(ctx);
  136. return 0;
  137. }