1
0

perplexity.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. #include <cmath>
  5. #include <ctime>
  6. #include <sstream>
  7. #if defined(_MSC_VER)
  8. #pragma warning(disable: 4244 4267) // possible loss of data
  9. #endif
  10. std::vector<float> softmax(const std::vector<float>& logits) {
  11. std::vector<float> 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. const float logit = logits[i] - max_logit;
  18. const float exp_logit = expf(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 `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  28. // Output: `perplexity: 13.5106 [114/114]`
  29. // BOS tokens will be added for each chunk before eval
  30. auto tokens = ::llama_tokenize(ctx, params.prompt, true);
  31. const int n_chunk_max = tokens.size() / params.n_ctx;
  32. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  33. const int n_vocab = llama_n_vocab(ctx);
  34. const int n_batch = params.n_batch;
  35. int count = 0;
  36. double nll = 0.0;
  37. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  38. for (int i = 0; i < n_chunk; ++i) {
  39. const int start = i * params.n_ctx;
  40. const int end = start + params.n_ctx;
  41. const int num_batches = (params.n_ctx + n_batch - 1) / n_batch;
  42. std::vector<float> logits;
  43. const auto t_start = std::chrono::high_resolution_clock::now();
  44. for (int j = 0; j < num_batches; ++j) {
  45. const int batch_start = start + j * n_batch;
  46. const int batch_size = std::min(end - batch_start, n_batch);
  47. // save original token and restore it after eval
  48. const auto token_org = tokens[batch_start];
  49. // add BOS token for the first batch of each chunk
  50. if (j == 0) {
  51. tokens[batch_start] = llama_token_bos();
  52. }
  53. if (llama_eval(ctx, tokens.data() + batch_start, batch_size, j * n_batch, params.n_threads)) {
  54. fprintf(stderr, "%s : failed to eval\n", __func__);
  55. return;
  56. }
  57. // restore the original token in case it was set to BOS
  58. tokens[batch_start] = token_org;
  59. const auto batch_logits = llama_get_logits(ctx);
  60. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  61. }
  62. const auto t_end = std::chrono::high_resolution_clock::now();
  63. if (i == 0) {
  64. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  65. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  66. int total_seconds = (int)(t_total * n_chunk);
  67. if (total_seconds >= 60*60) {
  68. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  69. total_seconds = total_seconds % (60*60);
  70. }
  71. fprintf(stderr, "%d minutes\n", total_seconds / 60);
  72. }
  73. // We get the logits for all the tokens in the context window (params.n_ctx)
  74. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  75. // calculate the perplexity over the last half of the window (so the model always has
  76. // some context to predict the token).
  77. //
  78. // We rely on the fact that attention in the forward pass only looks at previous
  79. // tokens here, so the logits returned for each token are an accurate representation
  80. // of what the model would have predicted at that point.
  81. //
  82. // Example, we have a context window of 512, we will compute perplexity for each of the
  83. // last 256 tokens. Then, we split the input up into context window size chunks to
  84. // process the entire prompt.
  85. for (int j = std::min(512, params.n_ctx / 2); j < params.n_ctx - 1; ++j) {
  86. // Calculate probability of next token, given the previous ones.
  87. const std::vector<float> tok_logits(
  88. logits.begin() + (j + 0) * n_vocab,
  89. logits.begin() + (j + 1) * n_vocab);
  90. const float prob = softmax(tok_logits)[tokens[start + j + 1]];
  91. nll += -std::log(prob);
  92. ++count;
  93. }
  94. // perplexity is e^(average negative log-likelihood)
  95. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  96. fflush(stdout);
  97. }
  98. printf("\n");
  99. }
  100. void perplexity_lines(llama_context * ctx, const gpt_params & params) {
  101. // Calculates perplexity over each line of the prompt
  102. std::vector<std::string> prompt_lines;
  103. std::istringstream strstream(params.prompt);
  104. std::string line;
  105. while (std::getline(strstream,line,'\n')) {
  106. prompt_lines.push_back(line);
  107. }
  108. const int n_vocab = llama_n_vocab(ctx);
  109. int counttotal = 0;
  110. size_t n_lines = prompt_lines.size();
  111. double nll = 0.0;
  112. fprintf(stderr, "%s: calculating perplexity over %lu lines\n", __func__, n_lines);
  113. printf("\nLine\tPPL line\tPPL cumulative\n");
  114. for (size_t i = 0; i < n_lines; ++i) {
  115. // Tokenize and insert BOS at start
  116. std::vector<int> batch_embd = ::llama_tokenize(ctx, prompt_lines[i], true);
  117. size_t batch_size = batch_embd.size();
  118. // Stop if line is too long
  119. if( batch_size > (size_t)params.n_ctx ) {
  120. fprintf(stderr, "%s : tokens in line %lu > n_ctxl\n", __func__, i);
  121. return;
  122. }
  123. if (llama_eval(ctx, batch_embd.data(), batch_size, 0, params.n_threads)) {
  124. fprintf(stderr, "%s : failed to eval\n", __func__);
  125. return;
  126. }
  127. const auto batch_logits = llama_get_logits(ctx);
  128. std::vector<float> logits;
  129. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  130. double nllline = 0.0;
  131. int countline = 0;
  132. // Perplexity over second half of the line
  133. for (size_t j = batch_size/2; j < batch_size - 1; ++j) {
  134. // Calculate probability of next token, given the previous ones.
  135. const std::vector<float> tok_logits(
  136. logits.begin() + (j + 0) * n_vocab,
  137. logits.begin() + (j + 1) * n_vocab);
  138. const float prob = softmax(tok_logits)[batch_embd[ j + 1]];
  139. nllline += -std::log(prob);
  140. ++countline;
  141. }
  142. nll += nllline;
  143. counttotal += countline;
  144. // perplexity is e^(average negative log-likelihood)
  145. printf("%lu\t%.8lf\t%.8lf\n", i + 1, std::exp(nllline/countline), std::exp(nll / counttotal) );
  146. fflush(stdout);
  147. }
  148. printf("\n");
  149. }
  150. int main(int argc, char ** argv) {
  151. gpt_params params;
  152. params.n_batch = 512;
  153. if (gpt_params_parse(argc, argv, params) == false) {
  154. return 1;
  155. }
  156. params.perplexity = true;
  157. params.n_batch = std::min(params.n_batch, params.n_ctx);
  158. if (params.n_ctx > 2048) {
  159. fprintf(stderr, "%s: warning: model might not support context sizes greater than 2048 tokens (%d specified);"
  160. "expect poor results\n", __func__, params.n_ctx);
  161. }
  162. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  163. if (params.seed == LLAMA_DEFAULT_SEED) {
  164. params.seed = time(NULL);
  165. }
  166. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  167. std::mt19937 rng(params.seed);
  168. if (params.random_prompt) {
  169. params.prompt = gpt_random_prompt(rng);
  170. }
  171. llama_backend_init(params.numa);
  172. llama_model * model;
  173. llama_context * ctx;
  174. // load the model and apply lora adapter, if any
  175. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  176. if (model == NULL) {
  177. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  178. return 1;
  179. }
  180. // print system information
  181. {
  182. fprintf(stderr, "\n");
  183. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  184. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  185. }
  186. if (params.perplexity_lines) {
  187. perplexity_lines(ctx, params);
  188. } else {
  189. perplexity(ctx, params);
  190. }
  191. llama_print_timings(ctx);
  192. llama_free(ctx);
  193. llama_free_model(model);
  194. llama_backend_free();
  195. return 0;
  196. }