perplexity.cpp 15 KB

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