perplexity.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. #include "build-info.h"
  2. #include "common.h"
  3. #include "llama.h"
  4. #include <cmath>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <ctime>
  8. #include <sstream>
  9. #include <thread>
  10. #include <mutex>
  11. #include <vector>
  12. #if defined(_MSC_VER)
  13. #pragma warning(disable: 4244 4267) // possible loss of data
  14. #endif
  15. struct results_perplexity {
  16. std::vector<llama_token> tokens;
  17. double ppl_value;
  18. std::vector<float> logits;
  19. std::vector<float> probs;
  20. };
  21. struct results_log_softmax {
  22. double log_softmax;
  23. float logit;
  24. float prob;
  25. };
  26. static void write_logfile(
  27. const llama_context * ctx, const gpt_params & params, const llama_model * model,
  28. const struct results_perplexity & results
  29. ) {
  30. if (params.logdir.empty()) {
  31. return;
  32. }
  33. if (params.hellaswag) {
  34. fprintf(stderr, "%s: warning: logging results is not implemented for HellaSwag. No files will be written.\n", __func__);
  35. return;
  36. }
  37. const std::string timestamp = get_sortable_timestamp();
  38. const bool success = create_directory_with_parents(params.logdir);
  39. if (!success) {
  40. fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n",
  41. __func__, params.logdir.c_str());
  42. return;
  43. }
  44. const std::string logfile_path = params.logdir + timestamp + ".yml";
  45. FILE * logfile = fopen(logfile_path.c_str(), "w");
  46. if (logfile == NULL) {
  47. fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
  48. return;
  49. }
  50. fprintf(logfile, "binary: main\n");
  51. char model_desc[128];
  52. llama_model_desc(model, model_desc, sizeof(model_desc));
  53. dump_non_result_info_yaml(logfile, params, ctx, timestamp, results.tokens, model_desc);
  54. fprintf(logfile, "\n");
  55. fprintf(logfile, "######################\n");
  56. fprintf(logfile, "# Perplexity Results #\n");
  57. fprintf(logfile, "######################\n");
  58. fprintf(logfile, "\n");
  59. dump_vector_float_yaml(logfile, "logits", results.logits);
  60. fprintf(logfile, "ppl_value: %f\n", results.ppl_value);
  61. dump_vector_float_yaml(logfile, "probs", results.probs);
  62. llama_dump_timing_info_yaml(logfile, ctx);
  63. fclose(logfile);
  64. }
  65. static std::vector<float> softmax(const std::vector<float>& logits) {
  66. std::vector<float> probs(logits.size());
  67. float max_logit = logits[0];
  68. for (float v : logits) max_logit = std::max(max_logit, v);
  69. double sum_exp = 0.0;
  70. for (size_t i = 0; i < logits.size(); i++) {
  71. // Subtract the maximum logit value from the current logit value for numerical stability
  72. const float logit = logits[i] - max_logit;
  73. const float exp_logit = expf(logit);
  74. sum_exp += exp_logit;
  75. probs[i] = exp_logit;
  76. }
  77. for (size_t i = 0; i < probs.size(); i++) probs[i] /= sum_exp;
  78. return probs;
  79. }
  80. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  81. float max_logit = logits[0];
  82. for (int i = 1; i < n_vocab; ++i) max_logit = std::max(max_logit, logits[i]);
  83. double sum_exp = 0.0;
  84. for (int i = 0; i < n_vocab; ++i) sum_exp += expf(logits[i] - max_logit);
  85. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  86. }
  87. static void process_logits(
  88. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  89. double & nll, double & nll2, float * logit_history, float * prob_history
  90. ) {
  91. std::mutex mutex;
  92. int counter = 0;
  93. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  94. double local_nll = 0, local_nll2 = 0;
  95. while (true) {
  96. std::unique_lock<std::mutex> lock(mutex);
  97. int i = counter++;
  98. if (i >= n_token) {
  99. nll += local_nll; nll2 += local_nll2;
  100. break;
  101. }
  102. lock.unlock();
  103. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  104. const double v = -results.log_softmax;
  105. local_nll += v;
  106. local_nll2 += v*v;
  107. logit_history[i] = results.logit;
  108. prob_history[i] = results.prob;
  109. }
  110. };
  111. for (auto & w : workers) w = std::thread(compute);
  112. compute();
  113. for (auto & w : workers) w.join();
  114. }
  115. static results_perplexity perplexity_v2(llama_context * ctx, const gpt_params & params) {
  116. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  117. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  118. // Output: `perplexity: 13.5106 [114/114]`
  119. // BOS tokens will be added for each chunk before eval
  120. const bool is_spm = llama_vocab_type(ctx) == LLAMA_VOCAB_TYPE_SPM;
  121. const bool add_bos = is_spm;
  122. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  123. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  124. if (int(tokens.size()) < 2*params.n_ctx) {
  125. fprintf(stderr, "%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*params.n_ctx,
  126. params.n_ctx);
  127. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  128. return {std::move(tokens), 0., {}, {}};
  129. }
  130. std::vector<float> logit_history;
  131. std::vector<float> prob_history;
  132. logit_history.resize(tokens.size());
  133. prob_history.resize(tokens.size());
  134. if (params.ppl_stride <= 0) {
  135. fprintf(stderr, "%s: stride is %d but must be greater than zero!\n",__func__,params.ppl_stride);
  136. return {tokens, -1, logit_history, prob_history};
  137. }
  138. const int calc_chunk = params.n_ctx;
  139. fprintf(stderr, "%s: have %zu tokens. Calculation chunk = %d\n", __func__, tokens.size(), calc_chunk);
  140. if (int(tokens.size()) <= calc_chunk) {
  141. fprintf(stderr, "%s: there are only %zu tokens, this is not enough for a context size of %d and stride %d\n",__func__,
  142. tokens.size(), params.n_ctx, params.ppl_stride);
  143. return {tokens, -1, logit_history, prob_history};
  144. }
  145. const int n_chunk_max = (tokens.size() - calc_chunk + params.ppl_stride - 1) / params.ppl_stride;
  146. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  147. const int n_vocab = llama_n_vocab(ctx);
  148. const int n_batch = params.n_batch;
  149. int count = 0;
  150. double nll = 0.0;
  151. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  152. for (int i = 0; i < n_chunk; ++i) {
  153. const int start = i * params.ppl_stride;
  154. const int end = start + calc_chunk;
  155. const int num_batches = (calc_chunk + n_batch - 1) / n_batch;
  156. //fprintf(stderr, "%s: evaluating %d...%d using %d batches\n", __func__, start, end, num_batches);
  157. std::vector<float> logits;
  158. const auto t_start = std::chrono::high_resolution_clock::now();
  159. for (int j = 0; j < num_batches; ++j) {
  160. const int batch_start = start + j * n_batch;
  161. const int batch_size = std::min(end - batch_start, n_batch);
  162. //fprintf(stderr, " Batch %d: starts at %d, size is %d, n_past is %d\n",j,batch_start,batch_size,j * n_batch);
  163. if (llama_eval(ctx, tokens.data() + batch_start, batch_size, j * n_batch, params.n_threads)) {
  164. //fprintf(stderr, "%s : failed to eval\n", __func__);
  165. return {tokens, -1, logit_history, prob_history};
  166. }
  167. // save original token and restore it after eval
  168. const auto token_org = tokens[batch_start];
  169. // add BOS token for the first batch of each chunk
  170. if (add_bos && j == 0) {
  171. tokens[batch_start] = llama_token_bos(ctx);
  172. }
  173. const auto batch_logits = llama_get_logits(ctx);
  174. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  175. if (j == 0) {
  176. tokens[batch_start] = token_org;
  177. }
  178. }
  179. const auto t_end = std::chrono::high_resolution_clock::now();
  180. if (i == 0) {
  181. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  182. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  183. int total_seconds = (int)(t_total * n_chunk);
  184. if (total_seconds >= 60*60) {
  185. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  186. total_seconds = total_seconds % (60*60);
  187. }
  188. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  189. }
  190. //fprintf(stderr, "%s: using tokens %d...%d\n",__func__,params.n_ctx - params.ppl_stride + start, params.n_ctx + start);
  191. for (int j = params.n_ctx - params.ppl_stride - 1; j < params.n_ctx - 1; ++j) {
  192. // Calculate probability of next token, given the previous ones.
  193. const std::vector<float> tok_logits(
  194. logits.begin() + (j + 0) * n_vocab,
  195. logits.begin() + (j + 1) * n_vocab);
  196. const float prob = softmax(tok_logits)[tokens[start + j + 1]];
  197. logit_history[start + j + 1] = tok_logits[tokens[start + j + 1]];
  198. prob_history[start + j + 1] = prob;
  199. nll += -std::log(prob);
  200. ++count;
  201. }
  202. // perplexity is e^(average negative log-likelihood)
  203. if (params.ppl_output_type == 0) {
  204. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  205. } else {
  206. printf("%8d %.4lf\n", i*params.ppl_stride, std::exp(nll / count));
  207. }
  208. fflush(stdout);
  209. }
  210. printf("\n");
  211. return {tokens, std::exp(nll / count), logit_history, prob_history};
  212. }
  213. static results_perplexity perplexity(llama_context * ctx, const gpt_params & params) {
  214. if (params.ppl_stride > 0) {
  215. return perplexity_v2(ctx, params);
  216. }
  217. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  218. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  219. // Output: `perplexity: 13.5106 [114/114]`
  220. // BOS tokens will be added for each chunk before eval
  221. const bool is_spm = llama_vocab_type(ctx) == LLAMA_VOCAB_TYPE_SPM;
  222. const bool add_bos = is_spm;
  223. auto tim1 = std::chrono::high_resolution_clock::now();
  224. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  225. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  226. auto tim2 = std::chrono::high_resolution_clock::now();
  227. fprintf(stderr, "%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  228. if (int(tokens.size()) < 2*params.n_ctx) {
  229. fprintf(stderr, "%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*params.n_ctx,
  230. params.n_ctx);
  231. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  232. return {std::move(tokens), 0., {}, {}};
  233. }
  234. std::vector<float> logit_history;
  235. logit_history.resize(tokens.size());
  236. std::vector<float> prob_history;
  237. prob_history.resize(tokens.size());
  238. const int n_chunk_max = tokens.size() / params.n_ctx;
  239. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  240. const int n_vocab = llama_n_vocab(ctx);
  241. const int n_batch = params.n_batch;
  242. int count = 0;
  243. double nll = 0.0;
  244. double nll2 = 0.0;
  245. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  246. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  247. for (int i = 0; i < n_chunk; ++i) {
  248. const int start = i * params.n_ctx;
  249. const int end = start + params.n_ctx;
  250. const int num_batches = (params.n_ctx + n_batch - 1) / n_batch;
  251. std::vector<float> logits;
  252. const auto t_start = std::chrono::high_resolution_clock::now();
  253. for (int j = 0; j < num_batches; ++j) {
  254. const int batch_start = start + j * n_batch;
  255. const int batch_size = std::min(end - batch_start, n_batch);
  256. // save original token and restore it after eval
  257. const auto token_org = tokens[batch_start];
  258. // add BOS token for the first batch of each chunk
  259. if (add_bos && j == 0) {
  260. tokens[batch_start] = llama_token_bos(ctx);
  261. }
  262. if (llama_eval(ctx, tokens.data() + batch_start, batch_size, j * n_batch, params.n_threads)) {
  263. fprintf(stderr, "%s : failed to eval\n", __func__);
  264. return {tokens, -1, logit_history, prob_history};
  265. }
  266. // restore the original token in case it was set to BOS
  267. tokens[batch_start] = token_org;
  268. const auto batch_logits = llama_get_logits(ctx);
  269. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  270. }
  271. const auto t_end = std::chrono::high_resolution_clock::now();
  272. if (i == 0) {
  273. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  274. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  275. int total_seconds = (int)(t_total * n_chunk);
  276. if (total_seconds >= 60*60) {
  277. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  278. total_seconds = total_seconds % (60*60);
  279. }
  280. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  281. }
  282. // We get the logits for all the tokens in the context window (params.n_ctx)
  283. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  284. // calculate the perplexity over the last half of the window (so the model always has
  285. // some context to predict the token).
  286. //
  287. // We rely on the fact that attention in the forward pass only looks at previous
  288. // tokens here, so the logits returned for each token are an accurate representation
  289. // of what the model would have predicted at that point.
  290. //
  291. // Example, we have a context window of 512, we will compute perplexity for each of the
  292. // last 256 tokens. Then, we split the input up into context window size chunks to
  293. // process the entire prompt.
  294. const int first = params.n_ctx/2;
  295. process_logits(n_vocab, logits.data() + first*n_vocab, tokens.data() + start + first, params.n_ctx - 1 - first,
  296. workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
  297. count += params.n_ctx - first - 1;
  298. // perplexity is e^(average negative log-likelihood)
  299. if (params.ppl_output_type == 0) {
  300. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  301. } else {
  302. double av = nll/count;
  303. double av2 = nll2/count - av*av;
  304. if (av2 > 0) av2 = sqrt(av2/(count-1));
  305. printf("%8d %.4lf %4lf %4lf\n", i*params.n_ctx, std::exp(nll / count), av, av2);
  306. }
  307. fflush(stdout);
  308. }
  309. printf("\n");
  310. nll2 /= count;
  311. nll /= count;
  312. const double ppl = exp(nll);
  313. nll2 -= nll * nll;
  314. if (nll2 > 0) {
  315. nll2 = sqrt(nll2/(count-1));
  316. printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  317. } else {
  318. printf("Unexpected negative standard deviation of log(prob)\n");
  319. }
  320. return {tokens, ppl, logit_history, prob_history};
  321. }
  322. static std::vector<float> hellaswag_evaluate_tokens(
  323. llama_context * ctx, const std::vector<int>& tokens, int n_past, int n_batch, int n_vocab, int n_thread
  324. ) {
  325. std::vector<float> result;
  326. result.reserve(tokens.size() * n_vocab);
  327. size_t n_chunk = (tokens.size() + n_batch - 1)/n_batch;
  328. for (size_t i_chunk = 0; i_chunk < n_chunk; ++i_chunk) {
  329. size_t n_tokens = tokens.size() - i_chunk * n_batch;
  330. n_tokens = std::min(n_tokens, size_t(n_batch));
  331. if (llama_eval(ctx, tokens.data() + i_chunk * n_batch, n_tokens, n_past, n_thread)) {
  332. fprintf(stderr, "%s : failed to eval\n", __func__);
  333. return {};
  334. }
  335. const auto logits = llama_get_logits(ctx);
  336. result.insert(result.end(), logits, logits + n_tokens * n_vocab);
  337. n_past += n_tokens;
  338. }
  339. return result;
  340. }
  341. static void hellaswag_score(llama_context * ctx, const gpt_params & params) {
  342. // Calculates hellaswag score (acc_norm) from prompt
  343. //
  344. // Data extracted from the HellaSwag validation dataset (MIT license) https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl
  345. // All used data fields are preprocessed as in https://github.com/EleutherAI/lm-evaluation-harness/blob/df3da98c5405deafd519c2ddca52bb7c3fe36bef/lm_eval/tasks/hellaswag.py#L62-L68
  346. //
  347. // All 10042 tasks should be extracted to keep the results standardized like other implementations.
  348. //
  349. // Datafile layout:
  350. // ['??'] denotes json fields
  351. // 6 lines per task:
  352. // ['activity_label'] + ": " +['ctx'] - The first part of the query, the context
  353. // ['label'] - The index the best common sense ending aka gold ending
  354. // ['endings'][0] - Endings added to the first part of the query
  355. // ['endings'][1]
  356. // ['endings'][2]
  357. // ['endings'][3]
  358. std::vector<std::string> prompt_lines;
  359. std::istringstream strstream(params.prompt);
  360. std::string line;
  361. while (std::getline(strstream,line,'\n')) {
  362. prompt_lines.push_back(line);
  363. }
  364. if( prompt_lines.size() % 6 != 0) {
  365. fprintf(stderr, "%s : number of lines in prompt not a multiple of 6.\n", __func__);
  366. return;
  367. }
  368. size_t hs_task_count = prompt_lines.size()/6;
  369. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, hs_task_count);
  370. const bool is_spm = llama_vocab_type(ctx) == LLAMA_VOCAB_TYPE_SPM;
  371. fprintf(stderr, "================================= is_spm = %d\n", is_spm);
  372. // This is needed as usual for LLaMA models
  373. const bool add_bos = is_spm;
  374. // Number of tasks to use when computing the score
  375. if ( params.hellaswag_tasks < hs_task_count ) {
  376. hs_task_count = params.hellaswag_tasks;
  377. }
  378. // The tasks should be randomized so the score stabilizes quickly.
  379. bool randomize_tasks = true;
  380. // The random seed should not impact the final result if the computation is done over enough tasks, so kept hardcoded for now
  381. std::mt19937 rng(1);
  382. // Dataholder for hellaswag tasks
  383. struct hs_data_t {
  384. std::string context;
  385. size_t gold_ending_idx;
  386. std::string ending[4];
  387. size_t ending_logprob_count[4];
  388. double ending_logprob[4];
  389. };
  390. fprintf(stderr, "%s : selecting %zu %s tasks.\n", __func__, hs_task_count, (randomize_tasks?"randomized":"the first") );
  391. // Select and read data from prompt lines
  392. hs_data_t *hs_data = new hs_data_t[hs_task_count];
  393. for (size_t i=0; i < hs_task_count; i++) {
  394. size_t idx = i;
  395. // Select a random example of those left in the prompt
  396. if (randomize_tasks) {
  397. std::uniform_int_distribution<size_t> dist(0, prompt_lines.size()/6-1 ) ;
  398. idx = dist(rng);
  399. }
  400. hs_data[i].context = prompt_lines[idx*6];
  401. hs_data[i].gold_ending_idx = std::stoi( prompt_lines[idx*6+1] );
  402. for (size_t j=0; j < 4; j++) {
  403. hs_data[i].ending[j] = prompt_lines[idx*6+2+j];
  404. }
  405. // Delete the selected random example from the prompt
  406. if (randomize_tasks) {
  407. prompt_lines.erase( std::next(prompt_lines.begin(),idx*6) , std::next(prompt_lines.begin(),idx*6+6) );
  408. }
  409. }
  410. fprintf(stderr, "%s : calculating hellaswag score over selected tasks.\n", __func__);
  411. printf("\ntask\tacc_norm\n");
  412. double acc = 0.0f;
  413. const int n_vocab = llama_n_vocab(ctx);
  414. std::vector<std::vector<int>> ending_tokens(4);
  415. std::vector<float> tok_logits(n_vocab);
  416. for (size_t task_idx = 0; task_idx < hs_task_count; task_idx++) {
  417. // Tokenize the context to count tokens
  418. std::vector<int> context_embd = ::llama_tokenize(ctx, hs_data[task_idx].context, add_bos);
  419. size_t context_size = context_embd.size();
  420. for (int i = 0; i < 4; ++i) {
  421. ending_tokens[i] = ::llama_tokenize(ctx, hs_data[task_idx].context + " " + hs_data[task_idx].ending[i], add_bos);
  422. for (int k = 0; k < int(context_size); ++k) {
  423. if (ending_tokens[i][k] != context_embd[k]) {
  424. fprintf(stderr, "Oops: ending %d of task %d differs from context at position %d\n",i,int(task_idx),k);
  425. break;
  426. }
  427. }
  428. }
  429. // Do the 1st ending
  430. // In this case we include the context when evaluating
  431. //auto query_embd = ::llama_tokenize(ctx, hs_data[task_idx].context + hs_data[task_idx].ending[0], add_bos);
  432. auto query_embd = ending_tokens[0];
  433. auto query_size = query_embd.size();
  434. // Stop if query wont fit the ctx window
  435. if (query_size > (size_t)params.n_ctx) {
  436. fprintf(stderr, "%s : number of tokens in query %zu > n_ctxl\n", __func__, query_size);
  437. return;
  438. }
  439. // Speedup small evaluations by evaluating atleast 32 tokens
  440. if (query_size < 32) {
  441. query_embd.resize(32);
  442. }
  443. auto logits = hellaswag_evaluate_tokens(ctx, query_embd, 0, params.n_batch, n_vocab, params.n_threads);
  444. if (logits.empty()) {
  445. fprintf(stderr, "%s : failed to eval\n", __func__);
  446. return;
  447. }
  448. std::memcpy(tok_logits.data(), logits.data() + (context_size-1)*n_vocab, n_vocab*sizeof(float));
  449. const auto first_probs = softmax(tok_logits);
  450. hs_data[task_idx].ending_logprob_count[0] = 1;
  451. hs_data[task_idx].ending_logprob[0] = std::log(first_probs[query_embd[context_size]]);
  452. // Calculate the logprobs over the ending
  453. for (size_t j = context_size; j < query_size - 1; j++) {
  454. std::memcpy(tok_logits.data(), logits.data() + j*n_vocab, n_vocab*sizeof(float));
  455. const float prob = softmax(tok_logits)[query_embd[j + 1]];
  456. hs_data[task_idx].ending_logprob[0] += std::log(prob);
  457. hs_data[task_idx].ending_logprob_count[0]++;
  458. }
  459. // Calculate the mean token logprob for acc_norm
  460. hs_data[task_idx].ending_logprob[0] /= hs_data[task_idx].ending_logprob_count[0];
  461. // Do the remaining endings
  462. // For these, we use the bare ending with n_past = context_size
  463. //
  464. for (size_t ending_idx = 1; ending_idx < 4; ending_idx++) {
  465. // Tokenize the query
  466. query_embd.resize(ending_tokens[ending_idx].size() - context_size);
  467. std::memcpy(query_embd.data(), ending_tokens[ending_idx].data() + context_size, query_embd.size()*sizeof(int));
  468. query_size = query_embd.size();
  469. // Stop if query wont fit the ctx window
  470. if (context_size + query_size > (size_t)params.n_ctx) {
  471. fprintf(stderr, "%s : number of tokens in query %zu > n_ctxl\n", __func__, query_size);
  472. return;
  473. }
  474. // Speedup small evaluations by evaluating atleast 32 tokens
  475. // No, resizing to 32 is actually slightly slower (at least on CUDA)
  476. //if (query_size < 32) {
  477. // query_embd.resize(32);
  478. //}
  479. // Evaluate the query
  480. logits = hellaswag_evaluate_tokens(ctx, query_embd, context_size, params.n_batch, n_vocab, params.n_threads);
  481. if (logits.empty()) {
  482. fprintf(stderr, "%s : failed to eval\n", __func__);
  483. return;
  484. }
  485. hs_data[task_idx].ending_logprob_count[ending_idx] = 1;
  486. hs_data[task_idx].ending_logprob[ending_idx] = std::log(first_probs[query_embd[0]]);
  487. // Calculate the logprobs over the ending
  488. for (size_t j = 0; j < query_size - 1; j++) {
  489. std::memcpy(tok_logits.data(), logits.data() + j*n_vocab, n_vocab*sizeof(float));
  490. const float prob = softmax(tok_logits)[query_embd[j + 1]];
  491. hs_data[task_idx].ending_logprob[ending_idx] += std::log(prob);
  492. hs_data[task_idx].ending_logprob_count[ending_idx]++;
  493. }
  494. // Calculate the mean token logprob for acc_norm
  495. hs_data[task_idx].ending_logprob[ending_idx] /= hs_data[task_idx].ending_logprob_count[ending_idx];
  496. // printf("task %lu, ending %lu, whole_len %lu, context_len %lu, ending_logprob_count %lu, ending_logprob %.4f\n",
  497. // 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] );
  498. }
  499. // Find the ending with maximum logprob
  500. size_t ending_logprob_max_idx = 0;
  501. double ending_logprob_max_val = hs_data[task_idx].ending_logprob[0];
  502. for (size_t j = 1; j < 4; j++) {
  503. if (hs_data[task_idx].ending_logprob[j] > ending_logprob_max_val) {
  504. ending_logprob_max_idx = j;
  505. ending_logprob_max_val = hs_data[task_idx].ending_logprob[j];
  506. }
  507. }
  508. // printf("max logprob ending idx %lu, gold ending idx %lu\n", ending_logprob_max_idx, hs_data[task_idx].gold_ending_idx);
  509. // If the gold ending got the maximum logprobe add one accuracy point
  510. if (ending_logprob_max_idx == hs_data[task_idx].gold_ending_idx) {
  511. acc += 1.0;
  512. }
  513. // Print the accumulated accuracy mean x 100
  514. printf("%zu\t%.8lf\n",task_idx+1, acc/double(task_idx+1)*100.0);
  515. fflush(stdout);
  516. }
  517. delete [] hs_data;
  518. printf("\n");
  519. }
  520. int main(int argc, char ** argv) {
  521. gpt_params params;
  522. params.n_batch = 512;
  523. if (!gpt_params_parse(argc, argv, params)) {
  524. return 1;
  525. }
  526. params.perplexity = true;
  527. params.n_batch = std::min(params.n_batch, params.n_ctx);
  528. if (params.ppl_stride > 0) {
  529. fprintf(stderr, "Will perform strided perplexity calculation -> adjusting context size from %d to %d\n",
  530. params.n_ctx, params.n_ctx + params.ppl_stride/2);
  531. params.n_ctx += params.ppl_stride/2;
  532. }
  533. print_build_info();
  534. if (params.seed == LLAMA_DEFAULT_SEED) {
  535. params.seed = time(NULL);
  536. }
  537. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  538. std::mt19937 rng(params.seed);
  539. if (params.random_prompt) {
  540. params.prompt = gpt_random_prompt(rng);
  541. }
  542. llama_backend_init(params.numa);
  543. llama_model * model;
  544. llama_context * ctx;
  545. // load the model and apply lora adapter, if any
  546. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  547. if (model == NULL) {
  548. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  549. return 1;
  550. }
  551. const int n_ctx_train = llama_n_ctx_train(ctx);
  552. if (params.n_ctx > n_ctx_train) {
  553. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  554. __func__, n_ctx_train, params.n_ctx);
  555. }
  556. // print system information
  557. {
  558. fprintf(stderr, "\n");
  559. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  560. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  561. }
  562. struct results_perplexity results;
  563. if (params.hellaswag) {
  564. hellaswag_score(ctx, params);
  565. } else {
  566. results = perplexity(ctx, params);
  567. }
  568. llama_print_timings(ctx);
  569. write_logfile(ctx, params, model, results);
  570. llama_free(ctx);
  571. llama_free_model(model);
  572. llama_backend_free();
  573. return 0;
  574. }