1
0

perplexity.cpp 28 KB

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