perplexity.cpp 21 KB

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