perplexity.cpp 78 KB

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