perplexity.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492
  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 <atomic>
  11. #include <vector>
  12. #include <array>
  13. #include <fstream>
  14. #include <sstream>
  15. #if defined(_MSC_VER)
  16. #pragma warning(disable: 4244 4267) // possible loss of data
  17. #endif
  18. struct results_perplexity {
  19. std::vector<llama_token> tokens;
  20. double ppl_value;
  21. std::vector<float> logits;
  22. std::vector<float> probs;
  23. };
  24. struct results_log_softmax {
  25. double log_softmax;
  26. float logit;
  27. float prob;
  28. };
  29. static void write_logfile(
  30. const llama_context * ctx, const gpt_params & params, const llama_model * model,
  31. const struct results_perplexity & results
  32. ) {
  33. if (params.logdir.empty()) {
  34. return;
  35. }
  36. if (params.hellaswag) {
  37. fprintf(stderr, "%s: warning: logging results is not implemented for HellaSwag. No files will be written.\n", __func__);
  38. return;
  39. }
  40. const std::string timestamp = get_sortable_timestamp();
  41. const bool success = create_directory_with_parents(params.logdir);
  42. if (!success) {
  43. fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n",
  44. __func__, params.logdir.c_str());
  45. return;
  46. }
  47. const std::string logfile_path = params.logdir + timestamp + ".yml";
  48. FILE * logfile = fopen(logfile_path.c_str(), "w");
  49. if (logfile == NULL) {
  50. fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
  51. return;
  52. }
  53. fprintf(logfile, "binary: main\n");
  54. char model_desc[128];
  55. llama_model_desc(model, model_desc, sizeof(model_desc));
  56. dump_non_result_info_yaml(logfile, params, ctx, timestamp, results.tokens, model_desc);
  57. fprintf(logfile, "\n");
  58. fprintf(logfile, "######################\n");
  59. fprintf(logfile, "# Perplexity Results #\n");
  60. fprintf(logfile, "######################\n");
  61. fprintf(logfile, "\n");
  62. dump_vector_float_yaml(logfile, "logits", results.logits);
  63. fprintf(logfile, "ppl_value: %f\n", results.ppl_value);
  64. dump_vector_float_yaml(logfile, "probs", results.probs);
  65. llama_dump_timing_info_yaml(logfile, ctx);
  66. fclose(logfile);
  67. }
  68. static std::vector<float> softmax(const std::vector<float>& logits) {
  69. std::vector<float> probs(logits.size());
  70. float max_logit = logits[0];
  71. for (float v : logits) {
  72. max_logit = std::max(max_logit, v);
  73. }
  74. double sum_exp = 0.0;
  75. for (size_t i = 0; i < logits.size(); i++) {
  76. // Subtract the maximum logit value from the current logit value for numerical stability
  77. const float logit = logits[i] - max_logit;
  78. const float exp_logit = expf(logit);
  79. sum_exp += exp_logit;
  80. probs[i] = exp_logit;
  81. }
  82. for (size_t i = 0; i < probs.size(); i++) {
  83. probs[i] /= sum_exp;
  84. }
  85. return probs;
  86. }
  87. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  88. float max_logit = logits[0];
  89. for (int i = 1; i < n_vocab; ++i) {
  90. max_logit = std::max(max_logit, logits[i]);
  91. }
  92. double sum_exp = 0.0;
  93. for (int i = 0; i < n_vocab; ++i) {
  94. sum_exp += expf(logits[i] - max_logit);
  95. }
  96. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  97. }
  98. static void process_logits(
  99. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  100. double & nll, double & nll2, float * logit_history, float * prob_history
  101. ) {
  102. std::mutex mutex;
  103. int counter = 0;
  104. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  105. double local_nll = 0;
  106. double local_nll2 = 0;
  107. while (true) {
  108. std::unique_lock<std::mutex> lock(mutex);
  109. int i = counter++;
  110. if (i >= n_token) {
  111. nll += local_nll; nll2 += local_nll2;
  112. break;
  113. }
  114. lock.unlock();
  115. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  116. const double v = -results.log_softmax;
  117. local_nll += v;
  118. local_nll2 += v*v;
  119. logit_history[i] = results.logit;
  120. prob_history[i] = results.prob;
  121. }
  122. };
  123. for (auto & w : workers) {
  124. w = std::thread(compute);
  125. }
  126. compute();
  127. for (auto & w : workers) {
  128. w.join();
  129. }
  130. }
  131. static results_perplexity perplexity_v2(llama_context * ctx, const gpt_params & params) {
  132. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  133. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  134. // Output: `perplexity: 13.5106 [114/114]`
  135. // BOS tokens will be added for each chunk before eval
  136. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  137. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  138. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  139. const int n_ctx = llama_n_ctx(ctx);
  140. if (int(tokens.size()) < 2*n_ctx) {
  141. fprintf(stderr, "%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*n_ctx,
  142. n_ctx);
  143. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  144. return {std::move(tokens), 0., {}, {}};
  145. }
  146. std::vector<float> logit_history;
  147. std::vector<float> prob_history;
  148. logit_history.resize(tokens.size());
  149. prob_history.resize(tokens.size());
  150. if (params.ppl_stride <= 0) {
  151. fprintf(stderr, "%s: stride is %d but must be greater than zero!\n",__func__,params.ppl_stride);
  152. return {tokens, -1, logit_history, prob_history};
  153. }
  154. const int calc_chunk = n_ctx;
  155. fprintf(stderr, "%s: have %zu tokens. Calculation chunk = %d\n", __func__, tokens.size(), calc_chunk);
  156. if (int(tokens.size()) <= calc_chunk) {
  157. fprintf(stderr, "%s: there are only %zu tokens, this is not enough for a context size of %d and stride %d\n",__func__,
  158. tokens.size(), n_ctx, params.ppl_stride);
  159. return {tokens, -1, logit_history, prob_history};
  160. }
  161. const int n_chunk_max = (tokens.size() - calc_chunk + params.ppl_stride - 1) / params.ppl_stride;
  162. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  163. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  164. const int n_batch = params.n_batch;
  165. int count = 0;
  166. double nll = 0.0;
  167. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  168. for (int i = 0; i < n_chunk; ++i) {
  169. const int start = i * params.ppl_stride;
  170. const int end = start + calc_chunk;
  171. const int num_batches = (calc_chunk + n_batch - 1) / n_batch;
  172. //fprintf(stderr, "%s: evaluating %d...%d using %d batches\n", __func__, start, end, num_batches);
  173. std::vector<float> logits;
  174. const auto t_start = std::chrono::high_resolution_clock::now();
  175. // clear the KV cache
  176. llama_kv_cache_clear(ctx);
  177. for (int j = 0; j < num_batches; ++j) {
  178. const int batch_start = start + j * n_batch;
  179. const int batch_size = std::min(end - batch_start, n_batch);
  180. //fprintf(stderr, " Batch %d: starts at %d, size is %d, n_past is %d\n",j,batch_start,batch_size,j * n_batch);
  181. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  182. //fprintf(stderr, "%s : failed to eval\n", __func__);
  183. return {tokens, -1, logit_history, prob_history};
  184. }
  185. // save original token and restore it after eval
  186. const auto token_org = tokens[batch_start];
  187. // add BOS token for the first batch of each chunk
  188. if (add_bos && j == 0) {
  189. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  190. }
  191. const auto batch_logits = llama_get_logits(ctx);
  192. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  193. if (j == 0) {
  194. tokens[batch_start] = token_org;
  195. }
  196. }
  197. const auto t_end = std::chrono::high_resolution_clock::now();
  198. if (i == 0) {
  199. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  200. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  201. int total_seconds = (int)(t_total * n_chunk);
  202. if (total_seconds >= 60*60) {
  203. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  204. total_seconds = total_seconds % (60*60);
  205. }
  206. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  207. }
  208. //fprintf(stderr, "%s: using tokens %d...%d\n",__func__,params.n_ctx - params.ppl_stride + start, params.n_ctx + start);
  209. for (int j = n_ctx - params.ppl_stride - 1; j < n_ctx - 1; ++j) {
  210. // Calculate probability of next token, given the previous ones.
  211. const std::vector<float> tok_logits(
  212. logits.begin() + (j + 0) * n_vocab,
  213. logits.begin() + (j + 1) * n_vocab);
  214. const float prob = softmax(tok_logits)[tokens[start + j + 1]];
  215. logit_history[start + j + 1] = tok_logits[tokens[start + j + 1]];
  216. prob_history[start + j + 1] = prob;
  217. nll += -std::log(prob);
  218. ++count;
  219. }
  220. // perplexity is e^(average negative log-likelihood)
  221. if (params.ppl_output_type == 0) {
  222. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  223. } else {
  224. printf("%8d %.4lf\n", i*params.ppl_stride, std::exp(nll / count));
  225. }
  226. fflush(stdout);
  227. }
  228. printf("\n");
  229. return {tokens, std::exp(nll / count), logit_history, prob_history};
  230. }
  231. static results_perplexity perplexity(llama_context * ctx, const gpt_params & params) {
  232. if (params.ppl_stride > 0) {
  233. return perplexity_v2(ctx, params);
  234. }
  235. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  236. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  237. // Output: `perplexity: 13.5106 [114/114]`
  238. // BOS tokens will be added for each chunk before eval
  239. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  240. const int n_ctx = llama_n_ctx(ctx);
  241. auto tim1 = std::chrono::high_resolution_clock::now();
  242. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  243. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  244. auto tim2 = std::chrono::high_resolution_clock::now();
  245. fprintf(stderr, "%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  246. if (int(tokens.size()) < 2*n_ctx) {
  247. fprintf(stderr, "%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*n_ctx,
  248. n_ctx);
  249. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  250. return {std::move(tokens), 0., {}, {}};
  251. }
  252. std::vector<float> logit_history;
  253. logit_history.resize(tokens.size());
  254. std::vector<float> prob_history;
  255. prob_history.resize(tokens.size());
  256. const int n_chunk_max = tokens.size() / n_ctx;
  257. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  258. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  259. const int n_batch = params.n_batch;
  260. int count = 0;
  261. double nll = 0.0;
  262. double nll2 = 0.0;
  263. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  264. std::vector<float> logits;
  265. if (num_batches > 1) {
  266. logits.reserve((size_t)n_ctx * n_vocab);
  267. }
  268. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  269. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  270. for (int i = 0; i < n_chunk; ++i) {
  271. const int start = i * n_ctx;
  272. const int end = start + n_ctx;
  273. const auto t_start = std::chrono::high_resolution_clock::now();
  274. // clear the KV cache
  275. llama_kv_cache_clear(ctx);
  276. for (int j = 0; j < num_batches; ++j) {
  277. const int batch_start = start + j * n_batch;
  278. const int batch_size = std::min(end - batch_start, n_batch);
  279. // save original token and restore it after eval
  280. const auto token_org = tokens[batch_start];
  281. // add BOS token for the first batch of each chunk
  282. if (add_bos && j == 0) {
  283. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  284. }
  285. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  286. fprintf(stderr, "%s : failed to eval\n", __func__);
  287. return {tokens, -1, logit_history, prob_history};
  288. }
  289. // restore the original token in case it was set to BOS
  290. tokens[batch_start] = token_org;
  291. if (num_batches > 1) {
  292. const auto * batch_logits = llama_get_logits(ctx);
  293. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  294. }
  295. }
  296. const auto t_end = std::chrono::high_resolution_clock::now();
  297. if (i == 0) {
  298. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  299. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  300. int total_seconds = (int)(t_total * n_chunk);
  301. if (total_seconds >= 60*60) {
  302. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  303. total_seconds = total_seconds % (60*60);
  304. }
  305. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  306. }
  307. // We get the logits for all the tokens in the context window (params.n_ctx)
  308. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  309. // calculate the perplexity over the last half of the window (so the model always has
  310. // some context to predict the token).
  311. //
  312. // We rely on the fact that attention in the forward pass only looks at previous
  313. // tokens here, so the logits returned for each token are an accurate representation
  314. // of what the model would have predicted at that point.
  315. //
  316. // Example, we have a context window of 512, we will compute perplexity for each of the
  317. // last 256 tokens. Then, we split the input up into context window size chunks to
  318. // process the entire prompt.
  319. const int first = n_ctx/2;
  320. const float * all_logits = num_batches > 1 ? logits.data() : llama_get_logits(ctx);
  321. process_logits(n_vocab, all_logits + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
  322. workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
  323. count += n_ctx - first - 1;
  324. // perplexity is e^(average negative log-likelihood)
  325. if (params.ppl_output_type == 0) {
  326. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  327. } else {
  328. double av = nll/count;
  329. double av2 = nll2/count - av*av;
  330. if (av2 > 0) av2 = sqrt(av2/(count-1));
  331. printf("%8d %.4lf %4lf %4lf\n", i*n_ctx, std::exp(nll / count), av, av2);
  332. }
  333. fflush(stdout);
  334. logits.clear();
  335. }
  336. printf("\n");
  337. nll2 /= count;
  338. nll /= count;
  339. const double ppl = exp(nll);
  340. nll2 -= nll * nll;
  341. if (nll2 > 0) {
  342. nll2 = sqrt(nll2/(count-1));
  343. printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  344. } else {
  345. printf("Unexpected negative standard deviation of log(prob)\n");
  346. }
  347. return {tokens, ppl, logit_history, prob_history};
  348. }
  349. static bool decode_helper(llama_context * ctx, llama_batch & batch, std::vector<float> & batch_logits, int32_t n_batch, int32_t n_vocab) {
  350. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch) {
  351. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  352. llama_batch batch_view = {
  353. n_tokens,
  354. batch.token + i,
  355. nullptr,
  356. batch.pos + i,
  357. batch.n_seq_id + i,
  358. batch.seq_id + i,
  359. batch.logits + i,
  360. 0, 0, 0, // unused
  361. };
  362. const int ret = llama_decode(ctx, batch_view);
  363. if (ret != 0) {
  364. LOG_TEE("failed to decode the batch, n_batch = %d, ret = %d\n", n_batch, ret);
  365. return false;
  366. }
  367. memcpy(batch_logits.data() + i*n_vocab, llama_get_logits(ctx), n_tokens*n_vocab*sizeof(float));
  368. }
  369. return true;
  370. }
  371. #define K_TOKEN_CHUNK 4
  372. static void compute_logprobs(const float * batch_logits, int n_vocab, std::vector<std::thread>& workers,
  373. const std::vector<std::pair<size_t, llama_token>>& eval_pairs, std::vector<float>& eval_results) {
  374. if (eval_results.size() != eval_pairs.size()) {
  375. eval_results.resize(eval_pairs.size());
  376. }
  377. if (eval_pairs.empty()) return;
  378. size_t max_threads = std::min((eval_pairs.size() + K_TOKEN_CHUNK - 1)/K_TOKEN_CHUNK, workers.size());
  379. std::atomic<int> counter(0);
  380. auto compute = [&counter, &eval_pairs, &eval_results, batch_logits, n_vocab] () {
  381. float local_logprobs[K_TOKEN_CHUNK];
  382. while (true) {
  383. size_t first = counter.fetch_add(K_TOKEN_CHUNK, std::memory_order_relaxed);
  384. if (first >= eval_results.size()) break;
  385. size_t last = std::min(first + K_TOKEN_CHUNK, eval_results.size());
  386. for (size_t i = first; i < last; ++i) {
  387. auto logits = batch_logits + eval_pairs[i].first * n_vocab;
  388. float max_logit = logits[0];
  389. for (int j = 1; j < n_vocab; ++j) {
  390. max_logit = std::max(max_logit, logits[j]);
  391. }
  392. float sum_p = 0.f;
  393. for (int j = 0; j < n_vocab; ++j) {
  394. sum_p += expf(logits[j] - max_logit);
  395. }
  396. local_logprobs[i - first] = logits[eval_pairs[i].second] - max_logit - std::log(sum_p);
  397. }
  398. std::memcpy(eval_results.data() + first, local_logprobs, (last - first)*sizeof(float));
  399. }
  400. };
  401. for (size_t it = 0; it < max_threads; ++it) {
  402. workers[it] = std::thread(compute);
  403. }
  404. for (size_t it = 0; it < max_threads; ++it) {
  405. workers[it].join();
  406. }
  407. }
  408. static void hellaswag_score(llama_context * ctx, const gpt_params & params) {
  409. // Calculates hellaswag score (acc_norm) from prompt
  410. //
  411. // Data extracted from the HellaSwag validation dataset (MIT license) https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl
  412. // All used data fields are preprocessed as in https://github.com/EleutherAI/lm-evaluation-harness/blob/df3da98c5405deafd519c2ddca52bb7c3fe36bef/lm_eval/tasks/hellaswag.py#L62-L68
  413. //
  414. // All 10042 tasks should be extracted to keep the results standardized like other implementations.
  415. //
  416. // Datafile layout:
  417. // ['??'] denotes json fields
  418. // 6 lines per task:
  419. // ['activity_label'] + ": " +['ctx'] - The first part of the query, the context
  420. // ['label'] - The index the best common sense ending aka gold ending
  421. // ['endings'][0] - Endings added to the first part of the query
  422. // ['endings'][1]
  423. // ['endings'][2]
  424. // ['endings'][3]
  425. std::vector<std::string> prompt_lines;
  426. std::istringstream strstream(params.prompt);
  427. std::string line;
  428. while (std::getline(strstream,line,'\n')) {
  429. prompt_lines.push_back(line);
  430. }
  431. if (prompt_lines.size() % 6 != 0) {
  432. fprintf(stderr, "%s : number of lines in prompt not a multiple of 6.\n", __func__);
  433. return;
  434. }
  435. size_t hs_task_count = prompt_lines.size()/6;
  436. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, hs_task_count);
  437. const bool is_spm = llama_vocab_type(llama_get_model(ctx)) == LLAMA_VOCAB_TYPE_SPM;
  438. fprintf(stderr, "================================= is_spm = %d\n", is_spm);
  439. // This is needed as usual for LLaMA models
  440. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  441. // The tasks should be randomized so the score stabilizes quickly.
  442. bool randomize_tasks = true;
  443. // Number of tasks to use when computing the score
  444. if (params.hellaswag_tasks < hs_task_count) {
  445. hs_task_count = params.hellaswag_tasks;
  446. }
  447. // The random seed should not impact the final result if the computation is done over enough tasks, so kept hardcoded for now
  448. std::mt19937 rng(1);
  449. // Dataholder for hellaswag tasks
  450. struct hs_data_t {
  451. std::string context;
  452. size_t gold_ending_idx;
  453. std::string ending[4];
  454. size_t ending_logprob_count[4];
  455. double ending_logprob[4];
  456. size_t i_batch; // starting index in the llama_batch
  457. size_t common_prefix; // max number of initial tokens that are the same in all sentences
  458. size_t required_tokens; // needed number of tokens to evaluate all 4 endings
  459. std::vector<llama_token> seq_tokens[4];
  460. };
  461. fprintf(stderr, "%s : selecting %zu %s tasks.\n", __func__, hs_task_count, (randomize_tasks?"randomized":"the first") );
  462. // Select and read data from prompt lines
  463. std::vector<hs_data_t> hs_data(hs_task_count);
  464. for (size_t i = 0; i < hs_task_count; i++) {
  465. size_t idx = i;
  466. auto & hs_cur = hs_data[i];
  467. // Select a random example of those left in the prompt
  468. if (randomize_tasks) {
  469. std::uniform_int_distribution<size_t> dist(0, prompt_lines.size()/6-1 ) ;
  470. idx = dist(rng);
  471. }
  472. hs_cur.context = prompt_lines[idx*6];
  473. hs_cur.gold_ending_idx = std::stoi( prompt_lines[idx*6+1] );
  474. for (size_t j = 0; j < 4; j++) {
  475. hs_cur.ending[j] = prompt_lines[idx*6+2+j];
  476. hs_cur.seq_tokens[j] = ::llama_tokenize(ctx, hs_cur.context + " " + hs_cur.ending[j], add_bos);
  477. }
  478. // determine the common prefix of the endings
  479. hs_cur.common_prefix = 0;
  480. for (size_t k = 0; k < hs_cur.seq_tokens[0].size(); k++) {
  481. if (hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[1][k] ||
  482. hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[2][k] ||
  483. hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[3][k]) {
  484. break;
  485. }
  486. hs_cur.common_prefix++;
  487. }
  488. hs_cur.required_tokens = hs_cur.common_prefix +
  489. hs_cur.seq_tokens[0].size() - hs_cur.common_prefix +
  490. hs_cur.seq_tokens[1].size() - hs_cur.common_prefix +
  491. hs_cur.seq_tokens[2].size() - hs_cur.common_prefix +
  492. hs_cur.seq_tokens[3].size() - hs_cur.common_prefix;
  493. //GGML_ASSERT(hs_cur.common_prefix >= ::llama_tokenize(ctx, hs_cur.context, add_bos).size());
  494. // Delete the selected random example from the prompt
  495. if (randomize_tasks) {
  496. prompt_lines.erase( std::next(prompt_lines.begin(),idx*6) , std::next(prompt_lines.begin(),idx*6+6) );
  497. }
  498. }
  499. fprintf(stderr, "%s : calculating hellaswag score over selected tasks.\n", __func__);
  500. printf("\ntask\tacc_norm\n");
  501. double acc = 0.0f;
  502. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  503. const int n_ctx = llama_n_ctx(ctx);
  504. const int n_batch = params.n_batch;
  505. const int max_tasks_per_batch = 32;
  506. const int max_seq = 4*max_tasks_per_batch;
  507. llama_batch batch = llama_batch_init(n_ctx, 0, max_seq);
  508. std::vector<float> tok_logits(n_vocab);
  509. std::vector<float> batch_logits(n_vocab*n_ctx);
  510. std::vector<std::pair<size_t, llama_token>> eval_pairs;
  511. std::vector<float> eval_results;
  512. std::vector<std::thread> workers(std::thread::hardware_concurrency());
  513. for (size_t i0 = 0; i0 < hs_task_count; i0++) {
  514. int n_cur = 0;
  515. size_t i1 = i0;
  516. size_t i_batch = 0; // this tells us where in `llama_batch` we are currently
  517. llama_batch_clear(batch);
  518. // batch as much tasks as possible into the available context
  519. // each task has 4 unique seuqnce ids - one for each ending
  520. // the common prefix is shared among the 4 sequences to save tokens
  521. // we extract logits only from the last common token and from all ending tokens of each sequence
  522. while (n_cur + (int) hs_data[i1].required_tokens <= n_ctx) {
  523. auto & hs_cur = hs_data[i1];
  524. const int s0 = 4*(i1 - i0);
  525. if (s0 + 4 > max_seq) {
  526. break;
  527. }
  528. for (size_t i = 0; i < hs_cur.common_prefix; ++i) {
  529. llama_batch_add(batch, hs_cur.seq_tokens[0][i], i, { s0 + 0, s0 + 1, s0 + 2, s0 + 3}, false);
  530. }
  531. batch.logits[batch.n_tokens - 1] = true; // we need logits for the last token of the common prefix
  532. for (int s = 0; s < 4; ++s) {
  533. for (size_t i = hs_cur.common_prefix; i < hs_cur.seq_tokens[s].size(); ++i) {
  534. llama_batch_add(batch, hs_cur.seq_tokens[s][i], i, { s0 + s }, true);
  535. }
  536. }
  537. hs_cur.i_batch = i_batch;
  538. i_batch += hs_cur.required_tokens;
  539. n_cur += hs_data[i1].required_tokens;
  540. if (++i1 == hs_task_count) {
  541. break;
  542. }
  543. }
  544. if (i0 == i1) {
  545. fprintf(stderr, "%s : task %zu does not fit in the context window\n", __func__, i0);
  546. return;
  547. }
  548. llama_kv_cache_clear(ctx);
  549. // decode all tasks [i0, i1)
  550. if (!decode_helper(ctx, batch, batch_logits, n_batch, n_vocab)) {
  551. fprintf(stderr, "%s: llama_decode() failed\n", __func__);
  552. return;
  553. }
  554. // Compute log-probs in parallel
  555. // First we collect all tasks
  556. eval_pairs.clear();
  557. for (size_t i = i0; i < i1; ++i) {
  558. auto & hs_cur = hs_data[i];
  559. size_t li = hs_cur.common_prefix;
  560. for (int s = 0; s < 4; ++s) {
  561. for (size_t j = hs_cur.common_prefix; j < hs_cur.seq_tokens[s].size() - 1; j++) {
  562. eval_pairs.push_back(std::make_pair(hs_cur.i_batch + li++, hs_cur.seq_tokens[s][j + 1]));
  563. }
  564. ++li;
  565. }
  566. }
  567. // Then we do the actual calculation
  568. compute_logprobs(batch_logits.data(), n_vocab, workers, eval_pairs, eval_results);
  569. size_t ir = 0;
  570. // compute the logprobs for each ending of the decoded tasks
  571. for (size_t i = i0; i < i1; ++i) {
  572. auto & hs_cur = hs_data[i];
  573. std::memcpy(tok_logits.data(), batch_logits.data() + n_vocab*(hs_cur.i_batch + hs_cur.common_prefix - 1), n_vocab*sizeof(float));
  574. const auto first_probs = softmax(tok_logits);
  575. for (int s = 0; s < 4; ++s) {
  576. hs_cur.ending_logprob_count[s] = 1;
  577. hs_cur.ending_logprob[s] = std::log(first_probs[hs_cur.seq_tokens[s][hs_cur.common_prefix]]);
  578. for (size_t j = hs_cur.common_prefix; j < hs_cur.seq_tokens[s].size() - 1; j++) {
  579. hs_cur.ending_logprob[s] += eval_results[ir++];
  580. hs_cur.ending_logprob_count[s]++;
  581. }
  582. hs_cur.ending_logprob[s] /= hs_cur.ending_logprob_count[s];
  583. }
  584. // Find the ending with maximum logprob
  585. size_t ending_logprob_max_idx = 0;
  586. double ending_logprob_max_val = hs_cur.ending_logprob[0];
  587. for (size_t s = 1; s < 4; s++) {
  588. if (hs_cur.ending_logprob[s] > ending_logprob_max_val) {
  589. ending_logprob_max_idx = s;
  590. ending_logprob_max_val = hs_cur.ending_logprob[s];
  591. }
  592. }
  593. //printf("max logprob ending idx %lu, gold ending idx %lu\n", ending_logprob_max_idx, hs_cur.gold_ending_idx);
  594. // If the gold ending got the maximum logprobe add one accuracy point
  595. if (ending_logprob_max_idx == hs_cur.gold_ending_idx) {
  596. acc += 1.0;
  597. }
  598. // Print the accumulated accuracy mean x 100
  599. printf("%zu\t%.8lf\n", i + 1, acc/double(i + 1)*100.0);
  600. fflush(stdout);
  601. }
  602. i0 = i1 - 1;
  603. }
  604. llama_batch_free(batch);
  605. printf("\n");
  606. }
  607. struct winogrande_entry {
  608. std::string first;
  609. std::string second;
  610. std::array<std::string, 2> choices;
  611. int answer;
  612. size_t i_batch;
  613. size_t common_prefix;
  614. size_t required_tokens;
  615. size_t n_base1; // number of tokens for context + choice 1
  616. size_t n_base2; // number of tokens for context + choice 2
  617. std::vector<llama_token> seq_tokens[2];
  618. };
  619. static std::vector<winogrande_entry> load_winogrande_from_csv(const std::string& prompt) {
  620. std::vector<winogrande_entry> result;
  621. std::istringstream in(prompt);
  622. std::string line;
  623. std::array<int, 4> comma_pos;
  624. while (true) {
  625. std::getline(in, line);
  626. if (in.fail() || in.eof()) break;
  627. int ipos = 0;
  628. bool quote_open = false;
  629. for (int i = 0; i < int(line.size()); ++i) {
  630. if (!quote_open) {
  631. if (line[i] == ',') {
  632. comma_pos[ipos++] = i;
  633. if (ipos == 4) break;
  634. }
  635. else if (line[i] == '"') {
  636. quote_open = true;
  637. }
  638. }
  639. else {
  640. if (line[i] == '"') {
  641. quote_open = false;
  642. }
  643. }
  644. }
  645. if (ipos != 4) {
  646. printf("%s: failed to find comma separators in <%s>\n", __func__, line.c_str());
  647. continue;
  648. }
  649. auto sentence = line[comma_pos[0]+1] == '"' ? line.substr(comma_pos[0]+2, comma_pos[1] - comma_pos[0] - 3)
  650. : line.substr(comma_pos[0]+1, comma_pos[1] - comma_pos[0] - 1);
  651. auto choice1 = line.substr(comma_pos[1]+1, comma_pos[2] - comma_pos[1] - 1);
  652. auto choice2 = line.substr(comma_pos[2]+1, comma_pos[3] - comma_pos[2] - 1);
  653. auto answer = line.substr(comma_pos[3]+1, line.size() - comma_pos[3] - 1);
  654. auto index = line.substr(0, comma_pos[0]);
  655. int where = 0;
  656. for ( ; where < int(sentence.size()); ++where) {
  657. if (sentence[where] == '_') break;
  658. }
  659. if (where == int(sentence.size())) {
  660. printf("%s: no _ in <%s>\n", __func__, sentence.c_str());
  661. continue;
  662. }
  663. std::istringstream stream(answer.c_str());
  664. int i_answer; stream >> i_answer;
  665. if (stream.fail() || i_answer < 1 || i_answer > 2) {
  666. printf("%s: failed to parse answer <%s>\n", __func__, answer.c_str());
  667. continue;
  668. }
  669. result.emplace_back();
  670. auto& wg = result.back();
  671. wg.first = sentence.substr(0, where);
  672. wg.second = sentence.substr(where + 1, sentence.size() - where - 1);
  673. wg.choices[0] = std::move(choice1);
  674. wg.choices[1] = std::move(choice2);
  675. wg.answer = i_answer;
  676. }
  677. return result;
  678. }
  679. /*
  680. * Evaluates the Winogrande score.
  681. * Uses a CSV containing task index, dentence, choice 1, choice 2, answer (1 or 2)
  682. * You can get one such dataset from e.g. https://huggingface.co/datasets/ikawrakow/winogrande-eval-for-llama.cpp
  683. * As an example, the 1st row in the above dataset is
  684. *
  685. * 0,Sarah was a much better surgeon than Maria so _ always got the easier cases.,Sarah,Maria,2
  686. *
  687. */
  688. static void winogrande_score(llama_context * ctx, const gpt_params & params) {
  689. constexpr int k_min_trailing_ctx = 3;
  690. auto data = load_winogrande_from_csv(params.prompt);
  691. if (data.empty()) {
  692. fprintf(stderr, "%s: no tasks\n", __func__);
  693. return;
  694. }
  695. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, data.size());
  696. if (params.winogrande_tasks > 0 && params.winogrande_tasks < data.size()) {
  697. fprintf(stderr, "%s : selecting %zu random tasks\n", __func__, params.winogrande_tasks);
  698. std::mt19937 rng(1);
  699. std::vector<int> aux(data.size());
  700. for (int i = 0; i < int(data.size()); ++i) {
  701. aux[i] = i;
  702. }
  703. float scale = 1/(1.f + (float)rng.max());
  704. std::vector<winogrande_entry> selected;
  705. selected.resize(params.winogrande_tasks);
  706. for (int i = 0; i < int(params.winogrande_tasks); ++i) {
  707. int j = int(scale*rng()*aux.size());
  708. selected[i] = std::move(data[aux[j]]);
  709. aux[j] = aux.back();
  710. aux.pop_back();
  711. }
  712. data = std::move(selected);
  713. }
  714. fprintf(stderr, "%s : tokenizing selected tasks\n", __func__);
  715. // This is needed as usual for LLaMA models
  716. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  717. for (auto & task : data) {
  718. task.seq_tokens[0] = ::llama_tokenize(ctx, task.first + task.choices[0] + task.second, add_bos);
  719. task.seq_tokens[1] = ::llama_tokenize(ctx, task.first + task.choices[1] + task.second, add_bos);
  720. task.common_prefix = 0;
  721. for (size_t k = 0; k < task.seq_tokens[0].size(); k++) {
  722. if (task.seq_tokens[0][k] != task.seq_tokens[1][k]) {
  723. break;
  724. }
  725. task.common_prefix++;
  726. }
  727. task.required_tokens = task.common_prefix +
  728. task.seq_tokens[0].size() - task.common_prefix +
  729. task.seq_tokens[1].size() - task.common_prefix;
  730. task.n_base1 = ::llama_tokenize(ctx, task.first + task.choices[0], add_bos).size();
  731. task.n_base2 = ::llama_tokenize(ctx, task.first + task.choices[1], add_bos).size();
  732. }
  733. fprintf(stderr, "%s : calculating winogrande score over selected tasks.\n", __func__);
  734. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  735. const int n_ctx = llama_n_ctx(ctx);
  736. const int n_batch = params.n_batch;
  737. const int max_tasks_per_batch = 128;
  738. const int max_seq = 2*max_tasks_per_batch;
  739. llama_batch batch = llama_batch_init(n_ctx, 0, max_seq);
  740. std::vector<float> tok_logits(n_vocab);
  741. std::vector<float> batch_logits(n_vocab*n_ctx);
  742. std::vector<std::pair<size_t, llama_token>> eval_pairs;
  743. std::vector<float> eval_results;
  744. std::vector<std::thread> workers(std::thread::hardware_concurrency());
  745. int n_correct = 0;
  746. int n_done = 0;
  747. for (size_t i0 = 0; i0 < data.size(); i0++) {
  748. int n_cur = 0;
  749. size_t i1 = i0;
  750. size_t i_batch = 0;
  751. llama_batch_clear(batch);
  752. while (n_cur + (int) data[i1].required_tokens <= n_ctx) {
  753. const int s0 = 2*(i1 - i0);
  754. if (s0 + 2 > max_seq) {
  755. break;
  756. }
  757. for (size_t i = 0; i < data[i1].common_prefix; ++i) {
  758. llama_batch_add(batch, data[i1].seq_tokens[0][i], i, { s0 + 0, s0 + 1}, false);
  759. }
  760. batch.logits[batch.n_tokens - 1] = true;
  761. for (int s = 0; s < 2; ++s) {
  762. for (size_t i = data[i1].common_prefix; i < data[i1].seq_tokens[s].size(); ++i) {
  763. llama_batch_add(batch, data[i1].seq_tokens[s][i], i, { s0 + s }, true);
  764. }
  765. }
  766. data[i1].i_batch = i_batch;
  767. i_batch += data[i1].required_tokens;
  768. n_cur += data[i1].required_tokens;
  769. if (++i1 == data.size()) {
  770. break;
  771. }
  772. }
  773. if (i0 == i1) {
  774. fprintf(stderr, "%s : task %zu does not fit in the context window\n", __func__, i0);
  775. return;
  776. }
  777. llama_kv_cache_clear(ctx);
  778. // decode all tasks [i0, i1)
  779. if (!decode_helper(ctx, batch, batch_logits, n_batch, n_vocab)) {
  780. fprintf(stderr, "%s: llama_decode() failed\n", __func__);
  781. return;
  782. }
  783. eval_pairs.clear();
  784. for (size_t i = i0; i < i1; ++i) {
  785. auto & task = data[i];
  786. const bool skip_choice =
  787. task.seq_tokens[0].size() - task.common_prefix > k_min_trailing_ctx &&
  788. task.seq_tokens[1].size() - task.common_prefix > k_min_trailing_ctx;
  789. const auto& n_base1 = skip_choice ? task.n_base1 : task.common_prefix;
  790. const int last_1st = task.seq_tokens[0].size() - n_base1 > 1 ? 1 : 0;
  791. size_t li = n_base1 - 1;
  792. for (size_t j = n_base1-1; j < task.seq_tokens[0].size()-1-last_1st; ++j) {
  793. eval_pairs.push_back(std::make_pair(task.i_batch + li++, task.seq_tokens[0][j+1]));
  794. }
  795. const auto& n_base2 = skip_choice ? task.n_base2 : task.common_prefix;
  796. const int last_2nd = task.seq_tokens[1].size() - n_base2 > 1 ? 1 : 0;
  797. li = task.seq_tokens[0].size() - task.common_prefix + n_base2 - 1;
  798. for (size_t j = n_base2-1; j < task.seq_tokens[1].size()-1-last_2nd; ++j) {
  799. eval_pairs.push_back(std::make_pair(task.i_batch + li++, task.seq_tokens[1][j+1]));
  800. }
  801. }
  802. compute_logprobs(batch_logits.data(), n_vocab, workers, eval_pairs, eval_results);
  803. size_t ir = 0;
  804. for (size_t i = i0; i < i1; ++i) {
  805. auto & task = data[i];
  806. const bool skip_choice =
  807. task.seq_tokens[0].size() - task.common_prefix > k_min_trailing_ctx &&
  808. task.seq_tokens[1].size() - task.common_prefix > k_min_trailing_ctx;
  809. float score_1st = 0;
  810. const auto& n_base1 = skip_choice ? task.n_base1 : task.common_prefix;
  811. const int last_1st = task.seq_tokens[0].size() - n_base1 > 1 ? 1 : 0;
  812. for (size_t j = n_base1-1; j < task.seq_tokens[0].size()-1-last_1st; ++j) {
  813. score_1st += eval_results[ir++];
  814. }
  815. score_1st /= (task.seq_tokens[0].size() - n_base1 - last_1st);
  816. float score_2nd = 0;
  817. const auto& n_base2 = skip_choice ? task.n_base2 : task.common_prefix;
  818. const int last_2nd = task.seq_tokens[1].size() - n_base2 > 1 ? 1 : 0;
  819. for (size_t j = n_base2-1; j < task.seq_tokens[1].size()-1-last_2nd; ++j) {
  820. score_2nd += eval_results[ir++];
  821. }
  822. score_2nd /= (task.seq_tokens[1].size() - n_base2 - last_2nd);
  823. int result = score_1st > score_2nd ? 1 : 2;
  824. if (result == task.answer) {
  825. ++n_correct;
  826. }
  827. ++n_done;
  828. // print the accumulated accuracy mean x 100
  829. printf("%zu\t%.4lf\t%10.6f %10.6f %d %d\n", i+1, 100.0 * n_correct/n_done, score_1st, score_2nd, result, task.answer);
  830. fflush(stdout);
  831. }
  832. i0 = i1 - 1;
  833. }
  834. printf("\n");
  835. if (n_done < 100) return;
  836. const float p = 1.f*n_correct/n_done;
  837. const float sigma = 100.f*sqrt(p*(1-p)/(n_done-1));
  838. printf("Final Winogrande score(%d tasks): %.4lf +/- %.4lf\n", n_done, 100*p, sigma);
  839. }
  840. static bool deserialize_string(std::istream& in, std::string& str) {
  841. uint32_t size;
  842. if (!in.read((char *)&size, sizeof(size)).fail()) {
  843. str.resize(size);
  844. if (!in.read((char *)str.data(), size).fail()) return true;
  845. }
  846. return false;
  847. }
  848. struct multiple_choice_answers {
  849. std::vector<std::string> answers;
  850. std::vector<int> labels;
  851. bool deserialize(std::istream& in) {
  852. uint32_t n;
  853. in.read((char *)&n, sizeof(n));
  854. if (in.fail() || n > 100) return false; // 100 as max. number of answers should be good enough for any practical purpose
  855. answers.resize(n);
  856. labels.resize(n);
  857. for (auto& a : answers) {
  858. if (!deserialize_string(in, a)) return false;
  859. }
  860. in.read((char *)labels.data(), n*sizeof(int));
  861. return !in.fail();
  862. }
  863. };
  864. struct multiple_choice_task {
  865. std::string question; // the question (or context that needs to be continued)
  866. multiple_choice_answers mc1; // possible answers (continuations) with a single correct answer
  867. multiple_choice_answers mc2; // possible answers (continuations) with multiple correct answers - not handled yet
  868. bool deserialize(std::istream& in) {
  869. if (!deserialize_string(in, question)) return false;
  870. return mc1.deserialize(in) && mc2.deserialize(in);
  871. }
  872. // For evaluation
  873. size_t i_batch; // starting index in the llama_batch
  874. size_t common_prefix; // max number of initial tokens that are the same in all sentences
  875. size_t required_tokens; // needed number of tokens to evaluate all answers
  876. std::vector<std::vector<llama_token>> seq_tokens;
  877. std::vector<float> log_probs;
  878. };
  879. static bool multiple_choice_prepare_one_task(llama_context * ctx, bool add_bos, multiple_choice_task& task, bool log_error) {
  880. if (task.question.empty() || task.mc1.answers.empty()) {
  881. if (log_error) {
  882. printf("%s: found bad task with empty question and/or answers\n", __func__);
  883. }
  884. return false;
  885. }
  886. task.seq_tokens.reserve(task.mc1.answers.size());
  887. for (auto& answer : task.mc1.answers) {
  888. if (answer.empty()) {
  889. if (log_error) {
  890. printf("%s: found empty answer\n", __func__);
  891. }
  892. return false;
  893. }
  894. task.seq_tokens.emplace_back(::llama_tokenize(ctx, task.question + " " + answer, add_bos));
  895. }
  896. auto min_len = task.seq_tokens.front().size();
  897. for (auto& seq : task.seq_tokens) {
  898. min_len = std::min(min_len, seq.size());
  899. }
  900. task.common_prefix = 0;
  901. for (size_t k = 0; k < min_len; ++k) {
  902. auto token = task.seq_tokens[0][k];
  903. bool all_same = true;
  904. for (size_t i = 1; i < task.seq_tokens.size(); ++i) {
  905. if (task.seq_tokens[i][k] != token) {
  906. all_same = false;
  907. break;
  908. }
  909. }
  910. if (!all_same) {
  911. break;
  912. }
  913. ++task.common_prefix;
  914. }
  915. task.required_tokens = task.common_prefix;
  916. for (auto& seq : task.seq_tokens) {
  917. task.required_tokens += seq.size() - task.common_prefix;
  918. }
  919. return true;
  920. }
  921. //
  922. // Calculates score for multiple choice tasks with single correct answer from prompt.
  923. // Commonly used LLM evaluation metrics of this type are
  924. // * ARC
  925. // * HellaSwag
  926. // * MMLU
  927. // * TruthfulQA
  928. //
  929. // Validation datasets for these 4 tests can be found at
  930. // https://huggingface.co/datasets/ikawrakow/validation-datasets-for-llama.cpp
  931. // The data for these datasets was extracted from
  932. // git@hf.co:datasets/allenai/ai2_arc
  933. // https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl
  934. // git@hf.co:datasets/Stevross/mmlu
  935. // https://huggingface.co/datasets/truthful_qa
  936. //
  937. static void multiple_choice_score(llama_context * ctx, const gpt_params & params) {
  938. std::istringstream strstream(params.prompt);
  939. uint32_t n_task;
  940. strstream.read((char *)&n_task, sizeof(n_task));
  941. if (strstream.fail() || n_task == 0) {
  942. printf("%s: no tasks\n", __func__);
  943. return;
  944. }
  945. printf("%s: there are %u tasks in prompt\n", __func__, n_task);
  946. std::vector<uint32_t> task_pos(n_task);
  947. strstream.read((char *)task_pos.data(), task_pos.size()*sizeof(uint32_t));
  948. if (strstream.fail()) {
  949. printf("%s: failed to raad task positions from prompt\n", __func__);
  950. return;
  951. }
  952. std::vector<multiple_choice_task> tasks;
  953. if (params.multiple_choice_tasks == 0 || params.multiple_choice_tasks >= (size_t)n_task) {
  954. // Use all tasks
  955. tasks.resize(n_task);
  956. printf("%s: reading tasks", __func__);
  957. int n_dot = n_task/100;
  958. int i = 0;
  959. for (auto& task : tasks) {
  960. ++i;
  961. if (!task.deserialize(strstream)) {
  962. printf("%s: failed to read task %d of %u\n", __func__, i, n_task);
  963. return;
  964. }
  965. if (i%n_dot == 0) printf(".");
  966. }
  967. printf("done\n");
  968. }
  969. else {
  970. printf("%s: selecting %zu random tasks from %u tasks available\n", __func__, params.multiple_choice_tasks, n_task);
  971. std::mt19937 rng(1);
  972. std::vector<int> aux(n_task);
  973. for (uint32_t i = 0; i < n_task; ++i) aux[i] = i;
  974. float scale = 1.f/(1.f + (float)std::mt19937::max());
  975. tasks.resize(params.multiple_choice_tasks);
  976. for (auto& task : tasks) {
  977. int j = (int)(scale * rng() * aux.size());
  978. int idx = aux[j];
  979. aux[j] = aux.back();
  980. aux.pop_back();
  981. strstream.seekg(task_pos[idx], std::ios::beg);
  982. if (!task.deserialize(strstream)) {
  983. printf("%s: failed to read task %d at position %u\n", __func__, idx, task_pos[idx]);
  984. return;
  985. }
  986. }
  987. n_task = params.multiple_choice_tasks;
  988. }
  989. // This is needed as usual for LLaMA models
  990. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  991. printf("%s: preparing task data", __func__);
  992. fflush(stdout);
  993. if (n_task > 500) {
  994. printf("...");
  995. fflush(stdout);
  996. std::atomic<int> counter(0);
  997. std::atomic<int> n_bad(0);
  998. auto prepare = [&counter, &n_bad, &tasks, ctx, add_bos] () {
  999. int num_tasks = tasks.size();
  1000. int n_bad_local = 0;
  1001. while (true) {
  1002. int first = counter.fetch_add(K_TOKEN_CHUNK);
  1003. if (first >= num_tasks) {
  1004. if (n_bad_local > 0) n_bad += n_bad_local;
  1005. break;
  1006. }
  1007. int last = std::min(first + K_TOKEN_CHUNK, num_tasks);
  1008. for (int i = first; i < last; ++i) {
  1009. if (!multiple_choice_prepare_one_task(ctx, add_bos, tasks[i], false)) ++n_bad_local;
  1010. }
  1011. }
  1012. };
  1013. size_t max_thread = std::thread::hardware_concurrency();
  1014. max_thread = std::min(max_thread, (tasks.size() + K_TOKEN_CHUNK - 1)/K_TOKEN_CHUNK);
  1015. std::vector<std::thread> workers(max_thread-1);
  1016. for (auto& w : workers) w = std::thread(prepare);
  1017. prepare();
  1018. for (auto& w : workers) w.join();
  1019. printf("done\n");
  1020. fflush(stdout);
  1021. int nbad = n_bad;
  1022. if (nbad > 0) {
  1023. printf("%s: found %d malformed tasks\n", __func__, nbad);
  1024. return;
  1025. }
  1026. } else {
  1027. int n_dot = n_task/100;
  1028. int i_task = 0;
  1029. for (auto& task : tasks) {
  1030. ++i_task;
  1031. if (!multiple_choice_prepare_one_task(ctx, add_bos, task, true)) {
  1032. return;
  1033. }
  1034. if (i_task%n_dot == 0) {
  1035. printf(".");
  1036. fflush(stdout);
  1037. }
  1038. }
  1039. printf("done\n");
  1040. }
  1041. printf("%s : calculating TruthfulQA score over %zu tasks.\n", __func__, tasks.size());
  1042. printf("\ntask\tacc_norm\n");
  1043. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  1044. const int n_ctx = llama_n_ctx(ctx);
  1045. const int n_batch = params.n_batch;
  1046. const int max_tasks_per_batch = 32;
  1047. const int max_seq = 4*max_tasks_per_batch;
  1048. llama_batch batch = llama_batch_init(n_ctx, 0, max_seq);
  1049. std::vector<float> tok_logits(n_vocab);
  1050. std::vector<float> batch_logits(n_vocab*n_ctx);
  1051. std::vector<std::pair<size_t, llama_token>> eval_pairs;
  1052. std::vector<float> eval_results;
  1053. std::vector<std::thread> workers(std::thread::hardware_concurrency());
  1054. std::vector<int> batch_indeces;
  1055. int n_done = 0;
  1056. int n_correct = 0;
  1057. int n_tot_answers = 0;
  1058. for (size_t i0 = 0; i0 < tasks.size(); i0++) {
  1059. int n_cur = 0;
  1060. size_t i1 = i0;
  1061. size_t i_batch = 0; // this tells us where in `llama_batch` we are currently
  1062. llama_batch_clear(batch);
  1063. // batch as much tasks as possible into the available context
  1064. // each task has 4 unique seuqnce ids - one for each ending
  1065. // the common prefix is shared among the 4 sequences to save tokens
  1066. // we extract logits only from the last common token and from all ending tokens of each sequence
  1067. int s0 = 0;
  1068. while (n_cur + (int) tasks[i1].required_tokens <= n_ctx) {
  1069. auto& cur_task = tasks[i1];
  1070. int num_answers = cur_task.seq_tokens.size();
  1071. if (s0 + num_answers > max_seq) {
  1072. break;
  1073. }
  1074. if (int(batch_indeces.size()) != num_answers) {
  1075. batch_indeces.resize(num_answers);
  1076. }
  1077. for (int s = 0; s < num_answers; ++s) batch_indeces[s] = s0 + s;
  1078. for (size_t i = 0; i < cur_task.common_prefix; ++i) {
  1079. //llama_batch_add(batch, cur_task.seq_tokens[0][i], i, { s0 + 0, s0 + 1, s0 + 2, s0 + 3}, false);
  1080. llama_batch_add(batch, cur_task.seq_tokens[0][i], i, batch_indeces, false);
  1081. }
  1082. batch.logits[batch.n_tokens - 1] = true; // we need logits for the last token of the common prefix
  1083. for (int s = 0; s < int(cur_task.seq_tokens.size()); ++s) {
  1084. for (size_t i = cur_task.common_prefix; i < cur_task.seq_tokens[s].size(); ++i) {
  1085. llama_batch_add(batch, cur_task.seq_tokens[s][i], i, { s0 + s }, true);
  1086. }
  1087. }
  1088. s0 += num_answers;
  1089. cur_task.i_batch = i_batch;
  1090. i_batch += cur_task.required_tokens;
  1091. n_cur += cur_task.required_tokens;
  1092. if (++i1 == tasks.size()) {
  1093. break;
  1094. }
  1095. }
  1096. if (i0 == i1) {
  1097. fprintf(stderr, "%s : task %zu does not fit in the context window\n", __func__, i0);
  1098. return;
  1099. }
  1100. llama_kv_cache_clear(ctx);
  1101. // decode all tasks [i0, i1)
  1102. if (!decode_helper(ctx, batch, batch_logits, n_batch, n_vocab)) {
  1103. fprintf(stderr, "%s: llama_decode() failed\n", __func__);
  1104. return;
  1105. }
  1106. // Compute log-probs in parallel
  1107. // First we collect all tasks
  1108. eval_pairs.clear();
  1109. for (size_t i = i0; i < i1; ++i) {
  1110. auto& cur_task = tasks[i];
  1111. size_t li = cur_task.common_prefix;
  1112. for (int s = 0; s < int(cur_task.seq_tokens.size()); ++s) {
  1113. for (size_t j = cur_task.common_prefix; j < cur_task.seq_tokens[s].size() - 1; j++) {
  1114. eval_pairs.push_back(std::make_pair(cur_task.i_batch + li++, cur_task.seq_tokens[s][j + 1]));
  1115. }
  1116. ++li;
  1117. }
  1118. }
  1119. // Then we do the actual calculation
  1120. compute_logprobs(batch_logits.data(), n_vocab, workers, eval_pairs, eval_results);
  1121. size_t ir = 0;
  1122. // compute the logprobs for each ending of the decoded tasks
  1123. for (size_t i = i0; i < i1; ++i) {
  1124. auto & cur_task = tasks[i];
  1125. //printf("==== Evaluating <%s> with correct answer ", cur_task.question.c_str());
  1126. //for (int j = 0; j < int(cur_task.mc1.labels.size()); ++j) {
  1127. // if (cur_task.mc1.labels[j] == 1) {
  1128. // printf("%d", j+1);
  1129. // }
  1130. //}
  1131. //printf("\n common_prefix: %zu\n", cur_task.common_prefix);
  1132. std::memcpy(tok_logits.data(), batch_logits.data() + n_vocab*(cur_task.i_batch + cur_task.common_prefix - 1), n_vocab*sizeof(float));
  1133. const auto first_probs = softmax(tok_logits);
  1134. cur_task.log_probs.resize(cur_task.seq_tokens.size());
  1135. for (int s = 0; s < int(cur_task.seq_tokens.size()); ++s) {
  1136. size_t count = 1;
  1137. float log_prob = std::log(first_probs[cur_task.seq_tokens[s][cur_task.common_prefix]]);
  1138. for (size_t j = cur_task.common_prefix; j < cur_task.seq_tokens[s].size() - 1; j++) {
  1139. //printf(" %zu %g\n", ir, eval_results[ir]);
  1140. ++count;
  1141. log_prob += eval_results[ir++];
  1142. }
  1143. cur_task.log_probs[s] = log_prob / count;
  1144. //printf(" Final: %g\n", log_prob / count);
  1145. //printf(" <%s> : %g\n", cur_task.mc1.answers[s].c_str(), log_prob/count);
  1146. }
  1147. // Find the ending with maximum logprob
  1148. size_t logprob_max_idx = 0;
  1149. float logprob_max_val = cur_task.log_probs[0];
  1150. for (size_t s = 1; s < cur_task.log_probs.size(); s++) {
  1151. if (cur_task.log_probs[s] > logprob_max_val) {
  1152. logprob_max_val = cur_task.log_probs[s];
  1153. logprob_max_idx = s;
  1154. }
  1155. }
  1156. n_tot_answers += cur_task.log_probs.size();
  1157. if (cur_task.mc1.labels[logprob_max_idx] == 1) {
  1158. ++n_correct;
  1159. }
  1160. ++n_done;
  1161. // Print the accumulated accuracy mean x 100
  1162. printf("%d\t%.8lf\n", n_done, 100.*n_correct/n_done);
  1163. fflush(stdout);
  1164. }
  1165. i0 = i1 - 1;
  1166. }
  1167. llama_batch_free(batch);
  1168. if (n_done < 100) return;
  1169. float p = 1.f*n_correct/n_done;
  1170. float sigma = sqrt(p*(1-p)/(n_done-1));
  1171. printf("\n Final result: %.4f +/- %.4f\n", 100.f*p, 100.f*sigma);
  1172. p = 1.f*n_done/n_tot_answers;
  1173. sigma = sqrt(p*(1-p)/(n_done-1));
  1174. printf("Random chance: %.4f +/- %.4f\n", 100.f*p, 100.f*sigma);
  1175. printf("\n");
  1176. }
  1177. int main(int argc, char ** argv) {
  1178. gpt_params params;
  1179. params.n_batch = 512;
  1180. if (!gpt_params_parse(argc, argv, params)) {
  1181. return 1;
  1182. }
  1183. params.logits_all = true;
  1184. params.n_batch = std::min(params.n_batch, params.n_ctx);
  1185. if (params.ppl_stride > 0) {
  1186. fprintf(stderr, "Will perform strided perplexity calculation -> adjusting context size from %d to %d\n",
  1187. params.n_ctx, params.n_ctx + params.ppl_stride/2);
  1188. params.n_ctx += params.ppl_stride/2;
  1189. }
  1190. print_build_info();
  1191. if (params.seed == LLAMA_DEFAULT_SEED) {
  1192. params.seed = time(NULL);
  1193. }
  1194. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  1195. std::mt19937 rng(params.seed);
  1196. if (params.random_prompt) {
  1197. params.prompt = gpt_random_prompt(rng);
  1198. }
  1199. llama_backend_init(params.numa);
  1200. llama_model * model;
  1201. llama_context * ctx;
  1202. // load the model and apply lora adapter, if any
  1203. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  1204. if (model == NULL) {
  1205. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  1206. return 1;
  1207. }
  1208. const int n_ctx_train = llama_n_ctx_train(model);
  1209. if (params.n_ctx > n_ctx_train) {
  1210. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  1211. __func__, n_ctx_train, params.n_ctx);
  1212. }
  1213. // print system information
  1214. {
  1215. fprintf(stderr, "\n");
  1216. fprintf(stderr, "%s\n", get_system_info(params).c_str());
  1217. }
  1218. struct results_perplexity results;
  1219. if (params.hellaswag) {
  1220. hellaswag_score(ctx, params);
  1221. } else if (params.winogrande) {
  1222. winogrande_score(ctx, params);
  1223. } else if (params.multiple_choice) {
  1224. multiple_choice_score(ctx, params);
  1225. } else {
  1226. results = perplexity(ctx, params);
  1227. }
  1228. llama_print_timings(ctx);
  1229. write_logfile(ctx, params, model, results);
  1230. llama_free(ctx);
  1231. llama_free_model(model);
  1232. llama_backend_free();
  1233. return 0;
  1234. }