1
0

perplexity.cpp 78 KB

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