perplexity.cpp 78 KB

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