1
0

perplexity.cpp 79 KB

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