perplexity.cpp 77 KB

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