perplexity.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. #include <cmath>
  5. #include <ctime>
  6. #include <sstream>
  7. #include <cstring>
  8. #if defined(_MSC_VER)
  9. #pragma warning(disable: 4244 4267) // possible loss of data
  10. #endif
  11. std::vector<float> softmax(const std::vector<float>& logits) {
  12. std::vector<float> probs(logits.size());
  13. float max_logit = logits[0];
  14. for (float v : logits) max_logit = std::max(max_logit, v);
  15. double sum_exp = 0.0;
  16. for (size_t i = 0; i < logits.size(); i++) {
  17. // Subtract the maximum logit value from the current logit value for numerical stability
  18. const float logit = logits[i] - max_logit;
  19. const float exp_logit = expf(logit);
  20. sum_exp += exp_logit;
  21. probs[i] = exp_logit;
  22. }
  23. for (size_t i = 0; i < probs.size(); i++) probs[i] /= sum_exp;
  24. return probs;
  25. }
  26. void perplexity(llama_context * ctx, const gpt_params & params) {
  27. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  28. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  29. // Output: `perplexity: 13.5106 [114/114]`
  30. // BOS tokens will be added for each chunk before eval
  31. auto tokens = ::llama_tokenize(ctx, params.prompt, true);
  32. const int n_chunk_max = tokens.size() / params.n_ctx;
  33. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  34. const int n_vocab = llama_n_vocab(ctx);
  35. const int n_batch = params.n_batch;
  36. int count = 0;
  37. double nll = 0.0;
  38. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  39. for (int i = 0; i < n_chunk; ++i) {
  40. const int start = i * params.n_ctx;
  41. const int end = start + params.n_ctx;
  42. const int num_batches = (params.n_ctx + n_batch - 1) / n_batch;
  43. std::vector<float> logits;
  44. const auto t_start = std::chrono::high_resolution_clock::now();
  45. for (int j = 0; j < num_batches; ++j) {
  46. const int batch_start = start + j * n_batch;
  47. const int batch_size = std::min(end - batch_start, n_batch);
  48. // save original token and restore it after eval
  49. const auto token_org = tokens[batch_start];
  50. // add BOS token for the first batch of each chunk
  51. if (j == 0) {
  52. tokens[batch_start] = llama_token_bos(ctx);
  53. }
  54. if (llama_eval(ctx, tokens.data() + batch_start, batch_size, j * n_batch, params.n_threads)) {
  55. fprintf(stderr, "%s : failed to eval\n", __func__);
  56. return;
  57. }
  58. // restore the original token in case it was set to BOS
  59. tokens[batch_start] = token_org;
  60. const auto batch_logits = llama_get_logits(ctx);
  61. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  62. }
  63. const auto t_end = std::chrono::high_resolution_clock::now();
  64. if (i == 0) {
  65. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  66. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  67. int total_seconds = (int)(t_total * n_chunk);
  68. if (total_seconds >= 60*60) {
  69. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  70. total_seconds = total_seconds % (60*60);
  71. }
  72. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  73. }
  74. // We get the logits for all the tokens in the context window (params.n_ctx)
  75. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  76. // calculate the perplexity over the last half of the window (so the model always has
  77. // some context to predict the token).
  78. //
  79. // We rely on the fact that attention in the forward pass only looks at previous
  80. // tokens here, so the logits returned for each token are an accurate representation
  81. // of what the model would have predicted at that point.
  82. //
  83. // Example, we have a context window of 512, we will compute perplexity for each of the
  84. // last 256 tokens. Then, we split the input up into context window size chunks to
  85. // process the entire prompt.
  86. for (int j = std::min(512, params.n_ctx / 2); j < params.n_ctx - 1; ++j) {
  87. // Calculate probability of next token, given the previous ones.
  88. const std::vector<float> tok_logits(
  89. logits.begin() + (j + 0) * n_vocab,
  90. logits.begin() + (j + 1) * n_vocab);
  91. const float prob = softmax(tok_logits)[tokens[start + j + 1]];
  92. nll += -std::log(prob);
  93. ++count;
  94. }
  95. // perplexity is e^(average negative log-likelihood)
  96. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  97. fflush(stdout);
  98. }
  99. printf("\n");
  100. }
  101. std::vector<float> hellaswag_evaluate_tokens(llama_context * ctx, const std::vector<int>& tokens, int n_past, int n_batch,
  102. int n_vocab, int n_thread) {
  103. std::vector<float> result;
  104. result.reserve(tokens.size() * n_vocab);
  105. size_t n_chunk = (tokens.size() + n_batch - 1)/n_batch;
  106. for (size_t i_chunk = 0; i_chunk < n_chunk; ++i_chunk) {
  107. size_t n_tokens = tokens.size() - i_chunk * n_batch;
  108. n_tokens = std::min(n_tokens, size_t(n_batch));
  109. if (llama_eval(ctx, tokens.data() + i_chunk * n_batch, n_tokens, n_past, n_thread)) {
  110. fprintf(stderr, "%s : failed to eval\n", __func__);
  111. return {};
  112. }
  113. const auto logits = llama_get_logits(ctx);
  114. result.insert(result.end(), logits, logits + n_tokens * n_vocab);
  115. n_past += n_tokens;
  116. }
  117. return result;
  118. }
  119. void hellaswag_score(llama_context * ctx, const gpt_params & params) {
  120. // Calculates hellaswag score (acc_norm) from prompt
  121. //
  122. // Data extracted from the HellaSwag validation dataset (MIT license) https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl
  123. // All used data fields are preprocessed as in https://github.com/EleutherAI/lm-evaluation-harness/blob/df3da98c5405deafd519c2ddca52bb7c3fe36bef/lm_eval/tasks/hellaswag.py#L62-L68
  124. //
  125. // All 10042 tasks should be extracted to keep the results standardized like other implementations.
  126. //
  127. // Datafile layout:
  128. // ['??'] denotes json fields
  129. // 6 lines per task:
  130. // ['activity_label'] + ": " +['ctx'] - The first part of the query, the context
  131. // ['label'] - The index the best common sense ending aka gold ending
  132. // ['endings'][0] - Endings added to the first part of the query
  133. // ['endings'][1]
  134. // ['endings'][2]
  135. // ['endings'][3]
  136. std::vector<std::string> prompt_lines;
  137. std::istringstream strstream(params.prompt);
  138. std::string line;
  139. while (std::getline(strstream,line,'\n')) {
  140. prompt_lines.push_back(line);
  141. }
  142. if( prompt_lines.size() % 6 != 0) {
  143. fprintf(stderr, "%s : number of lines in prompt not a multiple of 6.\n", __func__);
  144. return;
  145. }
  146. size_t hs_task_count = prompt_lines.size()/6;
  147. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, hs_task_count);
  148. // This is needed as usual for LLaMA models
  149. bool prepend_bos = true;
  150. // Number of tasks to use when computing the score
  151. if ( params.hellaswag_tasks < hs_task_count ) {
  152. hs_task_count = params.hellaswag_tasks;
  153. }
  154. // The tasks should be randomized so the score stabilizes quickly.
  155. bool randomize_tasks = true;
  156. // The random seed should not impact the final result if the computation is done over enough tasks, so kept hardcoded for now
  157. std::mt19937 rng(1);
  158. // Dataholder for hellaswag tasks
  159. struct hs_data_t {
  160. std::string context;
  161. size_t gold_ending_idx;
  162. std::string ending[4];
  163. size_t ending_logprob_count[4];
  164. double ending_logprob[4];
  165. };
  166. fprintf(stderr, "%s : selecting %zu %s tasks.\n", __func__, hs_task_count, (randomize_tasks?"randomized":"the first") );
  167. // Select and read data from prompt lines
  168. hs_data_t *hs_data = new hs_data_t[hs_task_count];
  169. for (size_t i=0; i < hs_task_count; i++) {
  170. size_t idx = i;
  171. // Select a random example of those left in the prompt
  172. if (randomize_tasks) {
  173. std::uniform_int_distribution<size_t> dist(0, prompt_lines.size()/6-1 ) ;
  174. idx = dist(rng);
  175. }
  176. hs_data[i].context = prompt_lines[idx*6];
  177. hs_data[i].gold_ending_idx = std::stoi( prompt_lines[idx*6+1] );
  178. for (size_t j=0; j < 4; j++) {
  179. hs_data[i].ending[j] = " " + prompt_lines[idx*6+2+j];
  180. }
  181. // Delete the selected random example from the prompt
  182. if (randomize_tasks) {
  183. prompt_lines.erase( std::next(prompt_lines.begin(),idx*6) , std::next(prompt_lines.begin(),idx*6+6) );
  184. }
  185. }
  186. fprintf(stderr, "%s : calculating hellaswag score over selected tasks.\n", __func__);
  187. printf("\ntask\tacc_norm\n");
  188. double acc = 0.0f;
  189. const int n_vocab = llama_n_vocab(ctx);
  190. std::vector<float> tok_logits(n_vocab);
  191. for (size_t task_idx = 0; task_idx < hs_task_count; task_idx++) {
  192. // Tokenize the context to count tokens
  193. std::vector<int> context_embd = ::llama_tokenize(ctx, hs_data[task_idx].context, prepend_bos);
  194. size_t context_size = context_embd.size();
  195. // Do the 1st ending
  196. // In this case we include the context when evaluating
  197. auto query_embd = ::llama_tokenize(ctx, hs_data[task_idx].context + hs_data[task_idx].ending[0], prepend_bos);
  198. auto query_size = query_embd.size();
  199. //printf("First query: %d\n",(int)query_size);
  200. // Stop if query wont fit the ctx window
  201. if (query_size > (size_t)params.n_ctx) {
  202. fprintf(stderr, "%s : number of tokens in query %zu > n_ctxl\n", __func__, query_size);
  203. return;
  204. }
  205. // Speedup small evaluations by evaluating atleast 32 tokens
  206. if (query_size < 32) {
  207. query_embd.resize(32);
  208. }
  209. auto logits = hellaswag_evaluate_tokens(ctx, query_embd, 0, params.n_batch, n_vocab, params.n_threads);
  210. if (logits.empty()) {
  211. fprintf(stderr, "%s : failed to eval\n", __func__);
  212. return;
  213. }
  214. std::memcpy(tok_logits.data(), logits.data() + (context_size-1)*n_vocab, n_vocab*sizeof(float));
  215. const auto first_probs = softmax(tok_logits);
  216. hs_data[task_idx].ending_logprob_count[0] = 1;
  217. hs_data[task_idx].ending_logprob[0] = std::log(first_probs[query_embd[context_size]]);
  218. // Calculate the logprobs over the ending
  219. for (size_t j = context_size; j < query_size - 1; j++) {
  220. std::memcpy(tok_logits.data(), logits.data() + j*n_vocab, n_vocab*sizeof(float));
  221. const float prob = softmax(tok_logits)[query_embd[j + 1]];
  222. hs_data[task_idx].ending_logprob[0] += std::log(prob);
  223. hs_data[task_idx].ending_logprob_count[0]++;
  224. }
  225. // Calculate the mean token logprob for acc_norm
  226. hs_data[task_idx].ending_logprob[0] /= hs_data[task_idx].ending_logprob_count[0];
  227. // Do the remaining endings
  228. // For these, we use the bare ending with n_past = context_size
  229. //
  230. for (size_t ending_idx = 1; ending_idx < 4; ending_idx++) {
  231. // Tokenize the query
  232. query_embd = ::llama_tokenize(ctx, hs_data[task_idx].ending[ending_idx], false);
  233. query_size = query_embd.size();
  234. // Stop if query wont fit the ctx window
  235. if (context_size + query_size > (size_t)params.n_ctx) {
  236. fprintf(stderr, "%s : number of tokens in query %zu > n_ctxl\n", __func__, query_size);
  237. return;
  238. }
  239. // Speedup small evaluations by evaluating atleast 32 tokens
  240. // No, resizing to 32 is actually slightly slower (at least on CUDA)
  241. //if (query_size < 32) {
  242. // query_embd.resize(32);
  243. //}
  244. // Evaluate the query
  245. logits = hellaswag_evaluate_tokens(ctx, query_embd, context_size, params.n_batch, n_vocab, params.n_threads);
  246. if (logits.empty()) {
  247. fprintf(stderr, "%s : failed to eval\n", __func__);
  248. return;
  249. }
  250. hs_data[task_idx].ending_logprob_count[ending_idx] = 1;
  251. hs_data[task_idx].ending_logprob[ending_idx] = std::log(first_probs[query_embd[0]]);
  252. // Calculate the logprobs over the ending
  253. for (size_t j = 0; j < query_size - 1; j++) {
  254. std::memcpy(tok_logits.data(), logits.data() + j*n_vocab, n_vocab*sizeof(float));
  255. const float prob = softmax(tok_logits)[query_embd[j + 1]];
  256. hs_data[task_idx].ending_logprob[ending_idx] += std::log(prob);
  257. hs_data[task_idx].ending_logprob_count[ending_idx]++;
  258. }
  259. // Calculate the mean token logprob for acc_norm
  260. hs_data[task_idx].ending_logprob[ending_idx] /= hs_data[task_idx].ending_logprob_count[ending_idx];
  261. // printf("task %lu, ending %lu, whole_len %lu, context_len %lu, ending_logprob_count %lu, ending_logprob %.4f\n",
  262. // 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] );
  263. }
  264. // Find the ending with maximum logprob
  265. size_t ending_logprob_max_idx = 0;
  266. double ending_logprob_max_val = hs_data[task_idx].ending_logprob[0];
  267. for (size_t j = 1; j < 4; j++) {
  268. if (hs_data[task_idx].ending_logprob[j] > ending_logprob_max_val) {
  269. ending_logprob_max_idx = j;
  270. ending_logprob_max_val = hs_data[task_idx].ending_logprob[j];
  271. }
  272. }
  273. // printf("max logprob ending idx %lu, gold ending idx %lu\n", ending_logprob_max_idx, hs_data[task_idx].gold_ending_idx);
  274. // If the gold ending got the maximum logprobe add one accuracy point
  275. if (ending_logprob_max_idx == hs_data[task_idx].gold_ending_idx) {
  276. acc += 1.0;
  277. }
  278. // Print the accumulated accuracy mean x 100
  279. printf("%zu\t%.8lf\n",task_idx+1, acc/double(task_idx+1)*100.0);
  280. fflush(stdout);
  281. }
  282. delete [] hs_data;
  283. printf("\n");
  284. }
  285. int main(int argc, char ** argv) {
  286. gpt_params params;
  287. params.n_batch = 512;
  288. if (gpt_params_parse(argc, argv, params) == false) {
  289. return 1;
  290. }
  291. params.perplexity = true;
  292. params.n_batch = std::min(params.n_batch, params.n_ctx);
  293. if (params.n_ctx > 2048) {
  294. fprintf(stderr, "%s: warning: model might not support context sizes greater than 2048 tokens (%d specified);"
  295. "expect poor results\n", __func__, params.n_ctx);
  296. }
  297. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  298. if (params.seed == LLAMA_DEFAULT_SEED) {
  299. params.seed = time(NULL);
  300. }
  301. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  302. std::mt19937 rng(params.seed);
  303. if (params.random_prompt) {
  304. params.prompt = gpt_random_prompt(rng);
  305. }
  306. llama_backend_init(params.numa);
  307. llama_model * model;
  308. llama_context * ctx;
  309. // load the model and apply lora adapter, if any
  310. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  311. if (model == NULL) {
  312. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  313. return 1;
  314. }
  315. // print system information
  316. {
  317. fprintf(stderr, "\n");
  318. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  319. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  320. }
  321. if (params.hellaswag) {
  322. hellaswag_score(ctx, params);
  323. } else {
  324. perplexity(ctx, params);
  325. }
  326. llama_print_timings(ctx);
  327. llama_free(ctx);
  328. llama_free_model(model);
  329. llama_backend_free();
  330. return 0;
  331. }