perplexity.cpp 72 KB

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