perplexity.cpp 27 KB

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