perplexity.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906
  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 inline int nearest_int(float fval) {
  99. //assert(fval <= 4194303.f);
  100. float val = fval + 12582912.f;
  101. int i; memcpy(&i, &val, sizeof(int));
  102. return (i & 0x007fffff) - 0x00400000;
  103. }
  104. static double log_softmax(int n_vocab, const float * logits, uint16_t * log_prob, int tok) {
  105. float max_logit = logits[0];
  106. float min_logit = logits[0];
  107. for (int i = 1; i < n_vocab; ++i) {
  108. max_logit = std::max(max_logit, logits[i]);
  109. min_logit = std::min(min_logit, logits[i]);
  110. }
  111. min_logit = std::max(min_logit, max_logit - 16);
  112. double sum_exp = 0.0;
  113. for (int i = 0; i < n_vocab; ++i) {
  114. sum_exp += expf(logits[i] - max_logit);
  115. }
  116. const float log_sum_exp = log(sum_exp);
  117. const float min_log_prob = min_logit - max_logit - log_sum_exp;
  118. const float scale = (max_logit - min_logit)/65535.f;
  119. float * d = (float *)log_prob;
  120. d[0] = scale;
  121. d[1] = min_log_prob;
  122. log_prob += 4;
  123. if (scale) {
  124. const float inv_scale = 1/scale;
  125. for (int i = 0; i < n_vocab; ++i) {
  126. log_prob[i] = logits[i] > min_logit ? nearest_int(inv_scale*(logits[i] - min_logit)) : 0;
  127. }
  128. } else {
  129. std::memset(log_prob, 0, n_vocab*sizeof(uint16_t));
  130. }
  131. return max_logit + log_sum_exp - logits[tok];
  132. }
  133. static void process_logits(
  134. int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
  135. double & nll, double & nll2, float * logit_history, float * prob_history
  136. ) {
  137. std::mutex mutex;
  138. int counter = 0;
  139. auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
  140. double local_nll = 0;
  141. double local_nll2 = 0;
  142. while (true) {
  143. std::unique_lock<std::mutex> lock(mutex);
  144. int i = counter++;
  145. if (i >= n_token) {
  146. nll += local_nll; nll2 += local_nll2;
  147. break;
  148. }
  149. lock.unlock();
  150. const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  151. const double v = -results.log_softmax;
  152. local_nll += v;
  153. local_nll2 += v*v;
  154. logit_history[i] = results.logit;
  155. prob_history[i] = results.prob;
  156. }
  157. };
  158. for (auto & w : workers) {
  159. w = std::thread(compute);
  160. }
  161. compute();
  162. for (auto & w : workers) {
  163. w.join();
  164. }
  165. }
  166. static void process_logits(std::ostream& out, int n_vocab, const float * logits, const int * tokens, int n_token,
  167. std::vector<std::thread> & workers, std::vector<uint16_t> & log_probs, double & nll, double & nll2) {
  168. std::mutex mutex;
  169. const int nv = 2*((n_vocab + 1)/2) + 4;
  170. int counter = 0;
  171. auto compute = [&mutex, &counter, &log_probs, &nll, &nll2, n_vocab, logits, tokens, n_token, nv] () {
  172. double local_nll = 0;
  173. double local_nll2 = 0;
  174. while (true) {
  175. std::unique_lock<std::mutex> lock(mutex);
  176. int i = counter++;
  177. if (i >= n_token) {
  178. nll += local_nll; nll2 += local_nll2;
  179. break;
  180. }
  181. lock.unlock();
  182. const double v = log_softmax(n_vocab, logits + i*n_vocab, log_probs.data() + i*nv, tokens[i+1]);
  183. local_nll += v;
  184. local_nll2 += v*v;
  185. }
  186. };
  187. for (auto & w : workers) {
  188. w = std::thread(compute);
  189. }
  190. compute();
  191. for (auto & w : workers) {
  192. w.join();
  193. }
  194. out.write((const char *)log_probs.data(), n_token*nv*sizeof(uint16_t));
  195. }
  196. struct kl_divergence_result {
  197. double sum_nll = 0;
  198. double sum_nll2 = 0;
  199. double sum_kld = 0;
  200. double sum_kld2 = 0;
  201. double sum_nll_diff = 0;
  202. double sum_nll_diff2 = 0;
  203. size_t n_same_top = 0;
  204. size_t count = 0;
  205. };
  206. static double log_softmax(int n_vocab, const float * logits, const uint16_t * base_log_prob, int tok, kl_divergence_result & kld) {
  207. float max_logit = logits[0];
  208. int imax = 0;
  209. for (int i = 1; i < n_vocab; ++i) {
  210. if (logits[i] > max_logit) {
  211. max_logit = logits[i];
  212. imax = i;
  213. }
  214. }
  215. double sum_exp = 0.0;
  216. for (int i = 0; i < n_vocab; ++i) {
  217. sum_exp += expf(logits[i] - max_logit);
  218. }
  219. const float log_sum_exp = log(sum_exp);
  220. const float * d = (const float *)base_log_prob;
  221. const float scale = d[0];
  222. const float min_log_prob = d[1];
  223. base_log_prob += 4;
  224. float nll = max_logit + log_sum_exp - logits[tok];
  225. kld.sum_nll += nll;
  226. kld.sum_nll2 += nll*nll;
  227. nll += (scale*base_log_prob[tok] + min_log_prob);
  228. kld.sum_nll_diff += nll;
  229. kld.sum_nll_diff2 += nll*nll;
  230. max_logit += log_sum_exp;
  231. double sum = 0;
  232. int imax_base = -1;
  233. float p_log_base_max = 0;
  234. for (int i = 0; i < n_vocab; ++i) {
  235. const float p_log_base = scale*base_log_prob[i] + min_log_prob;
  236. if (i == 0 || p_log_base > p_log_base_max) {
  237. p_log_base_max = p_log_base;
  238. imax_base = i;
  239. }
  240. if (p_log_base > -16.f) {
  241. const float p_base = expf(p_log_base);
  242. sum += p_base * (p_log_base - logits[i] + max_logit);
  243. }
  244. }
  245. kld.sum_kld += sum;
  246. kld.sum_kld2 += sum*sum;
  247. ++kld.count;
  248. if (imax == imax_base) ++kld.n_same_top;
  249. return sum;
  250. }
  251. static void process_logits(int n_vocab, const float * logits, const int * tokens, int n_token,
  252. std::vector<std::thread> & workers, const std::vector<uint16_t> & base_log_probs, kl_divergence_result & kld,
  253. float * kld_values) {
  254. std::mutex mutex;
  255. const int nv = 2*((n_vocab + 1)/2) + 4;
  256. int counter = 0;
  257. auto compute = [&mutex, &counter, &base_log_probs, &kld, n_vocab, logits, tokens, n_token, nv, kld_values] () {
  258. kl_divergence_result local_kld;
  259. while (true) {
  260. std::unique_lock<std::mutex> lock(mutex);
  261. int i = counter++;
  262. if (i >= n_token) {
  263. kld.sum_nll += local_kld.sum_nll;
  264. kld.sum_nll2 += local_kld.sum_nll2;
  265. kld.sum_kld += local_kld.sum_kld;
  266. kld.sum_kld2 += local_kld.sum_kld2;
  267. kld.sum_nll_diff += local_kld.sum_nll_diff;
  268. kld.sum_nll_diff2 += local_kld.sum_nll_diff2;
  269. kld.n_same_top += local_kld.n_same_top;
  270. kld.count += local_kld.count;
  271. break;
  272. }
  273. lock.unlock();
  274. double v = log_softmax(n_vocab, logits + i*n_vocab, base_log_probs.data() + i*nv, tokens[i+1], local_kld);
  275. kld_values[i] = (float)v;
  276. }
  277. };
  278. for (auto & w : workers) {
  279. w = std::thread(compute);
  280. }
  281. compute();
  282. for (auto & w : workers) {
  283. w.join();
  284. }
  285. }
  286. static results_perplexity perplexity_v2(llama_context * ctx, const gpt_params & params) {
  287. // Download: https://huggingface.co/datasets/ggml-org/ci/resolve/main/wikitext-2-raw-v1.zip
  288. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  289. // Output: `perplexity: 13.5106 [114/114]`
  290. // BOS tokens will be added for each chunk before eval
  291. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  292. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  293. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  294. const int n_ctx = llama_n_ctx(ctx);
  295. if (int(tokens.size()) < 2*n_ctx) {
  296. fprintf(stderr, "%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*n_ctx,
  297. n_ctx);
  298. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  299. return {std::move(tokens), 0., {}, {}};
  300. }
  301. std::vector<float> logit_history;
  302. std::vector<float> prob_history;
  303. logit_history.resize(tokens.size());
  304. prob_history.resize(tokens.size());
  305. if (params.ppl_stride <= 0) {
  306. fprintf(stderr, "%s: stride is %d but must be greater than zero!\n",__func__,params.ppl_stride);
  307. return {tokens, -1, logit_history, prob_history};
  308. }
  309. const int calc_chunk = n_ctx;
  310. fprintf(stderr, "%s: have %zu tokens. Calculation chunk = %d\n", __func__, tokens.size(), calc_chunk);
  311. if (int(tokens.size()) <= calc_chunk) {
  312. fprintf(stderr, "%s: there are only %zu tokens, this is not enough for a context size of %d and stride %d\n",__func__,
  313. tokens.size(), n_ctx, params.ppl_stride);
  314. return {tokens, -1, logit_history, prob_history};
  315. }
  316. const int n_chunk_max = (tokens.size() - calc_chunk + params.ppl_stride - 1) / params.ppl_stride;
  317. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  318. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  319. const int n_batch = params.n_batch;
  320. int count = 0;
  321. double nll = 0.0;
  322. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  323. for (int i = 0; i < n_chunk; ++i) {
  324. const int start = i * params.ppl_stride;
  325. const int end = start + calc_chunk;
  326. const int num_batches = (calc_chunk + n_batch - 1) / n_batch;
  327. //fprintf(stderr, "%s: evaluating %d...%d using %d batches\n", __func__, start, end, num_batches);
  328. std::vector<float> logits;
  329. const auto t_start = std::chrono::high_resolution_clock::now();
  330. // clear the KV cache
  331. llama_kv_cache_clear(ctx);
  332. for (int j = 0; j < num_batches; ++j) {
  333. const int batch_start = start + j * n_batch;
  334. const int batch_size = std::min(end - batch_start, n_batch);
  335. //fprintf(stderr, " Batch %d: starts at %d, size is %d, n_past is %d\n",j,batch_start,batch_size,j * n_batch);
  336. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  337. //fprintf(stderr, "%s : failed to eval\n", __func__);
  338. return {tokens, -1, logit_history, prob_history};
  339. }
  340. // save original token and restore it after eval
  341. const auto token_org = tokens[batch_start];
  342. // add BOS token for the first batch of each chunk
  343. if (add_bos && j == 0) {
  344. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  345. }
  346. const auto batch_logits = llama_get_logits(ctx);
  347. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  348. if (j == 0) {
  349. tokens[batch_start] = token_org;
  350. }
  351. }
  352. const auto t_end = std::chrono::high_resolution_clock::now();
  353. if (i == 0) {
  354. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  355. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  356. int total_seconds = (int)(t_total * n_chunk);
  357. if (total_seconds >= 60*60) {
  358. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  359. total_seconds = total_seconds % (60*60);
  360. }
  361. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  362. }
  363. //fprintf(stderr, "%s: using tokens %d...%d\n",__func__,params.n_ctx - params.ppl_stride + start, params.n_ctx + start);
  364. for (int j = n_ctx - params.ppl_stride - 1; j < n_ctx - 1; ++j) {
  365. // Calculate probability of next token, given the previous ones.
  366. const std::vector<float> tok_logits(
  367. logits.begin() + (j + 0) * n_vocab,
  368. logits.begin() + (j + 1) * n_vocab);
  369. const float prob = softmax(tok_logits)[tokens[start + j + 1]];
  370. logit_history[start + j + 1] = tok_logits[tokens[start + j + 1]];
  371. prob_history[start + j + 1] = prob;
  372. nll += -std::log(prob);
  373. ++count;
  374. }
  375. // perplexity is e^(average negative log-likelihood)
  376. if (params.ppl_output_type == 0) {
  377. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  378. } else {
  379. printf("%8d %.4lf\n", i*params.ppl_stride, std::exp(nll / count));
  380. }
  381. fflush(stdout);
  382. }
  383. printf("\n");
  384. return {tokens, std::exp(nll / count), logit_history, prob_history};
  385. }
  386. static results_perplexity perplexity(llama_context * ctx, const gpt_params & params, const int32_t n_ctx) {
  387. if (params.ppl_stride > 0) {
  388. return perplexity_v2(ctx, params);
  389. }
  390. // Download: https://huggingface.co/datasets/ggml-org/ci/resolve/main/wikitext-2-raw-v1.zip
  391. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  392. // Output: `perplexity: 13.5106 [114/114]`
  393. // BOS tokens will be added for each chunk before eval
  394. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  395. std::ofstream logits_stream;
  396. if (!params.logits_file.empty()) {
  397. logits_stream.open(params.logits_file.c_str(), std::ios::binary);
  398. if (!logits_stream.is_open()) {
  399. fprintf(stderr, "%s: failed to open %s for writing\n", __func__, params.logits_file.c_str());
  400. return {};
  401. }
  402. fprintf(stderr, "%s: saving all logits to %s\n", __func__, params.logits_file.c_str());
  403. logits_stream.write("_logits_", 8);
  404. logits_stream.write(reinterpret_cast<const char *>(&n_ctx), sizeof(n_ctx));
  405. }
  406. auto tim1 = std::chrono::high_resolution_clock::now();
  407. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  408. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  409. auto tim2 = std::chrono::high_resolution_clock::now();
  410. fprintf(stderr, "%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  411. if (int(tokens.size()) < 2*n_ctx) {
  412. fprintf(stderr, "%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*n_ctx,
  413. n_ctx);
  414. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  415. return {std::move(tokens), 0., {}, {}};
  416. }
  417. std::vector<float> logit_history;
  418. logit_history.resize(tokens.size());
  419. std::vector<float> prob_history;
  420. prob_history.resize(tokens.size());
  421. const int n_chunk_max = tokens.size() / n_ctx;
  422. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  423. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  424. const int n_batch = params.n_batch;
  425. int count = 0;
  426. double nll = 0.0;
  427. double nll2 = 0.0;
  428. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  429. const int n_seq = std::max(1, n_batch / n_ctx);
  430. GGML_ASSERT(n_batch < n_ctx || n_batch % n_ctx == 0);
  431. GGML_ASSERT(params.n_ctx == n_seq * n_ctx);
  432. llama_batch batch = llama_batch_init(std::min(n_batch, n_ctx*n_seq), 0, 1);
  433. std::vector<float> logits;
  434. if (num_batches > 1) {
  435. logits.reserve((size_t)n_ctx * n_vocab);
  436. }
  437. fprintf(stderr, "%s: calculating perplexity over %d chunks, n_ctx=%d, batch_size=%d, n_seq=%d\n", __func__, n_chunk, n_ctx, n_batch, n_seq);
  438. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  439. std::vector<uint16_t> log_probs;
  440. if (!params.logits_file.empty()) {
  441. logits_stream.write((const char *)&n_vocab, sizeof(n_vocab));
  442. logits_stream.write((const char *)&n_chunk, sizeof(n_chunk));
  443. logits_stream.write((const char *)tokens.data(), n_chunk*n_ctx*sizeof(tokens[0]));
  444. const int nv = 2*((n_vocab + 1)/2) + 4;
  445. log_probs.resize(n_ctx * nv);
  446. }
  447. // We get the logits for all the tokens in the context window (params.n_ctx)
  448. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  449. // calculate the perplexity over the last half of the window (so the model always has
  450. // some context to predict the token).
  451. //
  452. // We rely on the fact that attention in the forward pass only looks at previous
  453. // tokens here, so the logits returned for each token are an accurate representation
  454. // of what the model would have predicted at that point.
  455. //
  456. // Example, we have a context window of 512, we will compute perplexity for each of the
  457. // last 256 tokens. Then, we split the input up into context window size chunks to
  458. // process the entire prompt.
  459. const int first = n_ctx/2;
  460. for (int i = 0; i < n_chunk; i += n_seq) {
  461. const int start = i * n_ctx;
  462. const int end = start + n_ctx;
  463. const int n_seq_batch = std::min(n_seq, n_chunk - i);
  464. const auto t_start = std::chrono::high_resolution_clock::now();
  465. // clear the KV cache
  466. llama_kv_cache_clear(ctx);
  467. for (int j = 0; j < num_batches; ++j) {
  468. const int batch_start = start + j * n_batch;
  469. const int batch_size = std::min(end - batch_start, n_batch);
  470. batch.n_tokens = 0;
  471. for (int seq = 0; seq < n_seq_batch; seq++) {
  472. int seq_start = batch_start + seq*n_ctx;
  473. // save original token and restore it after eval
  474. const auto token_org = tokens[seq_start];
  475. // add BOS token for the first batch of each chunk
  476. if (add_bos && j == 0) {
  477. tokens[seq_start] = llama_token_bos(llama_get_model(ctx));
  478. }
  479. for (int k = 0; k < batch_size; ++k) {
  480. const int idx = seq*n_ctx + k;
  481. batch.token[idx] = tokens[seq_start + k];
  482. batch.pos[idx] = j*n_batch + k;
  483. batch.n_seq_id[idx] = 1;
  484. batch.seq_id[idx][0] = seq;
  485. batch.logits[idx] = batch.pos[idx] >= first ? 1 : 0;
  486. }
  487. batch.n_tokens += batch_size;
  488. // restore the original token in case it was set to BOS
  489. tokens[seq_start] = token_org;
  490. }
  491. if (llama_decode(ctx, batch)) {
  492. fprintf(stderr, "%s : failed to eval\n", __func__);
  493. return {tokens, -1, logit_history, prob_history};
  494. }
  495. if (num_batches > 1) {
  496. const auto * batch_logits = llama_get_logits(ctx);
  497. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  498. }
  499. }
  500. if (i == 0) {
  501. llama_synchronize(ctx);
  502. const auto t_end = std::chrono::high_resolution_clock::now();
  503. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  504. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  505. int total_seconds = (int)(t_total*n_chunk/n_seq);
  506. if (total_seconds >= 60*60) {
  507. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  508. total_seconds = total_seconds % (60*60);
  509. }
  510. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  511. }
  512. for (int seq = 0; seq < n_seq_batch; seq++) {
  513. const float * all_logits = num_batches > 1 ? logits.data() : llama_get_logits_ith(ctx, seq*n_ctx);
  514. llama_token * tokens_data = tokens.data() + start + seq*n_ctx + first;
  515. if (!params.logits_file.empty()) {
  516. process_logits(logits_stream, n_vocab, all_logits + first*n_vocab,
  517. tokens_data, n_ctx - 1 - first,
  518. workers, log_probs, nll, nll2);
  519. } else {
  520. process_logits(n_vocab, all_logits + first*n_vocab,
  521. tokens_data, n_ctx - 1 - first,
  522. workers, nll, nll2,
  523. logit_history.data() + start + seq*n_ctx + first,
  524. prob_history.data() + start + seq*n_ctx + first);
  525. }
  526. count += n_ctx - first - 1;
  527. // perplexity is e^(average negative log-likelihood)
  528. if (params.ppl_output_type == 0) {
  529. printf("[%d]%.4lf,", i + seq + 1, std::exp(nll / count));
  530. } else {
  531. double av = nll/count;
  532. double av2 = nll2/count - av*av;
  533. if (av2 > 0) av2 = sqrt(av2/(count-1));
  534. printf("%8d %.4lf %4lf %4lf\n", i*n_ctx, std::exp(nll / count), av, av2);
  535. }
  536. }
  537. fflush(stdout);
  538. logits.clear();
  539. }
  540. printf("\n");
  541. nll2 /= count;
  542. nll /= count;
  543. const double ppl = exp(nll);
  544. nll2 -= nll * nll;
  545. if (nll2 > 0) {
  546. nll2 = sqrt(nll2/(count-1));
  547. printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  548. } else {
  549. printf("Unexpected negative standard deviation of log(prob)\n");
  550. }
  551. llama_batch_free(batch);
  552. return {tokens, ppl, logit_history, prob_history};
  553. }
  554. static bool decode_helper(llama_context * ctx, llama_batch & batch, std::vector<float> & batch_logits, int32_t n_batch, int32_t n_vocab) {
  555. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch) {
  556. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  557. llama_batch batch_view = {
  558. n_tokens,
  559. batch.token + i,
  560. nullptr,
  561. batch.pos + i,
  562. batch.n_seq_id + i,
  563. batch.seq_id + i,
  564. batch.logits + i,
  565. 0, 0, 0, // unused
  566. };
  567. const int ret = llama_decode(ctx, batch_view);
  568. if (ret != 0) {
  569. LOG_TEE("failed to decode the batch, n_batch = %d, ret = %d\n", n_batch, ret);
  570. return false;
  571. }
  572. memcpy(batch_logits.data() + i*n_vocab, llama_get_logits(ctx), n_tokens*n_vocab*sizeof(float));
  573. }
  574. return true;
  575. }
  576. #define K_TOKEN_CHUNK 4
  577. static void compute_logprobs(const float * batch_logits, int n_vocab, std::vector<std::thread>& workers,
  578. const std::vector<std::pair<size_t, llama_token>>& eval_pairs, std::vector<float>& eval_results) {
  579. if (eval_results.size() != eval_pairs.size()) {
  580. eval_results.resize(eval_pairs.size());
  581. }
  582. if (eval_pairs.empty()) return;
  583. size_t max_threads = std::min((eval_pairs.size() + K_TOKEN_CHUNK - 1)/K_TOKEN_CHUNK, workers.size());
  584. std::atomic<int> counter(0);
  585. auto compute = [&counter, &eval_pairs, &eval_results, batch_logits, n_vocab] () {
  586. float local_logprobs[K_TOKEN_CHUNK];
  587. while (true) {
  588. size_t first = counter.fetch_add(K_TOKEN_CHUNK, std::memory_order_relaxed);
  589. if (first >= eval_results.size()) break;
  590. size_t last = std::min(first + K_TOKEN_CHUNK, eval_results.size());
  591. for (size_t i = first; i < last; ++i) {
  592. auto logits = batch_logits + eval_pairs[i].first * n_vocab;
  593. float max_logit = logits[0];
  594. for (int j = 1; j < n_vocab; ++j) {
  595. max_logit = std::max(max_logit, logits[j]);
  596. }
  597. float sum_p = 0.f;
  598. for (int j = 0; j < n_vocab; ++j) {
  599. sum_p += expf(logits[j] - max_logit);
  600. }
  601. local_logprobs[i - first] = logits[eval_pairs[i].second] - max_logit - std::log(sum_p);
  602. }
  603. std::memcpy(eval_results.data() + first, local_logprobs, (last - first)*sizeof(float));
  604. }
  605. };
  606. for (size_t it = 0; it < max_threads; ++it) {
  607. workers[it] = std::thread(compute);
  608. }
  609. for (size_t it = 0; it < max_threads; ++it) {
  610. workers[it].join();
  611. }
  612. }
  613. static void hellaswag_score(llama_context * ctx, const gpt_params & params) {
  614. // Calculates hellaswag score (acc_norm) from prompt
  615. //
  616. // Data extracted from the HellaSwag validation dataset (MIT license) https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl
  617. // All used data fields are preprocessed as in https://github.com/EleutherAI/lm-evaluation-harness/blob/df3da98c5405deafd519c2ddca52bb7c3fe36bef/lm_eval/tasks/hellaswag.py#L62-L68
  618. //
  619. // All 10042 tasks should be extracted to keep the results standardized like other implementations.
  620. //
  621. // Datafile layout:
  622. // ['??'] denotes json fields
  623. // 6 lines per task:
  624. // ['activity_label'] + ": " +['ctx'] - The first part of the query, the context
  625. // ['label'] - The index the best common sense ending aka gold ending
  626. // ['endings'][0] - Endings added to the first part of the query
  627. // ['endings'][1]
  628. // ['endings'][2]
  629. // ['endings'][3]
  630. std::vector<std::string> prompt_lines;
  631. std::istringstream strstream(params.prompt);
  632. std::string line;
  633. while (std::getline(strstream,line,'\n')) {
  634. prompt_lines.push_back(line);
  635. }
  636. if (prompt_lines.size() % 6 != 0) {
  637. fprintf(stderr, "%s : number of lines in prompt not a multiple of 6.\n", __func__);
  638. return;
  639. }
  640. size_t hs_task_count = prompt_lines.size()/6;
  641. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, hs_task_count);
  642. const bool is_spm = llama_vocab_type(llama_get_model(ctx)) == LLAMA_VOCAB_TYPE_SPM;
  643. fprintf(stderr, "================================= is_spm = %d\n", is_spm);
  644. // This is needed as usual for LLaMA models
  645. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  646. // The tasks should be randomized so the score stabilizes quickly.
  647. bool randomize_tasks = true;
  648. // Number of tasks to use when computing the score
  649. if (params.hellaswag_tasks < hs_task_count) {
  650. hs_task_count = params.hellaswag_tasks;
  651. }
  652. // The random seed should not impact the final result if the computation is done over enough tasks, so kept hardcoded for now
  653. std::mt19937 rng(1);
  654. // Dataholder for hellaswag tasks
  655. struct hs_data_t {
  656. std::string context;
  657. size_t gold_ending_idx;
  658. std::string ending[4];
  659. size_t ending_logprob_count[4];
  660. double ending_logprob[4];
  661. size_t i_batch; // starting index in the llama_batch
  662. size_t common_prefix; // max number of initial tokens that are the same in all sentences
  663. size_t required_tokens; // needed number of tokens to evaluate all 4 endings
  664. std::vector<llama_token> seq_tokens[4];
  665. };
  666. fprintf(stderr, "%s : selecting %zu %s tasks.\n", __func__, hs_task_count, (randomize_tasks?"randomized":"the first") );
  667. // Select and read data from prompt lines
  668. std::vector<hs_data_t> hs_data(hs_task_count);
  669. for (size_t i = 0; i < hs_task_count; i++) {
  670. size_t idx = i;
  671. auto & hs_cur = hs_data[i];
  672. // Select a random example of those left in the prompt
  673. if (randomize_tasks) {
  674. std::uniform_int_distribution<size_t> dist(0, prompt_lines.size()/6-1 ) ;
  675. idx = dist(rng);
  676. }
  677. hs_cur.context = prompt_lines[idx*6];
  678. hs_cur.gold_ending_idx = std::stoi( prompt_lines[idx*6+1] );
  679. for (size_t j = 0; j < 4; j++) {
  680. hs_cur.ending[j] = prompt_lines[idx*6+2+j];
  681. hs_cur.seq_tokens[j] = ::llama_tokenize(ctx, hs_cur.context + " " + hs_cur.ending[j], add_bos);
  682. }
  683. // determine the common prefix of the endings
  684. hs_cur.common_prefix = 0;
  685. for (size_t k = 0; k < hs_cur.seq_tokens[0].size(); k++) {
  686. if (hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[1][k] ||
  687. hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[2][k] ||
  688. hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[3][k]) {
  689. break;
  690. }
  691. hs_cur.common_prefix++;
  692. }
  693. hs_cur.required_tokens = hs_cur.common_prefix +
  694. hs_cur.seq_tokens[0].size() - hs_cur.common_prefix +
  695. hs_cur.seq_tokens[1].size() - hs_cur.common_prefix +
  696. hs_cur.seq_tokens[2].size() - hs_cur.common_prefix +
  697. hs_cur.seq_tokens[3].size() - hs_cur.common_prefix;
  698. //GGML_ASSERT(hs_cur.common_prefix >= ::llama_tokenize(ctx, hs_cur.context, add_bos).size());
  699. // Delete the selected random example from the prompt
  700. if (randomize_tasks) {
  701. prompt_lines.erase( std::next(prompt_lines.begin(),idx*6) , std::next(prompt_lines.begin(),idx*6+6) );
  702. }
  703. }
  704. fprintf(stderr, "%s : calculating hellaswag score over selected tasks.\n", __func__);
  705. printf("\ntask\tacc_norm\n");
  706. double acc = 0.0f;
  707. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  708. const int n_ctx = llama_n_ctx(ctx);
  709. const int n_batch = params.n_batch;
  710. const int max_tasks_per_batch = 32;
  711. const int max_seq = std::min(4*max_tasks_per_batch, (int) llama_n_seq_max(ctx));
  712. llama_batch batch = llama_batch_init(n_ctx, 0, max_seq);
  713. std::vector<float> tok_logits(n_vocab);
  714. std::vector<float> batch_logits(n_vocab*n_ctx);
  715. std::vector<std::pair<size_t, llama_token>> eval_pairs;
  716. std::vector<float> eval_results;
  717. std::vector<std::thread> workers(std::thread::hardware_concurrency());
  718. for (size_t i0 = 0; i0 < hs_task_count; i0++) {
  719. int n_cur = 0;
  720. size_t i1 = i0;
  721. size_t i_batch = 0; // this tells us where in `llama_batch` we are currently
  722. llama_batch_clear(batch);
  723. // batch as much tasks as possible into the available context
  724. // each task has 4 unique seuqnce ids - one for each ending
  725. // the common prefix is shared among the 4 sequences to save tokens
  726. // we extract logits only from the last common token and from all ending tokens of each sequence
  727. while (n_cur + (int) hs_data[i1].required_tokens <= n_ctx) {
  728. auto & hs_cur = hs_data[i1];
  729. const int s0 = 4*(i1 - i0);
  730. if (s0 + 4 > max_seq) {
  731. break;
  732. }
  733. for (size_t i = 0; i < hs_cur.common_prefix; ++i) {
  734. llama_batch_add(batch, hs_cur.seq_tokens[0][i], i, { s0 + 0, s0 + 1, s0 + 2, s0 + 3}, false);
  735. }
  736. batch.logits[batch.n_tokens - 1] = true; // we need logits for the last token of the common prefix
  737. for (int s = 0; s < 4; ++s) {
  738. for (size_t i = hs_cur.common_prefix; i < hs_cur.seq_tokens[s].size(); ++i) {
  739. llama_batch_add(batch, hs_cur.seq_tokens[s][i], i, { s0 + s }, true);
  740. }
  741. }
  742. hs_cur.i_batch = i_batch;
  743. i_batch += hs_cur.required_tokens;
  744. n_cur += hs_data[i1].required_tokens;
  745. if (++i1 == hs_task_count) {
  746. break;
  747. }
  748. }
  749. if (i0 == i1) {
  750. fprintf(stderr, "%s : task %zu does not fit in the context window\n", __func__, i0);
  751. return;
  752. }
  753. llama_kv_cache_clear(ctx);
  754. // decode all tasks [i0, i1)
  755. if (!decode_helper(ctx, batch, batch_logits, n_batch, n_vocab)) {
  756. fprintf(stderr, "%s: llama_decode() failed\n", __func__);
  757. return;
  758. }
  759. // Compute log-probs in parallel
  760. // First we collect all tasks
  761. eval_pairs.clear();
  762. for (size_t i = i0; i < i1; ++i) {
  763. auto & hs_cur = hs_data[i];
  764. size_t li = hs_cur.common_prefix;
  765. for (int s = 0; s < 4; ++s) {
  766. for (size_t j = hs_cur.common_prefix; j < hs_cur.seq_tokens[s].size() - 1; j++) {
  767. eval_pairs.emplace_back(hs_cur.i_batch + li++, hs_cur.seq_tokens[s][j + 1]);
  768. }
  769. ++li;
  770. }
  771. }
  772. // Then we do the actual calculation
  773. compute_logprobs(batch_logits.data(), n_vocab, workers, eval_pairs, eval_results);
  774. size_t ir = 0;
  775. // compute the logprobs for each ending of the decoded tasks
  776. for (size_t i = i0; i < i1; ++i) {
  777. auto & hs_cur = hs_data[i];
  778. std::memcpy(tok_logits.data(), batch_logits.data() + n_vocab*(hs_cur.i_batch + hs_cur.common_prefix - 1), n_vocab*sizeof(float));
  779. const auto first_probs = softmax(tok_logits);
  780. for (int s = 0; s < 4; ++s) {
  781. hs_cur.ending_logprob_count[s] = 1;
  782. hs_cur.ending_logprob[s] = std::log(first_probs[hs_cur.seq_tokens[s][hs_cur.common_prefix]]);
  783. for (size_t j = hs_cur.common_prefix; j < hs_cur.seq_tokens[s].size() - 1; j++) {
  784. hs_cur.ending_logprob[s] += eval_results[ir++];
  785. hs_cur.ending_logprob_count[s]++;
  786. }
  787. hs_cur.ending_logprob[s] /= hs_cur.ending_logprob_count[s];
  788. }
  789. // Find the ending with maximum logprob
  790. size_t ending_logprob_max_idx = 0;
  791. double ending_logprob_max_val = hs_cur.ending_logprob[0];
  792. for (size_t s = 1; s < 4; s++) {
  793. if (hs_cur.ending_logprob[s] > ending_logprob_max_val) {
  794. ending_logprob_max_idx = s;
  795. ending_logprob_max_val = hs_cur.ending_logprob[s];
  796. }
  797. }
  798. //printf("max logprob ending idx %lu, gold ending idx %lu\n", ending_logprob_max_idx, hs_cur.gold_ending_idx);
  799. // If the gold ending got the maximum logprobe add one accuracy point
  800. if (ending_logprob_max_idx == hs_cur.gold_ending_idx) {
  801. acc += 1.0;
  802. }
  803. // Print the accumulated accuracy mean x 100
  804. printf("%zu\t%.8lf\n", i + 1, acc/double(i + 1)*100.0);
  805. fflush(stdout);
  806. }
  807. i0 = i1 - 1;
  808. }
  809. llama_batch_free(batch);
  810. printf("\n");
  811. }
  812. struct winogrande_entry {
  813. std::string first;
  814. std::string second;
  815. std::array<std::string, 2> choices;
  816. int answer;
  817. size_t i_batch;
  818. size_t common_prefix;
  819. size_t required_tokens;
  820. size_t n_base1; // number of tokens for context + choice 1
  821. size_t n_base2; // number of tokens for context + choice 2
  822. std::vector<llama_token> seq_tokens[2];
  823. };
  824. static std::vector<winogrande_entry> load_winogrande_from_csv(const std::string& prompt) {
  825. std::vector<winogrande_entry> result;
  826. std::istringstream in(prompt);
  827. std::string line;
  828. std::array<int, 4> comma_pos;
  829. while (true) {
  830. std::getline(in, line);
  831. if (in.fail() || in.eof()) break;
  832. int ipos = 0;
  833. bool quote_open = false;
  834. for (int i = 0; i < int(line.size()); ++i) {
  835. if (!quote_open) {
  836. if (line[i] == ',') {
  837. comma_pos[ipos++] = i;
  838. if (ipos == 4) break;
  839. }
  840. else if (line[i] == '"') {
  841. quote_open = true;
  842. }
  843. }
  844. else {
  845. if (line[i] == '"') {
  846. quote_open = false;
  847. }
  848. }
  849. }
  850. if (ipos != 4) {
  851. printf("%s: failed to find comma separators in <%s>\n", __func__, line.c_str());
  852. continue;
  853. }
  854. auto sentence = line[comma_pos[0]+1] == '"' ? line.substr(comma_pos[0]+2, comma_pos[1] - comma_pos[0] - 3)
  855. : line.substr(comma_pos[0]+1, comma_pos[1] - comma_pos[0] - 1);
  856. auto choice1 = line.substr(comma_pos[1]+1, comma_pos[2] - comma_pos[1] - 1);
  857. auto choice2 = line.substr(comma_pos[2]+1, comma_pos[3] - comma_pos[2] - 1);
  858. auto answer = line.substr(comma_pos[3]+1, line.size() - comma_pos[3] - 1);
  859. auto index = line.substr(0, comma_pos[0]);
  860. int where = 0;
  861. for ( ; where < int(sentence.size()); ++where) {
  862. if (sentence[where] == '_') break;
  863. }
  864. if (where == int(sentence.size())) {
  865. printf("%s: no _ in <%s>\n", __func__, sentence.c_str());
  866. continue;
  867. }
  868. std::istringstream stream(answer.c_str());
  869. int i_answer; stream >> i_answer;
  870. if (stream.fail() || i_answer < 1 || i_answer > 2) {
  871. printf("%s: failed to parse answer <%s>\n", __func__, answer.c_str());
  872. continue;
  873. }
  874. result.emplace_back();
  875. auto& wg = result.back();
  876. wg.first = sentence.substr(0, where);
  877. wg.second = sentence.substr(where + 1, sentence.size() - where - 1);
  878. wg.choices[0] = std::move(choice1);
  879. wg.choices[1] = std::move(choice2);
  880. wg.answer = i_answer;
  881. }
  882. return result;
  883. }
  884. /*
  885. * Evaluates the Winogrande score.
  886. * Uses a CSV containing task index, dentence, choice 1, choice 2, answer (1 or 2)
  887. * You can get one such dataset from e.g. https://huggingface.co/datasets/ikawrakow/winogrande-eval-for-llama.cpp
  888. * As an example, the 1st row in the above dataset is
  889. *
  890. * 0,Sarah was a much better surgeon than Maria so _ always got the easier cases.,Sarah,Maria,2
  891. *
  892. */
  893. static void winogrande_score(llama_context * ctx, const gpt_params & params) {
  894. constexpr int k_min_trailing_ctx = 3;
  895. auto data = load_winogrande_from_csv(params.prompt);
  896. if (data.empty()) {
  897. fprintf(stderr, "%s: no tasks\n", __func__);
  898. return;
  899. }
  900. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, data.size());
  901. if (params.winogrande_tasks > 0 && params.winogrande_tasks < data.size()) {
  902. fprintf(stderr, "%s : selecting %zu random tasks\n", __func__, params.winogrande_tasks);
  903. std::mt19937 rng(1);
  904. std::vector<int> aux(data.size());
  905. for (int i = 0; i < int(data.size()); ++i) {
  906. aux[i] = i;
  907. }
  908. float scale = 1/(1.f + (float)rng.max());
  909. std::vector<winogrande_entry> selected;
  910. selected.resize(params.winogrande_tasks);
  911. for (int i = 0; i < int(params.winogrande_tasks); ++i) {
  912. int j = int(scale*rng()*aux.size());
  913. selected[i] = std::move(data[aux[j]]);
  914. aux[j] = aux.back();
  915. aux.pop_back();
  916. }
  917. data = std::move(selected);
  918. }
  919. fprintf(stderr, "%s : tokenizing selected tasks\n", __func__);
  920. // This is needed as usual for LLaMA models
  921. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  922. for (auto & task : data) {
  923. task.seq_tokens[0] = ::llama_tokenize(ctx, task.first + task.choices[0] + task.second, add_bos);
  924. task.seq_tokens[1] = ::llama_tokenize(ctx, task.first + task.choices[1] + task.second, add_bos);
  925. task.common_prefix = 0;
  926. for (size_t k = 0; k < task.seq_tokens[0].size(); k++) {
  927. if (task.seq_tokens[0][k] != task.seq_tokens[1][k]) {
  928. break;
  929. }
  930. task.common_prefix++;
  931. }
  932. task.required_tokens = task.common_prefix +
  933. task.seq_tokens[0].size() - task.common_prefix +
  934. task.seq_tokens[1].size() - task.common_prefix;
  935. task.n_base1 = ::llama_tokenize(ctx, task.first + task.choices[0], add_bos).size();
  936. task.n_base2 = ::llama_tokenize(ctx, task.first + task.choices[1], add_bos).size();
  937. }
  938. fprintf(stderr, "%s : calculating winogrande score over selected tasks.\n", __func__);
  939. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  940. const int n_ctx = llama_n_ctx(ctx);
  941. const int n_batch = params.n_batch;
  942. const int max_tasks_per_batch = 128;
  943. const int max_seq = std::min(2*max_tasks_per_batch, (int) llama_n_seq_max(ctx));
  944. llama_batch batch = llama_batch_init(n_ctx, 0, max_seq);
  945. std::vector<float> tok_logits(n_vocab);
  946. std::vector<float> batch_logits(n_vocab*n_ctx);
  947. std::vector<std::pair<size_t, llama_token>> eval_pairs;
  948. std::vector<float> eval_results;
  949. std::vector<std::thread> workers(std::thread::hardware_concurrency());
  950. int n_correct = 0;
  951. int n_done = 0;
  952. for (size_t i0 = 0; i0 < data.size(); i0++) {
  953. int n_cur = 0;
  954. size_t i1 = i0;
  955. size_t i_batch = 0;
  956. llama_batch_clear(batch);
  957. while (n_cur + (int) data[i1].required_tokens <= n_ctx) {
  958. const int s0 = 2*(i1 - i0);
  959. if (s0 + 2 > max_seq) {
  960. break;
  961. }
  962. for (size_t i = 0; i < data[i1].common_prefix; ++i) {
  963. llama_batch_add(batch, data[i1].seq_tokens[0][i], i, { s0 + 0, s0 + 1}, false);
  964. }
  965. batch.logits[batch.n_tokens - 1] = true;
  966. for (int s = 0; s < 2; ++s) {
  967. for (size_t i = data[i1].common_prefix; i < data[i1].seq_tokens[s].size(); ++i) {
  968. llama_batch_add(batch, data[i1].seq_tokens[s][i], i, { s0 + s }, true);
  969. }
  970. }
  971. data[i1].i_batch = i_batch;
  972. i_batch += data[i1].required_tokens;
  973. n_cur += data[i1].required_tokens;
  974. if (++i1 == data.size()) {
  975. break;
  976. }
  977. }
  978. if (i0 == i1) {
  979. fprintf(stderr, "%s : task %zu does not fit in the context window\n", __func__, i0);
  980. return;
  981. }
  982. llama_kv_cache_clear(ctx);
  983. // decode all tasks [i0, i1)
  984. if (!decode_helper(ctx, batch, batch_logits, n_batch, n_vocab)) {
  985. fprintf(stderr, "%s: llama_decode() failed\n", __func__);
  986. return;
  987. }
  988. eval_pairs.clear();
  989. for (size_t i = i0; i < i1; ++i) {
  990. auto & task = data[i];
  991. const bool skip_choice =
  992. task.seq_tokens[0].size() - task.common_prefix > k_min_trailing_ctx &&
  993. task.seq_tokens[1].size() - task.common_prefix > k_min_trailing_ctx;
  994. const auto& n_base1 = skip_choice ? task.n_base1 : task.common_prefix;
  995. const int last_1st = task.seq_tokens[0].size() - n_base1 > 1 ? 1 : 0;
  996. size_t li = n_base1 - 1;
  997. for (size_t j = n_base1-1; j < task.seq_tokens[0].size()-1-last_1st; ++j) {
  998. eval_pairs.emplace_back(task.i_batch + li++, task.seq_tokens[0][j+1]);
  999. }
  1000. const auto& n_base2 = skip_choice ? task.n_base2 : task.common_prefix;
  1001. const int last_2nd = task.seq_tokens[1].size() - n_base2 > 1 ? 1 : 0;
  1002. li = task.seq_tokens[0].size() - task.common_prefix + n_base2 - 1;
  1003. for (size_t j = n_base2-1; j < task.seq_tokens[1].size()-1-last_2nd; ++j) {
  1004. eval_pairs.emplace_back(task.i_batch + li++, task.seq_tokens[1][j+1]);
  1005. }
  1006. }
  1007. compute_logprobs(batch_logits.data(), n_vocab, workers, eval_pairs, eval_results);
  1008. size_t ir = 0;
  1009. for (size_t i = i0; i < i1; ++i) {
  1010. auto & task = data[i];
  1011. const bool skip_choice =
  1012. task.seq_tokens[0].size() - task.common_prefix > k_min_trailing_ctx &&
  1013. task.seq_tokens[1].size() - task.common_prefix > k_min_trailing_ctx;
  1014. float score_1st = 0;
  1015. const auto& n_base1 = skip_choice ? task.n_base1 : task.common_prefix;
  1016. const int last_1st = task.seq_tokens[0].size() - n_base1 > 1 ? 1 : 0;
  1017. for (size_t j = n_base1-1; j < task.seq_tokens[0].size()-1-last_1st; ++j) {
  1018. score_1st += eval_results[ir++];
  1019. }
  1020. score_1st /= (task.seq_tokens[0].size() - n_base1 - last_1st);
  1021. float score_2nd = 0;
  1022. const auto& n_base2 = skip_choice ? task.n_base2 : task.common_prefix;
  1023. const int last_2nd = task.seq_tokens[1].size() - n_base2 > 1 ? 1 : 0;
  1024. for (size_t j = n_base2-1; j < task.seq_tokens[1].size()-1-last_2nd; ++j) {
  1025. score_2nd += eval_results[ir++];
  1026. }
  1027. score_2nd /= (task.seq_tokens[1].size() - n_base2 - last_2nd);
  1028. int result = score_1st > score_2nd ? 1 : 2;
  1029. if (result == task.answer) {
  1030. ++n_correct;
  1031. }
  1032. ++n_done;
  1033. // print the accumulated accuracy mean x 100
  1034. 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);
  1035. fflush(stdout);
  1036. }
  1037. i0 = i1 - 1;
  1038. }
  1039. printf("\n");
  1040. if (n_done < 100) return;
  1041. const float p = 1.f*n_correct/n_done;
  1042. const float sigma = 100.f*sqrt(p*(1-p)/(n_done-1));
  1043. printf("Final Winogrande score(%d tasks): %.4lf +/- %.4lf\n", n_done, 100*p, sigma);
  1044. }
  1045. static bool deserialize_string(std::istream & in, std::string & str) {
  1046. uint32_t size;
  1047. if (!in.read((char *)&size, sizeof(size)).fail()) {
  1048. str.resize(size);
  1049. if (!in.read((char *)&str[0], size).fail()) return true;
  1050. }
  1051. return false;
  1052. }
  1053. struct multiple_choice_answers {
  1054. std::vector<std::string> answers;
  1055. std::vector<int> labels;
  1056. bool deserialize(std::istream& in) {
  1057. uint32_t n;
  1058. in.read((char *)&n, sizeof(n));
  1059. if (in.fail() || n > 100) return false; // 100 as max. number of answers should be good enough for any practical purpose
  1060. answers.resize(n);
  1061. labels.resize(n);
  1062. for (auto& a : answers) {
  1063. if (!deserialize_string(in, a)) return false;
  1064. }
  1065. in.read((char *)labels.data(), n*sizeof(int));
  1066. return !in.fail();
  1067. }
  1068. };
  1069. struct multiple_choice_task {
  1070. std::string question; // the question (or context that needs to be continued)
  1071. multiple_choice_answers mc1; // possible answers (continuations) with a single correct answer
  1072. multiple_choice_answers mc2; // possible answers (continuations) with multiple correct answers - not handled yet
  1073. bool deserialize(std::istream& in) {
  1074. if (!deserialize_string(in, question)) return false;
  1075. return mc1.deserialize(in) && mc2.deserialize(in);
  1076. }
  1077. // For evaluation
  1078. size_t i_batch; // starting index in the llama_batch
  1079. size_t common_prefix; // max number of initial tokens that are the same in all sentences
  1080. size_t required_tokens; // needed number of tokens to evaluate all answers
  1081. std::vector<std::vector<llama_token>> seq_tokens;
  1082. std::vector<float> log_probs;
  1083. };
  1084. static bool multiple_choice_prepare_one_task(llama_context * ctx, bool add_bos, multiple_choice_task& task, bool log_error) {
  1085. if (task.question.empty() || task.mc1.answers.empty()) {
  1086. if (log_error) {
  1087. printf("%s: found bad task with empty question and/or answers\n", __func__);
  1088. }
  1089. return false;
  1090. }
  1091. task.seq_tokens.reserve(task.mc1.answers.size());
  1092. for (auto& answer : task.mc1.answers) {
  1093. if (answer.empty()) {
  1094. if (log_error) {
  1095. printf("%s: found empty answer\n", __func__);
  1096. }
  1097. return false;
  1098. }
  1099. task.seq_tokens.emplace_back(::llama_tokenize(ctx, task.question + " " + answer, add_bos));
  1100. }
  1101. auto min_len = task.seq_tokens.front().size();
  1102. for (auto& seq : task.seq_tokens) {
  1103. min_len = std::min(min_len, seq.size());
  1104. }
  1105. task.common_prefix = 0;
  1106. for (size_t k = 0; k < min_len; ++k) {
  1107. auto token = task.seq_tokens[0][k];
  1108. bool all_same = true;
  1109. for (size_t i = 1; i < task.seq_tokens.size(); ++i) {
  1110. if (task.seq_tokens[i][k] != token) {
  1111. all_same = false;
  1112. break;
  1113. }
  1114. }
  1115. if (!all_same) {
  1116. break;
  1117. }
  1118. ++task.common_prefix;
  1119. }
  1120. task.required_tokens = task.common_prefix;
  1121. for (auto& seq : task.seq_tokens) {
  1122. task.required_tokens += seq.size() - task.common_prefix;
  1123. }
  1124. return true;
  1125. }
  1126. //
  1127. // Calculates score for multiple choice tasks with single correct answer from prompt.
  1128. // Commonly used LLM evaluation metrics of this type are
  1129. // * ARC
  1130. // * HellaSwag
  1131. // * MMLU
  1132. // * TruthfulQA
  1133. //
  1134. // Validation datasets for these 4 tests can be found at
  1135. // https://huggingface.co/datasets/ikawrakow/validation-datasets-for-llama.cpp
  1136. // The data for these datasets was extracted from
  1137. // git@hf.co:datasets/allenai/ai2_arc
  1138. // https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl
  1139. // git@hf.co:datasets/Stevross/mmlu
  1140. // https://huggingface.co/datasets/truthful_qa
  1141. //
  1142. static void multiple_choice_score(llama_context * ctx, const gpt_params & params) {
  1143. std::istringstream strstream(params.prompt);
  1144. uint32_t n_task;
  1145. strstream.read((char *)&n_task, sizeof(n_task));
  1146. if (strstream.fail() || n_task == 0) {
  1147. printf("%s: no tasks\n", __func__);
  1148. return;
  1149. }
  1150. printf("%s: there are %u tasks in prompt\n", __func__, n_task);
  1151. std::vector<uint32_t> task_pos(n_task);
  1152. strstream.read((char *)task_pos.data(), task_pos.size()*sizeof(uint32_t));
  1153. if (strstream.fail()) {
  1154. printf("%s: failed to raad task positions from prompt\n", __func__);
  1155. return;
  1156. }
  1157. std::vector<multiple_choice_task> tasks;
  1158. if (params.multiple_choice_tasks == 0 || params.multiple_choice_tasks >= (size_t)n_task) {
  1159. // Use all tasks
  1160. tasks.resize(n_task);
  1161. printf("%s: reading tasks", __func__);
  1162. int n_dot = n_task/100;
  1163. int i = 0;
  1164. for (auto& task : tasks) {
  1165. ++i;
  1166. if (!task.deserialize(strstream)) {
  1167. printf("%s: failed to read task %d of %u\n", __func__, i, n_task);
  1168. return;
  1169. }
  1170. if (i%n_dot == 0) printf(".");
  1171. }
  1172. printf("done\n");
  1173. }
  1174. else {
  1175. printf("%s: selecting %zu random tasks from %u tasks available\n", __func__, params.multiple_choice_tasks, n_task);
  1176. std::mt19937 rng(1);
  1177. std::vector<int> aux(n_task);
  1178. for (uint32_t i = 0; i < n_task; ++i) aux[i] = i;
  1179. float scale = 1.f/(1.f + (float)std::mt19937::max());
  1180. tasks.resize(params.multiple_choice_tasks);
  1181. for (auto& task : tasks) {
  1182. int j = (int)(scale * rng() * aux.size());
  1183. int idx = aux[j];
  1184. aux[j] = aux.back();
  1185. aux.pop_back();
  1186. strstream.seekg(task_pos[idx], std::ios::beg);
  1187. if (!task.deserialize(strstream)) {
  1188. printf("%s: failed to read task %d at position %u\n", __func__, idx, task_pos[idx]);
  1189. return;
  1190. }
  1191. }
  1192. n_task = params.multiple_choice_tasks;
  1193. }
  1194. // This is needed as usual for LLaMA models
  1195. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  1196. printf("%s: preparing task data", __func__);
  1197. fflush(stdout);
  1198. if (n_task > 500) {
  1199. printf("...");
  1200. fflush(stdout);
  1201. std::atomic<int> counter(0);
  1202. std::atomic<int> n_bad(0);
  1203. auto prepare = [&counter, &n_bad, &tasks, ctx, add_bos] () {
  1204. int num_tasks = tasks.size();
  1205. int n_bad_local = 0;
  1206. while (true) {
  1207. int first = counter.fetch_add(K_TOKEN_CHUNK);
  1208. if (first >= num_tasks) {
  1209. if (n_bad_local > 0) n_bad += n_bad_local;
  1210. break;
  1211. }
  1212. int last = std::min(first + K_TOKEN_CHUNK, num_tasks);
  1213. for (int i = first; i < last; ++i) {
  1214. if (!multiple_choice_prepare_one_task(ctx, add_bos, tasks[i], false)) ++n_bad_local;
  1215. }
  1216. }
  1217. };
  1218. size_t max_thread = std::thread::hardware_concurrency();
  1219. max_thread = std::min(max_thread, (tasks.size() + K_TOKEN_CHUNK - 1)/K_TOKEN_CHUNK);
  1220. std::vector<std::thread> workers(max_thread-1);
  1221. for (auto& w : workers) w = std::thread(prepare);
  1222. prepare();
  1223. for (auto& w : workers) w.join();
  1224. printf("done\n");
  1225. fflush(stdout);
  1226. int nbad = n_bad;
  1227. if (nbad > 0) {
  1228. printf("%s: found %d malformed tasks\n", __func__, nbad);
  1229. return;
  1230. }
  1231. } else {
  1232. int n_dot = n_task/100;
  1233. int i_task = 0;
  1234. for (auto& task : tasks) {
  1235. ++i_task;
  1236. if (!multiple_choice_prepare_one_task(ctx, add_bos, task, true)) {
  1237. return;
  1238. }
  1239. if (i_task%n_dot == 0) {
  1240. printf(".");
  1241. fflush(stdout);
  1242. }
  1243. }
  1244. printf("done\n");
  1245. }
  1246. printf("%s : calculating TruthfulQA score over %zu tasks.\n", __func__, tasks.size());
  1247. printf("\ntask\tacc_norm\n");
  1248. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  1249. const int n_ctx = llama_n_ctx(ctx);
  1250. const int n_batch = params.n_batch;
  1251. const int max_tasks_per_batch = 32;
  1252. const int max_seq = std::min(4*max_tasks_per_batch, (int) llama_n_seq_max(ctx));
  1253. llama_batch batch = llama_batch_init(n_ctx, 0, max_seq);
  1254. std::vector<float> tok_logits(n_vocab);
  1255. std::vector<float> batch_logits(n_vocab*n_ctx);
  1256. std::vector<std::pair<size_t, llama_token>> eval_pairs;
  1257. std::vector<float> eval_results;
  1258. std::vector<std::thread> workers(std::thread::hardware_concurrency());
  1259. std::vector<int> batch_indeces;
  1260. int n_done = 0;
  1261. int n_correct = 0;
  1262. int n_tot_answers = 0;
  1263. for (size_t i0 = 0; i0 < tasks.size(); i0++) {
  1264. int n_cur = 0;
  1265. size_t i1 = i0;
  1266. size_t i_batch = 0; // this tells us where in `llama_batch` we are currently
  1267. llama_batch_clear(batch);
  1268. // batch as much tasks as possible into the available context
  1269. // each task has 4 unique seuqnce ids - one for each ending
  1270. // the common prefix is shared among the 4 sequences to save tokens
  1271. // we extract logits only from the last common token and from all ending tokens of each sequence
  1272. int s0 = 0;
  1273. while (n_cur + (int) tasks[i1].required_tokens <= n_ctx) {
  1274. auto& cur_task = tasks[i1];
  1275. int num_answers = cur_task.seq_tokens.size();
  1276. if (s0 + num_answers > max_seq) {
  1277. break;
  1278. }
  1279. if (int(batch_indeces.size()) != num_answers) {
  1280. batch_indeces.resize(num_answers);
  1281. }
  1282. for (int s = 0; s < num_answers; ++s) batch_indeces[s] = s0 + s;
  1283. for (size_t i = 0; i < cur_task.common_prefix; ++i) {
  1284. //llama_batch_add(batch, cur_task.seq_tokens[0][i], i, { s0 + 0, s0 + 1, s0 + 2, s0 + 3}, false);
  1285. llama_batch_add(batch, cur_task.seq_tokens[0][i], i, batch_indeces, false);
  1286. }
  1287. batch.logits[batch.n_tokens - 1] = true; // we need logits for the last token of the common prefix
  1288. for (int s = 0; s < int(cur_task.seq_tokens.size()); ++s) {
  1289. for (size_t i = cur_task.common_prefix; i < cur_task.seq_tokens[s].size(); ++i) {
  1290. llama_batch_add(batch, cur_task.seq_tokens[s][i], i, { s0 + s }, true);
  1291. }
  1292. }
  1293. s0 += num_answers;
  1294. cur_task.i_batch = i_batch;
  1295. i_batch += cur_task.required_tokens;
  1296. n_cur += cur_task.required_tokens;
  1297. if (++i1 == tasks.size()) {
  1298. break;
  1299. }
  1300. }
  1301. if (i0 == i1) {
  1302. fprintf(stderr, "%s : task %zu does not fit in the context window\n", __func__, i0);
  1303. return;
  1304. }
  1305. llama_kv_cache_clear(ctx);
  1306. // decode all tasks [i0, i1)
  1307. if (!decode_helper(ctx, batch, batch_logits, n_batch, n_vocab)) {
  1308. fprintf(stderr, "%s: llama_decode() failed\n", __func__);
  1309. return;
  1310. }
  1311. // Compute log-probs in parallel
  1312. // First we collect all tasks
  1313. eval_pairs.clear();
  1314. for (size_t i = i0; i < i1; ++i) {
  1315. auto& cur_task = tasks[i];
  1316. size_t li = cur_task.common_prefix;
  1317. for (int s = 0; s < int(cur_task.seq_tokens.size()); ++s) {
  1318. for (size_t j = cur_task.common_prefix; j < cur_task.seq_tokens[s].size() - 1; j++) {
  1319. eval_pairs.emplace_back(cur_task.i_batch + li++, cur_task.seq_tokens[s][j + 1]);
  1320. }
  1321. ++li;
  1322. }
  1323. }
  1324. // Then we do the actual calculation
  1325. compute_logprobs(batch_logits.data(), n_vocab, workers, eval_pairs, eval_results);
  1326. size_t ir = 0;
  1327. // compute the logprobs for each ending of the decoded tasks
  1328. for (size_t i = i0; i < i1; ++i) {
  1329. auto & cur_task = tasks[i];
  1330. //printf("==== Evaluating <%s> with correct answer ", cur_task.question.c_str());
  1331. //for (int j = 0; j < int(cur_task.mc1.labels.size()); ++j) {
  1332. // if (cur_task.mc1.labels[j] == 1) {
  1333. // printf("%d", j+1);
  1334. // }
  1335. //}
  1336. //printf("\n common_prefix: %zu\n", cur_task.common_prefix);
  1337. std::memcpy(tok_logits.data(), batch_logits.data() + n_vocab*(cur_task.i_batch + cur_task.common_prefix - 1), n_vocab*sizeof(float));
  1338. const auto first_probs = softmax(tok_logits);
  1339. cur_task.log_probs.resize(cur_task.seq_tokens.size());
  1340. for (int s = 0; s < int(cur_task.seq_tokens.size()); ++s) {
  1341. size_t count = 1;
  1342. float log_prob = std::log(first_probs[cur_task.seq_tokens[s][cur_task.common_prefix]]);
  1343. for (size_t j = cur_task.common_prefix; j < cur_task.seq_tokens[s].size() - 1; j++) {
  1344. //printf(" %zu %g\n", ir, eval_results[ir]);
  1345. ++count;
  1346. log_prob += eval_results[ir++];
  1347. }
  1348. cur_task.log_probs[s] = log_prob / count;
  1349. //printf(" Final: %g\n", log_prob / count);
  1350. //printf(" <%s> : %g\n", cur_task.mc1.answers[s].c_str(), log_prob/count);
  1351. }
  1352. // Find the ending with maximum logprob
  1353. size_t logprob_max_idx = 0;
  1354. float logprob_max_val = cur_task.log_probs[0];
  1355. for (size_t s = 1; s < cur_task.log_probs.size(); s++) {
  1356. if (cur_task.log_probs[s] > logprob_max_val) {
  1357. logprob_max_val = cur_task.log_probs[s];
  1358. logprob_max_idx = s;
  1359. }
  1360. }
  1361. n_tot_answers += cur_task.log_probs.size();
  1362. if (cur_task.mc1.labels[logprob_max_idx] == 1) {
  1363. ++n_correct;
  1364. }
  1365. ++n_done;
  1366. // Print the accumulated accuracy mean x 100
  1367. printf("%d\t%.8lf\n", n_done, 100.*n_correct/n_done);
  1368. fflush(stdout);
  1369. }
  1370. i0 = i1 - 1;
  1371. }
  1372. llama_batch_free(batch);
  1373. if (n_done < 100) return;
  1374. float p = 1.f*n_correct/n_done;
  1375. float sigma = sqrt(p*(1-p)/(n_done-1));
  1376. printf("\n Final result: %.4f +/- %.4f\n", 100.f*p, 100.f*sigma);
  1377. p = 1.f*n_done/n_tot_answers;
  1378. sigma = sqrt(p*(1-p)/(n_done-1));
  1379. printf("Random chance: %.4f +/- %.4f\n", 100.f*p, 100.f*sigma);
  1380. printf("\n");
  1381. }
  1382. static void kl_divergence(llama_context * ctx, const gpt_params & params) {
  1383. if (params.logits_file.empty()) {
  1384. fprintf(stderr, "%s: you must provide a name of a file containing the log probabilities of the base model\n", __func__);
  1385. return;
  1386. }
  1387. std::ifstream in(params.logits_file.c_str(), std::ios::binary);
  1388. if (!in) {
  1389. fprintf(stderr, "%s: failed to open %s\n", __func__, params.logits_file.c_str());
  1390. return;
  1391. }
  1392. {
  1393. char check[9]; check[8] = 0;
  1394. in.read(check, 8);
  1395. if (in.fail() || strncmp("_logits_", check, 8) != 0) {
  1396. fprintf(stderr, "%s: %s does not look like a file containing log-probabilities\n", __func__, params.logits_file.c_str());
  1397. return;
  1398. }
  1399. }
  1400. uint32_t n_ctx;
  1401. in.read((char *)&n_ctx, sizeof(n_ctx));
  1402. if (n_ctx > llama_n_ctx(ctx)) {
  1403. fprintf(stderr, "%s: %s has been computed with %u, while the current context is %d. Increase it with -c and retry\n",
  1404. __func__, params.logits_file.c_str(), n_ctx, params.n_ctx);
  1405. }
  1406. int n_vocab, n_chunk;
  1407. in.read((char *)&n_vocab, sizeof(n_vocab));
  1408. in.read((char *)&n_chunk, sizeof(n_chunk));
  1409. if (in.fail()) {
  1410. fprintf(stderr, "%s: failed reading n_vocab, n_chunk from %s\n", __func__, params.logits_file.c_str());
  1411. return;
  1412. }
  1413. if (n_vocab != llama_n_vocab(llama_get_model(ctx))) {
  1414. fprintf(stderr, "%s: inconsistent vocabulary (%d vs %d)\n", __func__, n_vocab, llama_n_vocab(llama_get_model(ctx)));
  1415. }
  1416. std::vector<llama_token> tokens(n_ctx * n_chunk);
  1417. if (in.read((char *)tokens.data(), tokens.size()*sizeof(tokens[0])).fail()) {
  1418. fprintf(stderr, "%s: failed reading evaluation tokens from %s\n", __func__, params.logits_file.c_str());
  1419. return;
  1420. }
  1421. const int n_batch = params.n_batch;
  1422. const int num_batches = (n_ctx + n_batch - 1)/n_batch;
  1423. const int nv = 2*((n_vocab + 1)/2) + 4;
  1424. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  1425. std::vector<uint16_t> log_probs_uint16(size_t(n_ctx - 1 - n_ctx/2) * nv);
  1426. std::vector<float> kld_values(size_t(n_ctx - 1 - n_ctx/2)*n_chunk);
  1427. std::vector<float> logits;
  1428. if (num_batches > 1) {
  1429. logits.reserve(n_ctx * n_vocab);
  1430. }
  1431. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  1432. auto mean_and_uncertainty = [] (double sum, double sum2, size_t count) {
  1433. if (count < 1) {
  1434. return std::make_pair(0., 0.);
  1435. }
  1436. double f = sum/count;
  1437. double df = sum2/count - f*f;
  1438. df = df > 0 && count > 10 ? sqrt(df/(count-1)) : 0.;
  1439. return std::make_pair(f, df);
  1440. };
  1441. kl_divergence_result kld;
  1442. auto kld_ptr = kld_values.data();
  1443. for (int i = 0; i < n_chunk; ++i) {
  1444. const int start = i * n_ctx;
  1445. const int end = start + n_ctx;
  1446. const auto t_start = std::chrono::high_resolution_clock::now();
  1447. if (in.read((char *)log_probs_uint16.data(), log_probs_uint16.size()*sizeof(uint16_t)).fail()) {
  1448. fprintf(stderr, "%s: failed reading log-probs for chunk %d\n", __func__, i);
  1449. return;
  1450. }
  1451. // clear the KV cache
  1452. llama_kv_cache_clear(ctx);
  1453. for (int j = 0; j < num_batches; ++j) {
  1454. const int batch_start = start + j * n_batch;
  1455. const int batch_size = std::min(end - batch_start, n_batch);
  1456. // save original token and restore it after eval
  1457. const auto token_org = tokens[batch_start];
  1458. // add BOS token for the first batch of each chunk
  1459. if (add_bos && j == 0) {
  1460. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  1461. }
  1462. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  1463. fprintf(stderr, "%s : failed to eval\n", __func__);
  1464. return;
  1465. }
  1466. // restore the original token in case it was set to BOS
  1467. tokens[batch_start] = token_org;
  1468. if (num_batches > 1) {
  1469. const auto * batch_logits = llama_get_logits(ctx);
  1470. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  1471. }
  1472. }
  1473. const auto t_end = std::chrono::high_resolution_clock::now();
  1474. if (i == 0) {
  1475. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  1476. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  1477. int total_seconds = (int)(t_total * n_chunk);
  1478. if (total_seconds >= 60*60) {
  1479. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  1480. total_seconds = total_seconds % (60*60);
  1481. }
  1482. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  1483. printf("\nchunk PPL ln(PPL(Q)/PPL(base)) KL-Divergence Same top\n");
  1484. }
  1485. const int first = n_ctx/2;
  1486. const float * all_logits = num_batches > 1 ? logits.data() : llama_get_logits(ctx);
  1487. process_logits(n_vocab, all_logits + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
  1488. workers, log_probs_uint16, kld, kld_ptr);
  1489. kld_ptr += n_ctx - 1 - first;
  1490. auto ppl = mean_and_uncertainty(kld.sum_nll, kld.sum_nll2, kld.count);
  1491. auto log_ppl_ratio = mean_and_uncertainty(kld.sum_nll_diff, kld.sum_nll_diff2, kld.count);
  1492. auto kl_div = mean_and_uncertainty(kld.sum_kld, kld.sum_kld2, kld.count);
  1493. auto p_top = 1.*kld.n_same_top/kld.count;
  1494. auto d_p_top = sqrt(p_top*(1 - p_top)/(kld.count - 1));
  1495. printf("%4d %10.4lf %10.5lf ± %10.5f %10.5f ± %10.5lf %.5f ± %.5f\n", i+1, exp(ppl.first),
  1496. log_ppl_ratio.first, log_ppl_ratio.second, kl_div.first, kl_div.second,
  1497. p_top, d_p_top);
  1498. fflush(stdout);
  1499. logits.clear();
  1500. }
  1501. printf("\n");
  1502. if (kld.count < 100) return; // we do not wish to do statistics on so few values
  1503. std::sort(kld_values.begin(), kld_values.end());
  1504. printf("===== KL-divergence statistics\n");
  1505. auto kl_div = mean_and_uncertainty(kld.sum_kld, kld.sum_kld2, kld.count);
  1506. printf("Average: %10.6f ±%10.6lf\n", kl_div.first, kl_div.second);
  1507. auto kld_median = kld_values.size()%2 == 0 ? 0.5f*(kld_values[kld_values.size()/2] + kld_values[kld_values.size()/2-1])
  1508. : kld_values[kld_values.size()/2];
  1509. printf("Median : %10.6f\n", kld_median);
  1510. auto percentile = [&kld_values] (float fraction) {
  1511. if (fraction <= 0) return kld_values.front();
  1512. if (fraction >= 1) return kld_values.back();
  1513. float p = fraction*(kld_values.size() - 1);
  1514. size_t ip = size_t(p); p -= ip;
  1515. return (1 - p)*kld_values[ip] + p*kld_values[std::min(ip+1, kld_values.size()-1)];
  1516. };
  1517. printf("Maximum: %10.6f\n", kld_values.back());
  1518. printf("KLD_99 : %10.6f\n", percentile(0.99f));
  1519. printf("KLD_95 : %10.6f\n", percentile(0.95f));
  1520. printf("KLD_90 : %10.6f\n", percentile(0.90f));
  1521. printf("Minimum: %10.6f\n", kld_values.front());
  1522. printf("KLD_01 : %10.6f\n", percentile(0.01f));
  1523. printf("KLD_05 : %10.6f\n", percentile(0.05f));
  1524. printf("KLD_10 : %10.6f\n", percentile(0.10f));
  1525. }
  1526. int main(int argc, char ** argv) {
  1527. gpt_params params;
  1528. if (!gpt_params_parse(argc, argv, params)) {
  1529. return 1;
  1530. }
  1531. params.logits_all = true;
  1532. const int32_t n_ctx = params.n_ctx;
  1533. const bool ppl = !params.hellaswag && !params.winogrande && !params.multiple_choice && !params.kl_divergence;
  1534. if (ppl) {
  1535. int n_seq = std::max(1, params.n_batch / n_ctx);
  1536. int32_t n_kv = n_seq * n_ctx;
  1537. params.n_parallel = n_seq;
  1538. params.n_ctx = n_kv;
  1539. params.n_batch = std::min(params.n_batch, n_kv);
  1540. } else {
  1541. params.n_batch = std::min(params.n_batch, params.n_ctx);
  1542. }
  1543. if (params.ppl_stride > 0) {
  1544. fprintf(stderr, "Will perform strided perplexity calculation -> adjusting context size from %d to %d\n",
  1545. params.n_ctx, params.n_ctx + params.ppl_stride/2);
  1546. params.n_ctx += params.ppl_stride/2;
  1547. }
  1548. print_build_info();
  1549. if (params.seed == LLAMA_DEFAULT_SEED) {
  1550. params.seed = time(NULL);
  1551. }
  1552. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  1553. std::mt19937 rng(params.seed);
  1554. if (params.random_prompt) {
  1555. params.prompt = gpt_random_prompt(rng);
  1556. }
  1557. llama_backend_init();
  1558. llama_numa_init(params.numa);
  1559. llama_model * model;
  1560. llama_context * ctx;
  1561. // ensure there's at least enough seq_ids for HellaSwag
  1562. params.n_parallel = std::max(4, params.n_parallel);
  1563. // load the model and apply lora adapter, if any
  1564. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  1565. if (model == NULL) {
  1566. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  1567. return 1;
  1568. }
  1569. const int n_ctx_train = llama_n_ctx_train(model);
  1570. if (params.n_ctx > n_ctx_train) {
  1571. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  1572. __func__, n_ctx_train, params.n_ctx);
  1573. }
  1574. // print system information
  1575. {
  1576. fprintf(stderr, "\n");
  1577. fprintf(stderr, "%s\n", get_system_info(params).c_str());
  1578. }
  1579. struct results_perplexity results;
  1580. if (params.hellaswag) {
  1581. hellaswag_score(ctx, params);
  1582. } else if (params.winogrande) {
  1583. winogrande_score(ctx, params);
  1584. } else if (params.multiple_choice) {
  1585. multiple_choice_score(ctx, params);
  1586. } else if (params.kl_divergence) {
  1587. kl_divergence(ctx, params);
  1588. } else {
  1589. results = perplexity(ctx, params, n_ctx);
  1590. }
  1591. llama_print_timings(ctx);
  1592. write_logfile(ctx, params, model, results);
  1593. llama_free(ctx);
  1594. llama_free_model(model);
  1595. llama_backend_free();
  1596. return 0;
  1597. }