perplexity.cpp 67 KB

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