perplexity.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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. #include <array>
  12. #include <fstream>
  13. #include <sstream>
  14. #if defined(_MSC_VER)
  15. #pragma warning(disable: 4244 4267) // possible loss of data
  16. #endif
  17. struct results_perplexity {
  18. std::vector<llama_token> tokens;
  19. double ppl_value;
  20. std::vector<float> logits;
  21. std::vector<float> probs;
  22. };
  23. struct results_log_softmax {
  24. double log_softmax;
  25. float logit;
  26. float prob;
  27. };
  28. static void write_logfile(
  29. const llama_context * ctx, const gpt_params & params, const llama_model * model,
  30. const struct results_perplexity & results
  31. ) {
  32. if (params.logdir.empty()) {
  33. return;
  34. }
  35. if (params.hellaswag) {
  36. fprintf(stderr, "%s: warning: logging results is not implemented for HellaSwag. No files will be written.\n", __func__);
  37. return;
  38. }
  39. const std::string timestamp = get_sortable_timestamp();
  40. const bool success = create_directory_with_parents(params.logdir);
  41. if (!success) {
  42. fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n",
  43. __func__, params.logdir.c_str());
  44. return;
  45. }
  46. const std::string logfile_path = params.logdir + timestamp + ".yml";
  47. FILE * logfile = fopen(logfile_path.c_str(), "w");
  48. if (logfile == NULL) {
  49. fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
  50. return;
  51. }
  52. fprintf(logfile, "binary: main\n");
  53. char model_desc[128];
  54. llama_model_desc(model, model_desc, sizeof(model_desc));
  55. dump_non_result_info_yaml(logfile, params, ctx, timestamp, results.tokens, model_desc);
  56. fprintf(logfile, "\n");
  57. fprintf(logfile, "######################\n");
  58. fprintf(logfile, "# Perplexity Results #\n");
  59. fprintf(logfile, "######################\n");
  60. fprintf(logfile, "\n");
  61. dump_vector_float_yaml(logfile, "logits", results.logits);
  62. fprintf(logfile, "ppl_value: %f\n", results.ppl_value);
  63. dump_vector_float_yaml(logfile, "probs", results.probs);
  64. llama_dump_timing_info_yaml(logfile, ctx);
  65. fclose(logfile);
  66. }
  67. static std::vector<float> softmax(const std::vector<float>& logits) {
  68. std::vector<float> probs(logits.size());
  69. float max_logit = logits[0];
  70. for (float v : logits) {
  71. max_logit = std::max(max_logit, v);
  72. }
  73. double sum_exp = 0.0;
  74. for (size_t i = 0; i < logits.size(); i++) {
  75. // Subtract the maximum logit value from the current logit value for numerical stability
  76. const float logit = logits[i] - max_logit;
  77. const float exp_logit = expf(logit);
  78. sum_exp += exp_logit;
  79. probs[i] = exp_logit;
  80. }
  81. for (size_t i = 0; i < probs.size(); i++) {
  82. probs[i] /= sum_exp;
  83. }
  84. return probs;
  85. }
  86. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  87. float max_logit = logits[0];
  88. for (int i = 1; i < n_vocab; ++i) {
  89. max_logit = std::max(max_logit, logits[i]);
  90. }
  91. double sum_exp = 0.0;
  92. for (int i = 0; i < n_vocab; ++i) {
  93. sum_exp += expf(logits[i] - max_logit);
  94. }
  95. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  96. }
  97. static void process_logits(
  98. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  99. double & nll, double & nll2, float * logit_history, float * prob_history
  100. ) {
  101. std::mutex mutex;
  102. int counter = 0;
  103. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  104. double local_nll = 0;
  105. double local_nll2 = 0;
  106. while (true) {
  107. std::unique_lock<std::mutex> lock(mutex);
  108. int i = counter++;
  109. if (i >= n_token) {
  110. nll += local_nll; nll2 += local_nll2;
  111. break;
  112. }
  113. lock.unlock();
  114. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  115. const double v = -results.log_softmax;
  116. local_nll += v;
  117. local_nll2 += v*v;
  118. logit_history[i] = results.logit;
  119. prob_history[i] = results.prob;
  120. }
  121. };
  122. for (auto & w : workers) {
  123. w = std::thread(compute);
  124. }
  125. compute();
  126. for (auto & w : workers) {
  127. w.join();
  128. }
  129. }
  130. static results_perplexity perplexity_v2(llama_context * ctx, const gpt_params & params) {
  131. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  132. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  133. // Output: `perplexity: 13.5106 [114/114]`
  134. // BOS tokens will be added for each chunk before eval
  135. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  136. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  137. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  138. const int n_ctx = llama_n_ctx(ctx);
  139. if (int(tokens.size()) < 2*n_ctx) {
  140. fprintf(stderr, "%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*n_ctx,
  141. n_ctx);
  142. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  143. return {std::move(tokens), 0., {}, {}};
  144. }
  145. std::vector<float> logit_history;
  146. std::vector<float> prob_history;
  147. logit_history.resize(tokens.size());
  148. prob_history.resize(tokens.size());
  149. if (params.ppl_stride <= 0) {
  150. fprintf(stderr, "%s: stride is %d but must be greater than zero!\n",__func__,params.ppl_stride);
  151. return {tokens, -1, logit_history, prob_history};
  152. }
  153. const int calc_chunk = n_ctx;
  154. fprintf(stderr, "%s: have %zu tokens. Calculation chunk = %d\n", __func__, tokens.size(), calc_chunk);
  155. if (int(tokens.size()) <= calc_chunk) {
  156. fprintf(stderr, "%s: there are only %zu tokens, this is not enough for a context size of %d and stride %d\n",__func__,
  157. tokens.size(), n_ctx, params.ppl_stride);
  158. return {tokens, -1, logit_history, prob_history};
  159. }
  160. const int n_chunk_max = (tokens.size() - calc_chunk + params.ppl_stride - 1) / params.ppl_stride;
  161. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  162. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  163. const int n_batch = params.n_batch;
  164. int count = 0;
  165. double nll = 0.0;
  166. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  167. for (int i = 0; i < n_chunk; ++i) {
  168. const int start = i * params.ppl_stride;
  169. const int end = start + calc_chunk;
  170. const int num_batches = (calc_chunk + n_batch - 1) / n_batch;
  171. //fprintf(stderr, "%s: evaluating %d...%d using %d batches\n", __func__, start, end, num_batches);
  172. std::vector<float> logits;
  173. const auto t_start = std::chrono::high_resolution_clock::now();
  174. // clear the KV cache
  175. llama_kv_cache_clear(ctx);
  176. for (int j = 0; j < num_batches; ++j) {
  177. const int batch_start = start + j * n_batch;
  178. const int batch_size = std::min(end - batch_start, n_batch);
  179. //fprintf(stderr, " Batch %d: starts at %d, size is %d, n_past is %d\n",j,batch_start,batch_size,j * n_batch);
  180. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  181. //fprintf(stderr, "%s : failed to eval\n", __func__);
  182. return {tokens, -1, logit_history, prob_history};
  183. }
  184. // save original token and restore it after eval
  185. const auto token_org = tokens[batch_start];
  186. // add BOS token for the first batch of each chunk
  187. if (add_bos && j == 0) {
  188. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  189. }
  190. const auto batch_logits = llama_get_logits(ctx);
  191. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  192. if (j == 0) {
  193. tokens[batch_start] = token_org;
  194. }
  195. }
  196. const auto t_end = std::chrono::high_resolution_clock::now();
  197. if (i == 0) {
  198. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  199. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  200. int total_seconds = (int)(t_total * n_chunk);
  201. if (total_seconds >= 60*60) {
  202. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  203. total_seconds = total_seconds % (60*60);
  204. }
  205. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  206. }
  207. //fprintf(stderr, "%s: using tokens %d...%d\n",__func__,params.n_ctx - params.ppl_stride + start, params.n_ctx + start);
  208. for (int j = n_ctx - params.ppl_stride - 1; j < n_ctx - 1; ++j) {
  209. // Calculate probability of next token, given the previous ones.
  210. const std::vector<float> tok_logits(
  211. logits.begin() + (j + 0) * n_vocab,
  212. logits.begin() + (j + 1) * n_vocab);
  213. const float prob = softmax(tok_logits)[tokens[start + j + 1]];
  214. logit_history[start + j + 1] = tok_logits[tokens[start + j + 1]];
  215. prob_history[start + j + 1] = prob;
  216. nll += -std::log(prob);
  217. ++count;
  218. }
  219. // perplexity is e^(average negative log-likelihood)
  220. if (params.ppl_output_type == 0) {
  221. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  222. } else {
  223. printf("%8d %.4lf\n", i*params.ppl_stride, std::exp(nll / count));
  224. }
  225. fflush(stdout);
  226. }
  227. printf("\n");
  228. return {tokens, std::exp(nll / count), logit_history, prob_history};
  229. }
  230. static results_perplexity perplexity(llama_context * ctx, const gpt_params & params) {
  231. if (params.ppl_stride > 0) {
  232. return perplexity_v2(ctx, params);
  233. }
  234. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  235. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  236. // Output: `perplexity: 13.5106 [114/114]`
  237. // BOS tokens will be added for each chunk before eval
  238. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  239. const int n_ctx = llama_n_ctx(ctx);
  240. auto tim1 = std::chrono::high_resolution_clock::now();
  241. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  242. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  243. auto tim2 = std::chrono::high_resolution_clock::now();
  244. fprintf(stderr, "%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  245. if (int(tokens.size()) < 2*n_ctx) {
  246. fprintf(stderr, "%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*n_ctx,
  247. n_ctx);
  248. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  249. return {std::move(tokens), 0., {}, {}};
  250. }
  251. std::vector<float> logit_history;
  252. logit_history.resize(tokens.size());
  253. std::vector<float> prob_history;
  254. prob_history.resize(tokens.size());
  255. const int n_chunk_max = tokens.size() / n_ctx;
  256. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  257. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  258. const int n_batch = params.n_batch;
  259. int count = 0;
  260. double nll = 0.0;
  261. double nll2 = 0.0;
  262. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  263. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  264. for (int i = 0; i < n_chunk; ++i) {
  265. const int start = i * n_ctx;
  266. const int end = start + n_ctx;
  267. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  268. std::vector<float> logits;
  269. const auto t_start = std::chrono::high_resolution_clock::now();
  270. // clear the KV cache
  271. llama_kv_cache_clear(ctx);
  272. for (int j = 0; j < num_batches; ++j) {
  273. const int batch_start = start + j * n_batch;
  274. const int batch_size = std::min(end - batch_start, n_batch);
  275. // save original token and restore it after eval
  276. const auto token_org = tokens[batch_start];
  277. // add BOS token for the first batch of each chunk
  278. if (add_bos && j == 0) {
  279. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  280. }
  281. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  282. fprintf(stderr, "%s : failed to eval\n", __func__);
  283. return {tokens, -1, logit_history, prob_history};
  284. }
  285. // restore the original token in case it was set to BOS
  286. tokens[batch_start] = token_org;
  287. const auto * batch_logits = llama_get_logits(ctx);
  288. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  289. }
  290. const auto t_end = std::chrono::high_resolution_clock::now();
  291. if (i == 0) {
  292. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  293. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  294. int total_seconds = (int)(t_total * n_chunk);
  295. if (total_seconds >= 60*60) {
  296. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  297. total_seconds = total_seconds % (60*60);
  298. }
  299. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  300. }
  301. // We get the logits for all the tokens in the context window (params.n_ctx)
  302. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  303. // calculate the perplexity over the last half of the window (so the model always has
  304. // some context to predict the token).
  305. //
  306. // We rely on the fact that attention in the forward pass only looks at previous
  307. // tokens here, so the logits returned for each token are an accurate representation
  308. // of what the model would have predicted at that point.
  309. //
  310. // Example, we have a context window of 512, we will compute perplexity for each of the
  311. // last 256 tokens. Then, we split the input up into context window size chunks to
  312. // process the entire prompt.
  313. const int first = n_ctx/2;
  314. process_logits(n_vocab, logits.data() + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
  315. workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
  316. count += n_ctx - first - 1;
  317. // perplexity is e^(average negative log-likelihood)
  318. if (params.ppl_output_type == 0) {
  319. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  320. } else {
  321. double av = nll/count;
  322. double av2 = nll2/count - av*av;
  323. if (av2 > 0) av2 = sqrt(av2/(count-1));
  324. printf("%8d %.4lf %4lf %4lf\n", i*n_ctx, std::exp(nll / count), av, av2);
  325. }
  326. fflush(stdout);
  327. }
  328. printf("\n");
  329. nll2 /= count;
  330. nll /= count;
  331. const double ppl = exp(nll);
  332. nll2 -= nll * nll;
  333. if (nll2 > 0) {
  334. nll2 = sqrt(nll2/(count-1));
  335. printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  336. } else {
  337. printf("Unexpected negative standard deviation of log(prob)\n");
  338. }
  339. return {tokens, ppl, logit_history, prob_history};
  340. }
  341. static std::vector<float> evaluate_tokens(llama_context * ctx, std::vector<int> & tokens,
  342. int n_past, int n_batch, int n_vocab) {
  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. llama_kv_cache_seq_rm(ctx, 0, n_past, -1);
  350. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + i_chunk * n_batch, n_tokens, n_past, 0))) {
  351. fprintf(stderr, "%s : failed to eval\n", __func__);
  352. return {};
  353. }
  354. const auto logits = llama_get_logits(ctx);
  355. result.insert(result.end(), logits, logits + n_tokens * n_vocab);
  356. n_past += n_tokens;
  357. }
  358. return result;
  359. }
  360. static void hellaswag_score(llama_context * ctx, const gpt_params & params) {
  361. // Calculates hellaswag score (acc_norm) from prompt
  362. //
  363. // Data extracted from the HellaSwag validation dataset (MIT license) https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl
  364. // All used data fields are preprocessed as in https://github.com/EleutherAI/lm-evaluation-harness/blob/df3da98c5405deafd519c2ddca52bb7c3fe36bef/lm_eval/tasks/hellaswag.py#L62-L68
  365. //
  366. // All 10042 tasks should be extracted to keep the results standardized like other implementations.
  367. //
  368. // Datafile layout:
  369. // ['??'] denotes json fields
  370. // 6 lines per task:
  371. // ['activity_label'] + ": " +['ctx'] - The first part of the query, the context
  372. // ['label'] - The index the best common sense ending aka gold ending
  373. // ['endings'][0] - Endings added to the first part of the query
  374. // ['endings'][1]
  375. // ['endings'][2]
  376. // ['endings'][3]
  377. std::vector<std::string> prompt_lines;
  378. std::istringstream strstream(params.prompt);
  379. std::string line;
  380. while (std::getline(strstream,line,'\n')) {
  381. prompt_lines.push_back(line);
  382. }
  383. if (prompt_lines.size() % 6 != 0) {
  384. fprintf(stderr, "%s : number of lines in prompt not a multiple of 6.\n", __func__);
  385. return;
  386. }
  387. size_t hs_task_count = prompt_lines.size()/6;
  388. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, hs_task_count);
  389. const bool is_spm = llama_vocab_type(llama_get_model(ctx)) == LLAMA_VOCAB_TYPE_SPM;
  390. fprintf(stderr, "================================= is_spm = %d\n", is_spm);
  391. // This is needed as usual for LLaMA models
  392. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  393. // Number of tasks to use when computing the score
  394. if (params.hellaswag_tasks < hs_task_count) {
  395. hs_task_count = params.hellaswag_tasks;
  396. }
  397. // The tasks should be randomized so the score stabilizes quickly.
  398. bool randomize_tasks = true;
  399. // The random seed should not impact the final result if the computation is done over enough tasks, so kept hardcoded for now
  400. std::mt19937 rng(1);
  401. // Dataholder for hellaswag tasks
  402. struct hs_data_t {
  403. std::string context;
  404. size_t gold_ending_idx;
  405. std::string ending[4];
  406. size_t ending_logprob_count[4];
  407. double ending_logprob[4];
  408. size_t i_batch; // starting index in the llama_batch
  409. size_t common_prefix; // max number of initial tokens that are the same in all sentences
  410. size_t required_tokens; // needed number of tokens to evaluate all 4 endings
  411. std::vector<llama_token> seq_tokens[4];
  412. };
  413. fprintf(stderr, "%s : selecting %zu %s tasks.\n", __func__, hs_task_count, (randomize_tasks?"randomized":"the first") );
  414. // Select and read data from prompt lines
  415. std::vector<hs_data_t> hs_data(hs_task_count);
  416. for (size_t i = 0; i < hs_task_count; i++) {
  417. size_t idx = i;
  418. auto & hs_cur = hs_data[i];
  419. // Select a random example of those left in the prompt
  420. if (randomize_tasks) {
  421. std::uniform_int_distribution<size_t> dist(0, prompt_lines.size()/6-1 ) ;
  422. idx = dist(rng);
  423. }
  424. hs_cur.context = prompt_lines[idx*6];
  425. hs_cur.gold_ending_idx = std::stoi( prompt_lines[idx*6+1] );
  426. for (size_t j = 0; j < 4; j++) {
  427. hs_cur.ending[j] = prompt_lines[idx*6+2+j];
  428. hs_cur.seq_tokens[j] = ::llama_tokenize(ctx, hs_cur.context + " " + hs_cur.ending[j], add_bos);
  429. }
  430. // determine the common prefix of the endings
  431. hs_cur.common_prefix = 0;
  432. hs_cur.required_tokens = 0;
  433. for (size_t k = 0; k < hs_cur.seq_tokens[0].size(); k++) {
  434. if (hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[1][k] ||
  435. hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[2][k] ||
  436. hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[3][k]) {
  437. break;
  438. }
  439. hs_cur.common_prefix++;
  440. }
  441. hs_cur.required_tokens = hs_cur.common_prefix +
  442. hs_cur.seq_tokens[0].size() - hs_cur.common_prefix +
  443. hs_cur.seq_tokens[1].size() - hs_cur.common_prefix +
  444. hs_cur.seq_tokens[2].size() - hs_cur.common_prefix +
  445. hs_cur.seq_tokens[3].size() - hs_cur.common_prefix;
  446. //GGML_ASSERT(hs_cur.common_prefix >= ::llama_tokenize(ctx, hs_cur.context, add_bos).size());
  447. // Delete the selected random example from the prompt
  448. if (randomize_tasks) {
  449. prompt_lines.erase( std::next(prompt_lines.begin(),idx*6) , std::next(prompt_lines.begin(),idx*6+6) );
  450. }
  451. }
  452. fprintf(stderr, "%s : calculating hellaswag score over selected tasks.\n", __func__);
  453. printf("\ntask\tacc_norm\n");
  454. double acc = 0.0f;
  455. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  456. const int n_ctx = llama_n_ctx(ctx);
  457. const int n_batch = params.n_batch;
  458. const int max_tasks_per_batch = params.n_parallel;
  459. const int max_seq = 4*max_tasks_per_batch;
  460. llama_batch batch = llama_batch_init(n_ctx, 0, max_seq);
  461. std::vector<float> tok_logits(n_vocab);
  462. std::vector<float> batch_logits(n_ctx*n_vocab);
  463. auto decode_helper = [&](llama_context * ctx, llama_batch & batch, int32_t n_batch) {
  464. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch) {
  465. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  466. llama_batch batch_view = {
  467. n_tokens,
  468. batch.token + i,
  469. nullptr,
  470. batch.pos + i,
  471. batch.n_seq_id + i,
  472. batch.seq_id + i,
  473. batch.logits + i,
  474. 0, 0, 0, // unused
  475. };
  476. const int ret = llama_decode(ctx, batch_view);
  477. if (ret != 0) {
  478. LOG_TEE("failed to decode the batch, n_batch = %d, ret = %d\n", n_batch, ret);
  479. return false;
  480. }
  481. memcpy(batch_logits.data() + i*n_vocab, llama_get_logits(ctx), n_tokens*n_vocab*sizeof(float));
  482. }
  483. return true;
  484. };
  485. for (size_t i0 = 0; i0 < hs_task_count; i0++) {
  486. int n_cur = 0;
  487. size_t i1 = i0;
  488. size_t i_batch = 0; // this tells us where in `llama_batch` we are currently
  489. llama_batch_clear(batch);
  490. // batch as much tasks as possible into the available context
  491. // each task has 4 unique seuqnce ids - one for each ending
  492. // the common prefix is shared among the 4 sequences to save tokens
  493. // we extract logits only from the last common token and from all ending tokens of each sequence
  494. while (n_cur + (int) hs_data[i1].required_tokens <= n_ctx) {
  495. auto & hs_cur = hs_data[i1];
  496. const int s0 = 4*(i1 - i0);
  497. if (s0 + 4 > max_seq) {
  498. break;
  499. }
  500. for (size_t i = 0; i < hs_cur.common_prefix; ++i) {
  501. llama_batch_add(batch, hs_cur.seq_tokens[0][i], i, { s0 + 0, s0 + 1, s0 + 2, s0 + 3}, false);
  502. }
  503. batch.logits[batch.n_tokens - 1] = true; // we need logits for the last token of the common prefix
  504. for (int s = 0; s < 4; ++s) {
  505. for (size_t i = hs_cur.common_prefix; i < hs_cur.seq_tokens[s].size(); ++i) {
  506. llama_batch_add(batch, hs_cur.seq_tokens[s][i], i, { s0 + s }, true);
  507. }
  508. }
  509. hs_cur.i_batch = i_batch;
  510. i_batch += hs_cur.required_tokens;
  511. n_cur += hs_data[i1].required_tokens;
  512. if (++i1 == hs_task_count) {
  513. break;
  514. }
  515. }
  516. if (i0 == i1) {
  517. fprintf(stderr, "%s : task %zu does not fit in the context window\n", __func__, i0);
  518. return;
  519. }
  520. llama_kv_cache_clear(ctx);
  521. // decode all tasks [i0, i1)
  522. if (!decode_helper(ctx, batch, n_batch)) {
  523. fprintf(stderr, "%s: llama_decode() failed\n", __func__);
  524. return;
  525. }
  526. // compute the logprobs for each ending of the decoded tasks
  527. for (size_t i = i0; i < i1; ++i) {
  528. auto & hs_cur = hs_data[i];
  529. std::memcpy(tok_logits.data(), batch_logits.data() + n_vocab*(hs_cur.i_batch + hs_cur.common_prefix - 1), n_vocab*sizeof(float));
  530. const auto first_probs = softmax(tok_logits);
  531. size_t li = hs_cur.common_prefix; // logits index in the batch
  532. for (int s = 0; s < 4; ++s) {
  533. hs_cur.ending_logprob_count[s] = 1;
  534. hs_cur.ending_logprob[s] = std::log(first_probs[hs_cur.seq_tokens[s][hs_cur.common_prefix]]);
  535. // Calculate the logprobs over the ending
  536. for (size_t j = hs_cur.common_prefix; j < hs_cur.seq_tokens[s].size() - 1; j++) {
  537. std::memcpy(tok_logits.data(), batch_logits.data() + n_vocab*(hs_cur.i_batch + li++), n_vocab*sizeof(float));
  538. const float prob = softmax(tok_logits)[hs_cur.seq_tokens[s][j + 1]];
  539. hs_cur.ending_logprob[s] += std::log(prob);
  540. hs_cur.ending_logprob_count[s]++;
  541. }
  542. // account that we skip the last token in the ending
  543. ++li;
  544. // Calculate the mean token logprob for acc_norm
  545. hs_cur.ending_logprob[s] /= hs_cur.ending_logprob_count[s];
  546. }
  547. // Find the ending with maximum logprob
  548. size_t ending_logprob_max_idx = 0;
  549. double ending_logprob_max_val = hs_cur.ending_logprob[0];
  550. for (size_t s = 1; s < 4; s++) {
  551. if (hs_cur.ending_logprob[s] > ending_logprob_max_val) {
  552. ending_logprob_max_idx = s;
  553. ending_logprob_max_val = hs_cur.ending_logprob[s];
  554. }
  555. }
  556. //printf("max logprob ending idx %lu, gold ending idx %lu\n", ending_logprob_max_idx, hs_cur.gold_ending_idx);
  557. // If the gold ending got the maximum logprobe add one accuracy point
  558. if (ending_logprob_max_idx == hs_cur.gold_ending_idx) {
  559. acc += 1.0;
  560. }
  561. // Print the accumulated accuracy mean x 100
  562. printf("%zu\t%.8lf\n", i + 1, acc/double(i + 1)*100.0);
  563. fflush(stdout);
  564. }
  565. i0 = i1 - 1;
  566. }
  567. llama_batch_free(batch);
  568. printf("\n");
  569. }
  570. struct winogrande_entry {
  571. std::string first;
  572. std::string second;
  573. std::array<std::string, 2> choices;
  574. int answer;
  575. };
  576. static std::vector<winogrande_entry> load_winogrande_from_csv(const std::string& prompt) {
  577. std::vector<winogrande_entry> result;
  578. std::istringstream in(prompt);
  579. std::string line;
  580. std::array<int, 4> comma_pos;
  581. while (true) {
  582. std::getline(in, line);
  583. if (in.fail() || in.eof()) break;
  584. int ipos = 0;
  585. bool quote_open = false;
  586. for (int i = 0; i < int(line.size()); ++i) {
  587. if (!quote_open) {
  588. if (line[i] == ',') {
  589. comma_pos[ipos++] = i;
  590. if (ipos == 4) break;
  591. }
  592. else if (line[i] == '"') {
  593. quote_open = true;
  594. }
  595. }
  596. else {
  597. if (line[i] == '"') {
  598. quote_open = false;
  599. }
  600. }
  601. }
  602. if (ipos != 4) {
  603. printf("%s: failed to find comma separators in <%s>\n", __func__, line.c_str());
  604. continue;
  605. }
  606. auto sentence = line[comma_pos[0]+1] == '"' ? line.substr(comma_pos[0]+2, comma_pos[1] - comma_pos[0] - 3)
  607. : line.substr(comma_pos[0]+1, comma_pos[1] - comma_pos[0] - 1);
  608. auto choice1 = line.substr(comma_pos[1]+1, comma_pos[2] - comma_pos[1] - 1);
  609. auto choice2 = line.substr(comma_pos[2]+1, comma_pos[3] - comma_pos[2] - 1);
  610. auto answer = line.substr(comma_pos[3]+1, line.size() - comma_pos[3] - 1);
  611. auto index = line.substr(0, comma_pos[0]);
  612. int where = 0;
  613. for ( ; where < int(sentence.size()); ++where) {
  614. if (sentence[where] == '_') break;
  615. }
  616. if (where == int(sentence.size())) {
  617. printf("%s: no _ in <%s>\n", __func__, sentence.c_str());
  618. continue;
  619. }
  620. std::istringstream stream(answer.c_str());
  621. int i_answer; stream >> i_answer;
  622. if (stream.fail() || i_answer < 1 || i_answer > 2) {
  623. printf("%s: failed to parse answer <%s>\n", __func__, answer.c_str());
  624. continue;
  625. }
  626. result.emplace_back();
  627. auto& wg = result.back();
  628. wg.first = sentence.substr(0, where);
  629. wg.second = sentence.substr(where + 1, sentence.size() - where - 1);
  630. wg.choices[0] = std::move(choice1);
  631. wg.choices[1] = std::move(choice2);
  632. wg.answer = i_answer;
  633. }
  634. return result;
  635. }
  636. /*
  637. * Evaluates the Winogrande score.
  638. * Uses a CSV containing task index, dentence, choice 1, choice 2, answer (1 or 2)
  639. * You can get one such dataset from e.g. https://huggingface.co/datasets/ikawrakow/winogrande-eval-for-llama.cpp
  640. * As an example, the 1st row in the above dataset is
  641. *
  642. * 0,Sarah was a much better surgeon than Maria so _ always got the easier cases.,Sarah,Maria,2
  643. *
  644. */
  645. static void winogrande_score(llama_context * ctx, const gpt_params & params) {
  646. constexpr int k_min_trailing_ctx = 3;
  647. auto data = load_winogrande_from_csv(params.prompt);
  648. if (data.empty()) {
  649. fprintf(stderr, "%s: no tasks\n", __func__);
  650. return;
  651. }
  652. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, data.size());
  653. if (params.winogrande_tasks > 0 && params.winogrande_tasks < data.size()) {
  654. fprintf(stderr, "%s : selecting %zu random tasks\n", __func__, params.winogrande_tasks);
  655. std::mt19937 rng(1);
  656. std::vector<int> aux(data.size());
  657. for (int i = 0; i < int(data.size()); ++i) {
  658. aux[i] = i;
  659. }
  660. float scale = 1/(1.f + (float)rng.max());
  661. std::vector<winogrande_entry> selected;
  662. selected.reserve(params.winogrande_tasks);
  663. for (int i = 0; i < int(params.winogrande_tasks); ++i) {
  664. int j = int(scale*rng()*aux.size());
  665. selected[i] = std::move(data[aux[j]]);
  666. aux[j] = aux.back();
  667. aux.pop_back();
  668. }
  669. data = std::move(selected);
  670. }
  671. // This is needed as usual for LLaMA models
  672. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  673. fprintf(stderr, "%s : calculating winogrande score over selected tasks.\n", __func__);
  674. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  675. const int n_ctx = llama_n_ctx(ctx);
  676. std::vector<float> tok_logits(n_vocab);
  677. int n_correct = 0;
  678. int n_done = 0;
  679. for (size_t task_idx = 0; task_idx < data.size(); task_idx++) {
  680. const auto& task = data[task_idx];
  681. auto base_context = ::llama_tokenize(ctx, task.first, add_bos);
  682. auto base_ctx_1st = ::llama_tokenize(ctx, task.first + task.choices[0], add_bos);
  683. auto base_ctx_2nd = ::llama_tokenize(ctx, task.first + task.choices[1], add_bos);
  684. auto sentence_1st = task.first + task.choices[0] + task.second;
  685. auto sentence_2nd = task.first + task.choices[1] + task.second;
  686. auto query_1st = ::llama_tokenize(ctx, sentence_1st, add_bos);
  687. auto query_2nd = ::llama_tokenize(ctx, sentence_2nd, add_bos);
  688. if (query_1st.size() > (size_t)n_ctx || query_2nd.size() > (size_t)n_ctx) {
  689. fprintf(stderr, "%s : number of tokens in queries %zu, %zu > n_ctxl\n", __func__, query_1st.size(), query_2nd.size());
  690. return;
  691. }
  692. auto query_1st_size = query_1st.size();
  693. auto query_2nd_size = query_2nd.size();
  694. // Speedup small evaluations by evaluating atleast 32 tokens
  695. // For Winogrande this seems to slow it down rather than speed it up.
  696. //if (query_1st.size() < 32) query_1st.resize(32);
  697. //if (query_2nd.size() < 32) query_2nd.resize(32);
  698. llama_kv_cache_clear(ctx);
  699. auto logits_1st = evaluate_tokens(ctx, query_1st, 0, params.n_batch, n_vocab);
  700. llama_kv_cache_clear(ctx);
  701. auto logits_2nd = evaluate_tokens(ctx, query_2nd, 0, params.n_batch, n_vocab);
  702. if (logits_1st.empty() || logits_2nd.empty()) {
  703. fprintf(stderr, "%s : failed to eval\n", __func__);
  704. return;
  705. }
  706. bool skip_choice = query_1st_size - base_ctx_1st.size() > k_min_trailing_ctx &&
  707. query_2nd_size - base_ctx_2nd.size() > k_min_trailing_ctx;
  708. float score_1st = 0;
  709. bool is_nan_1st = false;
  710. const auto& base_1 = skip_choice ? base_ctx_1st : base_context;
  711. const int last_1st = query_1st_size - base_1.size() > 1 ? 1 : 0;
  712. for (size_t j = base_1.size()-1; j < query_1st_size-1-last_1st; ++j) {
  713. std::memcpy(tok_logits.data(), logits_1st.data() + j*n_vocab, n_vocab*sizeof(float));
  714. const float prob = softmax(tok_logits)[query_1st[j+1]];
  715. if (std::isnan(prob) || !prob) {
  716. fprintf(stderr, "%s: %g probability for token %zu when evaluating <%s>. Base context has %zu tokens\n", __func__,
  717. prob, j, sentence_1st.c_str(), base_context.size());
  718. is_nan_1st = true;
  719. break;
  720. }
  721. score_1st += std::log(prob);
  722. }
  723. score_1st /= (query_1st_size - base_1.size() - last_1st);
  724. float score_2nd = 0;
  725. bool is_nan_2nd = false;
  726. const auto& base_2 = skip_choice ? base_ctx_2nd : base_context;
  727. const int last_2nd = query_2nd_size - base_2.size() > 1 ? 1 : 0;
  728. for (size_t j = base_2.size()-1; j < query_2nd_size-1-last_2nd; ++j) {
  729. std::memcpy(tok_logits.data(), logits_2nd.data() + j*n_vocab, n_vocab*sizeof(float));
  730. const float prob = softmax(tok_logits)[query_2nd[j+1]];
  731. if (std::isnan(prob) || !prob) {
  732. fprintf(stderr, "%s: %g probability for token %zu when evaluating <%s>. Base context has %zu tokens\n", __func__,
  733. prob, j, sentence_2nd.c_str(), base_context.size());
  734. is_nan_2nd = true;
  735. break;
  736. }
  737. score_2nd += std::log(prob);
  738. }
  739. score_2nd /= (query_2nd_size - base_2.size() - last_2nd);
  740. if (is_nan_1st || is_nan_2nd) {
  741. continue;
  742. }
  743. if (std::isnan(score_1st) || std::isnan(score_2nd)) {
  744. printf("================== NaN score %g, %g) for:\n", score_1st, score_2nd);
  745. printf("Q1: <%s> - %zu tokens\n", sentence_1st.c_str(), query_1st_size);
  746. printf("Q2: <%s> - %zu tokens\n", sentence_2nd.c_str(), query_2nd_size);
  747. printf("B : <%s> - %zu tokens\n", task.first.c_str(), base_context.size());
  748. printf("base_1 has %zu tokens, base_2 has %zu tokens, skip_choice = %d\n", base_1.size(), base_2.size(), skip_choice);
  749. continue;
  750. }
  751. int result = score_1st > score_2nd ? 1 : 2;
  752. if (result == task.answer) {
  753. ++n_correct;
  754. }
  755. ++n_done;
  756. // Print the accumulated accuracy mean x 100
  757. printf("%zu\t%.4lf\t%10.6f %10.6f %d %d\n",task_idx+1, 100.0 * n_correct/n_done,score_1st,score_2nd,result,task.answer);
  758. fflush(stdout);
  759. }
  760. printf("\n");
  761. if (n_done < 100) return;
  762. const float p = 1.f*n_correct/n_done;
  763. const float sigma = 100.f*sqrt(p*(1-p)/(n_done-1));
  764. printf("Final Winogrande score(%d tasks): %.4lf +/- %.4lf\n", n_done, 100*p, sigma);
  765. }
  766. int main(int argc, char ** argv) {
  767. gpt_params params;
  768. params.n_batch = 512;
  769. if (!gpt_params_parse(argc, argv, params)) {
  770. return 1;
  771. }
  772. params.logits_all = true;
  773. params.n_batch = std::min(params.n_batch, params.n_ctx);
  774. if (params.ppl_stride > 0) {
  775. fprintf(stderr, "Will perform strided perplexity calculation -> adjusting context size from %d to %d\n",
  776. params.n_ctx, params.n_ctx + params.ppl_stride/2);
  777. params.n_ctx += params.ppl_stride/2;
  778. }
  779. print_build_info();
  780. if (params.seed == LLAMA_DEFAULT_SEED) {
  781. params.seed = time(NULL);
  782. }
  783. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  784. std::mt19937 rng(params.seed);
  785. if (params.random_prompt) {
  786. params.prompt = gpt_random_prompt(rng);
  787. }
  788. llama_backend_init(params.numa);
  789. llama_model * model;
  790. llama_context * ctx;
  791. // load the model and apply lora adapter, if any
  792. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  793. if (model == NULL) {
  794. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  795. return 1;
  796. }
  797. const int n_ctx_train = llama_n_ctx_train(model);
  798. if (params.n_ctx > n_ctx_train) {
  799. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  800. __func__, n_ctx_train, params.n_ctx);
  801. }
  802. // print system information
  803. {
  804. fprintf(stderr, "\n");
  805. fprintf(stderr, "%s\n", get_system_info(params).c_str());
  806. }
  807. struct results_perplexity results;
  808. if (params.hellaswag) {
  809. hellaswag_score(ctx, params);
  810. } else if (params.winogrande) {
  811. winogrande_score(ctx, params);
  812. } else {
  813. results = perplexity(ctx, params);
  814. }
  815. llama_print_timings(ctx);
  816. write_logfile(ctx, params, model, results);
  817. llama_free(ctx);
  818. llama_free_model(model);
  819. llama_backend_free();
  820. return 0;
  821. }