perplexity.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 hellaswag_score(llama_context * ctx, const gpt_params & params) {
  101. // Calculates hellaswag score (acc_norm) from prompt
  102. //
  103. // Data extracted from the HellaSwag validation dataset (MIT license) https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl
  104. // All used data fields are preprocessed as in https://github.com/EleutherAI/lm-evaluation-harness/blob/df3da98c5405deafd519c2ddca52bb7c3fe36bef/lm_eval/tasks/hellaswag.py#L62-L68
  105. //
  106. // All 10042 tasks should be extracted to keep the results standardized like other implementations.
  107. //
  108. // Datafile layout:
  109. // ['??'] denotes json fields
  110. // 6 lines per task:
  111. // ['activity_label'] + ": " +['ctx'] - The first part of the query, the context
  112. // ['label'] - The index the best common sense ending aka gold ending
  113. // ['endings'][0] - Endings added to the first part of the query
  114. // ['endings'][1]
  115. // ['endings'][2]
  116. // ['endings'][3]
  117. std::vector<std::string> prompt_lines;
  118. std::istringstream strstream(params.prompt);
  119. std::string line;
  120. while (std::getline(strstream,line,'\n')) {
  121. prompt_lines.push_back(line);
  122. }
  123. if( prompt_lines.size() % 6 != 0) {
  124. fprintf(stderr, "%s : number of lines in prompt not a multiple of 6.\n", __func__);
  125. return;
  126. }
  127. size_t hs_task_count = prompt_lines.size()/6;
  128. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, hs_task_count);
  129. // This is needed as usual for LLaMA models
  130. bool prepend_bos = true;
  131. // Number of tasks to use when computing the score
  132. if ( params.hellaswag_tasks < hs_task_count ) {
  133. hs_task_count = params.hellaswag_tasks;
  134. }
  135. // The tasks should be randomized so the score stabilizes quickly.
  136. bool randomize_tasks = true;
  137. // The random seed should not impact the final result if the computation is done over enough tasks, so kept hardcoded for now
  138. std::mt19937 rng(1);
  139. // Dataholder for hellaswag tasks
  140. struct hs_data_t {
  141. std::string context;
  142. size_t gold_ending_idx;
  143. std::string ending[4];
  144. size_t ending_logprob_count[4];
  145. double ending_logprob[4];
  146. };
  147. fprintf(stderr, "%s : selecting %zu %s tasks.\n", __func__, hs_task_count, (randomize_tasks?"randomized":"the first") );
  148. // Select and read data from prompt lines
  149. hs_data_t *hs_data = new hs_data_t[hs_task_count];
  150. for (size_t i=0; i < hs_task_count; i++) {
  151. size_t idx = i;
  152. // Select a random example of those left in the prompt
  153. if (randomize_tasks) {
  154. std::uniform_int_distribution<size_t> dist(0, prompt_lines.size()/6-1 ) ;
  155. idx = dist(rng);
  156. }
  157. hs_data[i].context = prompt_lines[idx*6];
  158. hs_data[i].gold_ending_idx = std::stoi( prompt_lines[idx*6+1] );
  159. for (size_t j=0; j < 4; j++) {
  160. hs_data[i].ending[j] = " " + prompt_lines[idx*6+2+j];
  161. }
  162. // Delete the selected random example from the prompt
  163. if (randomize_tasks) {
  164. prompt_lines.erase( std::next(prompt_lines.begin(),idx*6) , std::next(prompt_lines.begin(),idx*6+6) );
  165. }
  166. }
  167. fprintf(stderr, "%s : calculating hellaswag score over selected tasks.\n", __func__);
  168. printf("\ntask\tacc_norm\n");
  169. double acc = 0.0f;
  170. const int n_vocab = llama_n_vocab(ctx);
  171. for (size_t task_idx = 0; task_idx < hs_task_count; task_idx++) {
  172. // Tokenize the context to count tokens
  173. std::vector<int> context_embd = ::llama_tokenize(ctx, hs_data[task_idx].context, prepend_bos);
  174. size_t context_size = context_embd.size();
  175. for (size_t ending_idx=0;ending_idx<4;ending_idx++) {
  176. // Tokenize the query
  177. std::vector<int> query_embd = ::llama_tokenize(ctx, hs_data[task_idx].context + hs_data[task_idx].ending[ending_idx], prepend_bos);
  178. size_t query_size = query_embd.size();
  179. // Stop if query wont fit the ctx window
  180. if (query_size > (size_t)params.n_ctx) {
  181. fprintf(stderr, "%s : number of tokens in query %zu > n_ctxl\n", __func__, query_size);
  182. return;
  183. }
  184. // Speedup small evaluations by evaluating atleast 32 tokens
  185. if (query_size < 32) {
  186. query_embd.resize(32);
  187. }
  188. // Evaluate the query
  189. if (llama_eval(ctx, query_embd.data(), query_embd.size(), 0, params.n_threads)) {
  190. fprintf(stderr, "%s : failed to eval\n", __func__);
  191. return;
  192. }
  193. const auto query_logits = llama_get_logits(ctx);
  194. std::vector<float> logits;
  195. logits.insert(logits.end(), query_logits, query_logits + query_size * n_vocab);
  196. hs_data[task_idx].ending_logprob_count[ending_idx] = 0;
  197. hs_data[task_idx].ending_logprob[ending_idx] = 0.0f;
  198. // Calculate the logprobs over the ending
  199. for (size_t j = context_size-1; j < query_size - 1; j++) {
  200. // Calculate probability of next token, given the previous ones.
  201. const std::vector<float> tok_logits(
  202. logits.begin() + (j + 0) * n_vocab,
  203. logits.begin() + (j + 1) * n_vocab);
  204. const float prob = softmax(tok_logits)[query_embd[ j + 1]];
  205. hs_data[task_idx].ending_logprob[ending_idx] += std::log(prob);
  206. hs_data[task_idx].ending_logprob_count[ending_idx]++;
  207. }
  208. // Calculate the mean token logprob for acc_norm
  209. hs_data[task_idx].ending_logprob[ending_idx] /= hs_data[task_idx].ending_logprob_count[ending_idx];
  210. // printf("task %lu, ending %lu, whole_len %lu, context_len %lu, ending_logprob_count %lu, ending_logprob %.4f\n",
  211. // task_idx,ending_idx,whole_size,context_size, hs_data[task_idx].ending_logprob_count[ending_idx], hs_data[task_idx].ending_logprob[ending_idx] );
  212. }
  213. // Find the ending with maximum logprob
  214. size_t ending_logprob_max_idx = -1;
  215. double ending_logprob_max_val = -INFINITY;
  216. for (size_t j=0; j < 4; j++) {
  217. if (hs_data[task_idx].ending_logprob[j] > ending_logprob_max_val) {
  218. ending_logprob_max_idx = j;
  219. ending_logprob_max_val = hs_data[task_idx].ending_logprob[j];
  220. }
  221. }
  222. // printf("max logprob ending idx %lu, gold ending idx %lu\n", ending_logprob_max_idx, hs_data[task_idx].gold_ending_idx);
  223. // If the gold ending got the maximum logprobe add one accuracy point
  224. if (ending_logprob_max_idx == hs_data[task_idx].gold_ending_idx) {
  225. acc += 1.0;
  226. }
  227. // Print the accumulated accuracy mean x 100
  228. printf("%zu\t%.8lf\n",task_idx+1, acc/double(task_idx+1)*100.0);
  229. fflush(stdout);
  230. }
  231. delete [] hs_data;
  232. printf("\n");
  233. }
  234. int main(int argc, char ** argv) {
  235. gpt_params params;
  236. params.n_batch = 512;
  237. if (gpt_params_parse(argc, argv, params) == false) {
  238. return 1;
  239. }
  240. params.perplexity = true;
  241. params.n_batch = std::min(params.n_batch, params.n_ctx);
  242. if (params.n_ctx > 2048) {
  243. fprintf(stderr, "%s: warning: model might not support context sizes greater than 2048 tokens (%d specified);"
  244. "expect poor results\n", __func__, params.n_ctx);
  245. }
  246. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  247. if (params.seed == LLAMA_DEFAULT_SEED) {
  248. params.seed = time(NULL);
  249. }
  250. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  251. std::mt19937 rng(params.seed);
  252. if (params.random_prompt) {
  253. params.prompt = gpt_random_prompt(rng);
  254. }
  255. llama_backend_init(params.numa);
  256. llama_model * model;
  257. llama_context * ctx;
  258. // load the model and apply lora adapter, if any
  259. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  260. if (model == NULL) {
  261. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  262. return 1;
  263. }
  264. // print system information
  265. {
  266. fprintf(stderr, "\n");
  267. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  268. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  269. }
  270. if (params.hellaswag) {
  271. hellaswag_score(ctx, params);
  272. } else {
  273. perplexity(ctx, params);
  274. }
  275. llama_print_timings(ctx);
  276. llama_free(ctx);
  277. llama_free_model(model);
  278. llama_backend_free();
  279. return 0;
  280. }