perplexity.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <ctime>
  7. #include <sstream>
  8. #include <thread>
  9. #include <mutex>
  10. #include <atomic>
  11. #include <vector>
  12. #include <array>
  13. #include <fstream>
  14. #include <sstream>
  15. #if defined(_MSC_VER)
  16. #pragma warning(disable: 4244 4267) // possible loss of data
  17. #endif
  18. struct results_perplexity {
  19. std::vector<llama_token> tokens;
  20. double ppl_value;
  21. std::vector<float> logits;
  22. std::vector<float> probs;
  23. };
  24. struct results_log_softmax {
  25. double log_softmax;
  26. float logit;
  27. float prob;
  28. };
  29. static void write_logfile(
  30. const llama_context * ctx, const gpt_params & params, const llama_model * model,
  31. const struct results_perplexity & results
  32. ) {
  33. if (params.logdir.empty()) {
  34. return;
  35. }
  36. if (params.hellaswag) {
  37. fprintf(stderr, "%s: warning: logging results is not implemented for HellaSwag. No files will be written.\n", __func__);
  38. return;
  39. }
  40. const std::string timestamp = get_sortable_timestamp();
  41. const bool success = create_directory_with_parents(params.logdir);
  42. if (!success) {
  43. fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n",
  44. __func__, params.logdir.c_str());
  45. return;
  46. }
  47. const std::string logfile_path = params.logdir + timestamp + ".yml";
  48. FILE * logfile = fopen(logfile_path.c_str(), "w");
  49. if (logfile == NULL) {
  50. fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
  51. return;
  52. }
  53. fprintf(logfile, "binary: main\n");
  54. char model_desc[128];
  55. llama_model_desc(model, model_desc, sizeof(model_desc));
  56. dump_non_result_info_yaml(logfile, params, ctx, timestamp, results.tokens, model_desc);
  57. fprintf(logfile, "\n");
  58. fprintf(logfile, "######################\n");
  59. fprintf(logfile, "# Perplexity Results #\n");
  60. fprintf(logfile, "######################\n");
  61. fprintf(logfile, "\n");
  62. dump_vector_float_yaml(logfile, "logits", results.logits);
  63. fprintf(logfile, "ppl_value: %f\n", results.ppl_value);
  64. dump_vector_float_yaml(logfile, "probs", results.probs);
  65. llama_dump_timing_info_yaml(logfile, ctx);
  66. fclose(logfile);
  67. }
  68. static std::vector<float> softmax(const std::vector<float>& logits) {
  69. std::vector<float> probs(logits.size());
  70. float max_logit = logits[0];
  71. for (float v : logits) {
  72. max_logit = std::max(max_logit, v);
  73. }
  74. double sum_exp = 0.0;
  75. for (size_t i = 0; i < logits.size(); i++) {
  76. // Subtract the maximum logit value from the current logit value for numerical stability
  77. const float logit = logits[i] - max_logit;
  78. const float exp_logit = expf(logit);
  79. sum_exp += exp_logit;
  80. probs[i] = exp_logit;
  81. }
  82. for (size_t i = 0; i < probs.size(); i++) {
  83. probs[i] /= sum_exp;
  84. }
  85. return probs;
  86. }
  87. static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
  88. float max_logit = logits[0];
  89. for (int i = 1; i < n_vocab; ++i) {
  90. max_logit = std::max(max_logit, logits[i]);
  91. }
  92. double sum_exp = 0.0;
  93. for (int i = 0; i < n_vocab; ++i) {
  94. sum_exp += expf(logits[i] - max_logit);
  95. }
  96. return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
  97. }
  98. static 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 + 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 results_perplexity perplexity_v2(llama_context * ctx, const gpt_params & params) {
  132. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  133. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  134. // Output: `perplexity: 13.5106 [114/114]`
  135. // BOS tokens will be added for each chunk before eval
  136. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  137. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  138. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  139. const int n_ctx = llama_n_ctx(ctx);
  140. if (int(tokens.size()) < 2*n_ctx) {
  141. fprintf(stderr, "%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*n_ctx,
  142. n_ctx);
  143. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  144. return {std::move(tokens), 0., {}, {}};
  145. }
  146. std::vector<float> logit_history;
  147. std::vector<float> prob_history;
  148. logit_history.resize(tokens.size());
  149. prob_history.resize(tokens.size());
  150. if (params.ppl_stride <= 0) {
  151. fprintf(stderr, "%s: stride is %d but must be greater than zero!\n",__func__,params.ppl_stride);
  152. return {tokens, -1, logit_history, prob_history};
  153. }
  154. const int calc_chunk = n_ctx;
  155. fprintf(stderr, "%s: have %zu tokens. Calculation chunk = %d\n", __func__, tokens.size(), calc_chunk);
  156. if (int(tokens.size()) <= calc_chunk) {
  157. fprintf(stderr, "%s: there are only %zu tokens, this is not enough for a context size of %d and stride %d\n",__func__,
  158. tokens.size(), n_ctx, params.ppl_stride);
  159. return {tokens, -1, logit_history, prob_history};
  160. }
  161. const int n_chunk_max = (tokens.size() - calc_chunk + params.ppl_stride - 1) / params.ppl_stride;
  162. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  163. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  164. const int n_batch = params.n_batch;
  165. int count = 0;
  166. double nll = 0.0;
  167. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  168. for (int i = 0; i < n_chunk; ++i) {
  169. const int start = i * params.ppl_stride;
  170. const int end = start + calc_chunk;
  171. const int num_batches = (calc_chunk + n_batch - 1) / n_batch;
  172. //fprintf(stderr, "%s: evaluating %d...%d using %d batches\n", __func__, start, end, num_batches);
  173. std::vector<float> logits;
  174. const auto t_start = std::chrono::high_resolution_clock::now();
  175. // clear the KV cache
  176. llama_kv_cache_clear(ctx);
  177. for (int j = 0; j < num_batches; ++j) {
  178. const int batch_start = start + j * n_batch;
  179. const int batch_size = std::min(end - batch_start, n_batch);
  180. //fprintf(stderr, " Batch %d: starts at %d, size is %d, n_past is %d\n",j,batch_start,batch_size,j * n_batch);
  181. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  182. //fprintf(stderr, "%s : failed to eval\n", __func__);
  183. return {tokens, -1, logit_history, prob_history};
  184. }
  185. // save original token and restore it after eval
  186. const auto token_org = tokens[batch_start];
  187. // add BOS token for the first batch of each chunk
  188. if (add_bos && j == 0) {
  189. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  190. }
  191. const auto batch_logits = llama_get_logits(ctx);
  192. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  193. if (j == 0) {
  194. tokens[batch_start] = token_org;
  195. }
  196. }
  197. const auto t_end = std::chrono::high_resolution_clock::now();
  198. if (i == 0) {
  199. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  200. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  201. int total_seconds = (int)(t_total * n_chunk);
  202. if (total_seconds >= 60*60) {
  203. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  204. total_seconds = total_seconds % (60*60);
  205. }
  206. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  207. }
  208. //fprintf(stderr, "%s: using tokens %d...%d\n",__func__,params.n_ctx - params.ppl_stride + start, params.n_ctx + start);
  209. for (int j = n_ctx - params.ppl_stride - 1; j < n_ctx - 1; ++j) {
  210. // Calculate probability of next token, given the previous ones.
  211. const std::vector<float> tok_logits(
  212. logits.begin() + (j + 0) * n_vocab,
  213. logits.begin() + (j + 1) * n_vocab);
  214. const float prob = softmax(tok_logits)[tokens[start + j + 1]];
  215. logit_history[start + j + 1] = tok_logits[tokens[start + j + 1]];
  216. prob_history[start + j + 1] = prob;
  217. nll += -std::log(prob);
  218. ++count;
  219. }
  220. // perplexity is e^(average negative log-likelihood)
  221. if (params.ppl_output_type == 0) {
  222. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  223. } else {
  224. printf("%8d %.4lf\n", i*params.ppl_stride, std::exp(nll / count));
  225. }
  226. fflush(stdout);
  227. }
  228. printf("\n");
  229. return {tokens, std::exp(nll / count), logit_history, prob_history};
  230. }
  231. static results_perplexity perplexity(llama_context * ctx, const gpt_params & params) {
  232. if (params.ppl_stride > 0) {
  233. return perplexity_v2(ctx, params);
  234. }
  235. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  236. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  237. // Output: `perplexity: 13.5106 [114/114]`
  238. // BOS tokens will be added for each chunk before eval
  239. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  240. const int n_ctx = llama_n_ctx(ctx);
  241. auto tim1 = std::chrono::high_resolution_clock::now();
  242. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  243. std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  244. auto tim2 = std::chrono::high_resolution_clock::now();
  245. fprintf(stderr, "%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
  246. if (int(tokens.size()) < 2*n_ctx) {
  247. fprintf(stderr, "%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*n_ctx,
  248. n_ctx);
  249. fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
  250. return {std::move(tokens), 0., {}, {}};
  251. }
  252. std::vector<float> logit_history;
  253. logit_history.resize(tokens.size());
  254. std::vector<float> prob_history;
  255. prob_history.resize(tokens.size());
  256. const int n_chunk_max = tokens.size() / n_ctx;
  257. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  258. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  259. const int n_batch = params.n_batch;
  260. int count = 0;
  261. double nll = 0.0;
  262. double nll2 = 0.0;
  263. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  264. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  265. for (int i = 0; i < n_chunk; ++i) {
  266. const int start = i * n_ctx;
  267. const int end = start + n_ctx;
  268. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  269. std::vector<float> logits;
  270. const auto t_start = std::chrono::high_resolution_clock::now();
  271. // clear the KV cache
  272. llama_kv_cache_clear(ctx);
  273. for (int j = 0; j < num_batches; ++j) {
  274. const int batch_start = start + j * n_batch;
  275. const int batch_size = std::min(end - batch_start, n_batch);
  276. // save original token and restore it after eval
  277. const auto token_org = tokens[batch_start];
  278. // add BOS token for the first batch of each chunk
  279. if (add_bos && j == 0) {
  280. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  281. }
  282. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  283. fprintf(stderr, "%s : failed to eval\n", __func__);
  284. return {tokens, -1, logit_history, prob_history};
  285. }
  286. // restore the original token in case it was set to BOS
  287. tokens[batch_start] = token_org;
  288. const auto * batch_logits = llama_get_logits(ctx);
  289. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  290. }
  291. const auto t_end = std::chrono::high_resolution_clock::now();
  292. if (i == 0) {
  293. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  294. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  295. int total_seconds = (int)(t_total * n_chunk);
  296. if (total_seconds >= 60*60) {
  297. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  298. total_seconds = total_seconds % (60*60);
  299. }
  300. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  301. }
  302. // We get the logits for all the tokens in the context window (params.n_ctx)
  303. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  304. // calculate the perplexity over the last half of the window (so the model always has
  305. // some context to predict the token).
  306. //
  307. // We rely on the fact that attention in the forward pass only looks at previous
  308. // tokens here, so the logits returned for each token are an accurate representation
  309. // of what the model would have predicted at that point.
  310. //
  311. // Example, we have a context window of 512, we will compute perplexity for each of the
  312. // last 256 tokens. Then, we split the input up into context window size chunks to
  313. // process the entire prompt.
  314. const int first = n_ctx/2;
  315. process_logits(n_vocab, logits.data() + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
  316. workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
  317. count += n_ctx - first - 1;
  318. // perplexity is e^(average negative log-likelihood)
  319. if (params.ppl_output_type == 0) {
  320. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  321. } else {
  322. double av = nll/count;
  323. double av2 = nll2/count - av*av;
  324. if (av2 > 0) av2 = sqrt(av2/(count-1));
  325. printf("%8d %.4lf %4lf %4lf\n", i*n_ctx, std::exp(nll / count), av, av2);
  326. }
  327. fflush(stdout);
  328. }
  329. printf("\n");
  330. nll2 /= count;
  331. nll /= count;
  332. const double ppl = exp(nll);
  333. nll2 -= nll * nll;
  334. if (nll2 > 0) {
  335. nll2 = sqrt(nll2/(count-1));
  336. printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  337. } else {
  338. printf("Unexpected negative standard deviation of log(prob)\n");
  339. }
  340. return {tokens, ppl, logit_history, prob_history};
  341. }
  342. static std::vector<float> evaluate_tokens(llama_context * ctx, std::vector<int> & tokens,
  343. int n_past, int n_batch, int n_vocab) {
  344. std::vector<float> result;
  345. result.reserve(tokens.size() * n_vocab);
  346. size_t n_chunk = (tokens.size() + n_batch - 1)/n_batch;
  347. for (size_t i_chunk = 0; i_chunk < n_chunk; ++i_chunk) {
  348. size_t n_tokens = tokens.size() - i_chunk * n_batch;
  349. n_tokens = std::min(n_tokens, size_t(n_batch));
  350. llama_kv_cache_seq_rm(ctx, 0, n_past, -1);
  351. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + i_chunk * n_batch, n_tokens, n_past, 0))) {
  352. fprintf(stderr, "%s : failed to eval\n", __func__);
  353. return {};
  354. }
  355. const auto logits = llama_get_logits(ctx);
  356. result.insert(result.end(), logits, logits + n_tokens * n_vocab);
  357. n_past += n_tokens;
  358. }
  359. return result;
  360. }
  361. static void hellaswag_compute_logprobs(const float * batch_logits, int n_vocab, std::vector<std::thread>& workers,
  362. const std::vector<std::pair<size_t, llama_token>>& eval_pairs, std::vector<float>& eval_results) {
  363. constexpr int k_token_chunk = 4;
  364. if (eval_results.size() != eval_pairs.size()) {
  365. eval_results.resize(eval_pairs.size());
  366. }
  367. if (eval_pairs.empty()) return;
  368. size_t max_threads = std::min((eval_pairs.size() + k_token_chunk - 1)/k_token_chunk, workers.size());
  369. std::atomic<int> counter(0);
  370. auto compute = [&counter, &eval_pairs, &eval_results, batch_logits, n_vocab] () {
  371. float local_logprobs[k_token_chunk];
  372. while (true) {
  373. size_t first = counter.fetch_add(k_token_chunk, std::memory_order_relaxed);
  374. if (first >= eval_results.size()) break;
  375. size_t last = std::min(first + k_token_chunk, eval_results.size());
  376. for (size_t i = first; i < last; ++i) {
  377. auto logits = batch_logits + eval_pairs[i].first * n_vocab;
  378. float max_logit = logits[0];
  379. for (int j = 1; j < n_vocab; ++j) {
  380. max_logit = std::max(max_logit, logits[j]);
  381. }
  382. float sum_p = 0.f;
  383. for (int j = 0; j < n_vocab; ++j) {
  384. sum_p += expf(logits[j] - max_logit);
  385. }
  386. local_logprobs[i - first] = logits[eval_pairs[i].second] - max_logit - std::log(sum_p);
  387. }
  388. std::memcpy(eval_results.data() + first, local_logprobs, (last - first)*sizeof(float));
  389. }
  390. };
  391. for (size_t it = 0; it < max_threads; ++it) {
  392. workers[it] = std::thread(compute);
  393. }
  394. for (size_t it = 0; it < max_threads; ++it) {
  395. workers[it].join();
  396. }
  397. }
  398. static void hellaswag_score(llama_context * ctx, const gpt_params & params) {
  399. // Calculates hellaswag score (acc_norm) from prompt
  400. //
  401. // Data extracted from the HellaSwag validation dataset (MIT license) https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl
  402. // All used data fields are preprocessed as in https://github.com/EleutherAI/lm-evaluation-harness/blob/df3da98c5405deafd519c2ddca52bb7c3fe36bef/lm_eval/tasks/hellaswag.py#L62-L68
  403. //
  404. // All 10042 tasks should be extracted to keep the results standardized like other implementations.
  405. //
  406. // Datafile layout:
  407. // ['??'] denotes json fields
  408. // 6 lines per task:
  409. // ['activity_label'] + ": " +['ctx'] - The first part of the query, the context
  410. // ['label'] - The index the best common sense ending aka gold ending
  411. // ['endings'][0] - Endings added to the first part of the query
  412. // ['endings'][1]
  413. // ['endings'][2]
  414. // ['endings'][3]
  415. std::vector<std::string> prompt_lines;
  416. std::istringstream strstream(params.prompt);
  417. std::string line;
  418. while (std::getline(strstream,line,'\n')) {
  419. prompt_lines.push_back(line);
  420. }
  421. if (prompt_lines.size() % 6 != 0) {
  422. fprintf(stderr, "%s : number of lines in prompt not a multiple of 6.\n", __func__);
  423. return;
  424. }
  425. size_t hs_task_count = prompt_lines.size()/6;
  426. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, hs_task_count);
  427. const bool is_spm = llama_vocab_type(llama_get_model(ctx)) == LLAMA_VOCAB_TYPE_SPM;
  428. fprintf(stderr, "================================= is_spm = %d\n", is_spm);
  429. // This is needed as usual for LLaMA models
  430. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  431. // Number of tasks to use when computing the score
  432. if (params.hellaswag_tasks < hs_task_count) {
  433. hs_task_count = params.hellaswag_tasks;
  434. }
  435. // The tasks should be randomized so the score stabilizes quickly.
  436. bool randomize_tasks = true;
  437. // The random seed should not impact the final result if the computation is done over enough tasks, so kept hardcoded for now
  438. std::mt19937 rng(1);
  439. // Dataholder for hellaswag tasks
  440. struct hs_data_t {
  441. std::string context;
  442. size_t gold_ending_idx;
  443. std::string ending[4];
  444. size_t ending_logprob_count[4];
  445. double ending_logprob[4];
  446. size_t i_batch; // starting index in the llama_batch
  447. size_t common_prefix; // max number of initial tokens that are the same in all sentences
  448. size_t required_tokens; // needed number of tokens to evaluate all 4 endings
  449. std::vector<llama_token> seq_tokens[4];
  450. };
  451. fprintf(stderr, "%s : selecting %zu %s tasks.\n", __func__, hs_task_count, (randomize_tasks?"randomized":"the first") );
  452. // Select and read data from prompt lines
  453. std::vector<hs_data_t> hs_data(hs_task_count);
  454. for (size_t i = 0; i < hs_task_count; i++) {
  455. size_t idx = i;
  456. auto & hs_cur = hs_data[i];
  457. // Select a random example of those left in the prompt
  458. if (randomize_tasks) {
  459. std::uniform_int_distribution<size_t> dist(0, prompt_lines.size()/6-1 ) ;
  460. idx = dist(rng);
  461. }
  462. hs_cur.context = prompt_lines[idx*6];
  463. hs_cur.gold_ending_idx = std::stoi( prompt_lines[idx*6+1] );
  464. for (size_t j = 0; j < 4; j++) {
  465. hs_cur.ending[j] = prompt_lines[idx*6+2+j];
  466. hs_cur.seq_tokens[j] = ::llama_tokenize(ctx, hs_cur.context + " " + hs_cur.ending[j], add_bos);
  467. }
  468. // determine the common prefix of the endings
  469. hs_cur.common_prefix = 0;
  470. hs_cur.required_tokens = 0;
  471. for (size_t k = 0; k < hs_cur.seq_tokens[0].size(); k++) {
  472. if (hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[1][k] ||
  473. hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[2][k] ||
  474. hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[3][k]) {
  475. break;
  476. }
  477. hs_cur.common_prefix++;
  478. }
  479. hs_cur.required_tokens = hs_cur.common_prefix +
  480. hs_cur.seq_tokens[0].size() - hs_cur.common_prefix +
  481. hs_cur.seq_tokens[1].size() - hs_cur.common_prefix +
  482. hs_cur.seq_tokens[2].size() - hs_cur.common_prefix +
  483. hs_cur.seq_tokens[3].size() - hs_cur.common_prefix;
  484. //GGML_ASSERT(hs_cur.common_prefix >= ::llama_tokenize(ctx, hs_cur.context, add_bos).size());
  485. // Delete the selected random example from the prompt
  486. if (randomize_tasks) {
  487. prompt_lines.erase( std::next(prompt_lines.begin(),idx*6) , std::next(prompt_lines.begin(),idx*6+6) );
  488. }
  489. }
  490. fprintf(stderr, "%s : calculating hellaswag score over selected tasks.\n", __func__);
  491. printf("\ntask\tacc_norm\n");
  492. double acc = 0.0f;
  493. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  494. const int n_ctx = llama_n_ctx(ctx);
  495. const int n_batch = params.n_batch;
  496. const int max_tasks_per_batch = params.n_parallel;
  497. const int max_seq = 4*max_tasks_per_batch;
  498. llama_batch batch = llama_batch_init(n_ctx, 0, max_seq);
  499. std::vector<float> tok_logits(n_vocab);
  500. std::vector<float> batch_logits(n_ctx*n_vocab);
  501. std::vector<std::pair<size_t, llama_token>> eval_pairs;
  502. std::vector<float> eval_results;
  503. std::vector<std::thread> workers(std::thread::hardware_concurrency());
  504. auto decode_helper = [&](llama_context * ctx, llama_batch & batch, int32_t n_batch) {
  505. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch) {
  506. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  507. llama_batch batch_view = {
  508. n_tokens,
  509. batch.token + i,
  510. nullptr,
  511. batch.pos + i,
  512. batch.n_seq_id + i,
  513. batch.seq_id + i,
  514. batch.logits + i,
  515. 0, 0, 0, // unused
  516. };
  517. const int ret = llama_decode(ctx, batch_view);
  518. if (ret != 0) {
  519. LOG_TEE("failed to decode the batch, n_batch = %d, ret = %d\n", n_batch, ret);
  520. return false;
  521. }
  522. memcpy(batch_logits.data() + i*n_vocab, llama_get_logits(ctx), n_tokens*n_vocab*sizeof(float));
  523. }
  524. return true;
  525. };
  526. for (size_t i0 = 0; i0 < hs_task_count; i0++) {
  527. int n_cur = 0;
  528. size_t i1 = i0;
  529. size_t i_batch = 0; // this tells us where in `llama_batch` we are currently
  530. llama_batch_clear(batch);
  531. // batch as much tasks as possible into the available context
  532. // each task has 4 unique seuqnce ids - one for each ending
  533. // the common prefix is shared among the 4 sequences to save tokens
  534. // we extract logits only from the last common token and from all ending tokens of each sequence
  535. while (n_cur + (int) hs_data[i1].required_tokens <= n_ctx) {
  536. auto & hs_cur = hs_data[i1];
  537. const int s0 = 4*(i1 - i0);
  538. if (s0 + 4 > max_seq) {
  539. break;
  540. }
  541. for (size_t i = 0; i < hs_cur.common_prefix; ++i) {
  542. llama_batch_add(batch, hs_cur.seq_tokens[0][i], i, { s0 + 0, s0 + 1, s0 + 2, s0 + 3}, false);
  543. }
  544. batch.logits[batch.n_tokens - 1] = true; // we need logits for the last token of the common prefix
  545. for (int s = 0; s < 4; ++s) {
  546. for (size_t i = hs_cur.common_prefix; i < hs_cur.seq_tokens[s].size(); ++i) {
  547. llama_batch_add(batch, hs_cur.seq_tokens[s][i], i, { s0 + s }, true);
  548. }
  549. }
  550. hs_cur.i_batch = i_batch;
  551. i_batch += hs_cur.required_tokens;
  552. n_cur += hs_data[i1].required_tokens;
  553. if (++i1 == hs_task_count) {
  554. break;
  555. }
  556. }
  557. if (i0 == i1) {
  558. fprintf(stderr, "%s : task %zu does not fit in the context window\n", __func__, i0);
  559. return;
  560. }
  561. llama_kv_cache_clear(ctx);
  562. // decode all tasks [i0, i1)
  563. if (!decode_helper(ctx, batch, n_batch)) {
  564. fprintf(stderr, "%s: llama_decode() failed\n", __func__);
  565. return;
  566. }
  567. // Compute log-probs in parallel
  568. // First we collect all tasks
  569. eval_pairs.clear();
  570. for (size_t i = i0; i < i1; ++i) {
  571. auto & hs_cur = hs_data[i];
  572. size_t li = hs_cur.common_prefix;
  573. for (int s = 0; s < 4; ++s) {
  574. for (size_t j = hs_cur.common_prefix; j < hs_cur.seq_tokens[s].size() - 1; j++) {
  575. eval_pairs.push_back(std::make_pair(hs_cur.i_batch + li++, hs_cur.seq_tokens[s][j + 1]));
  576. }
  577. ++li;
  578. }
  579. }
  580. // Then we do the actual calculation
  581. hellaswag_compute_logprobs(batch_logits.data(), n_vocab, workers, eval_pairs, eval_results);
  582. size_t ir = 0;
  583. // compute the logprobs for each ending of the decoded tasks
  584. for (size_t i = i0; i < i1; ++i) {
  585. auto & hs_cur = hs_data[i];
  586. std::memcpy(tok_logits.data(), batch_logits.data() + n_vocab*(hs_cur.i_batch + hs_cur.common_prefix - 1), n_vocab*sizeof(float));
  587. const auto first_probs = softmax(tok_logits);
  588. for (int s = 0; s < 4; ++s) {
  589. hs_cur.ending_logprob_count[s] = 1;
  590. hs_cur.ending_logprob[s] = std::log(first_probs[hs_cur.seq_tokens[s][hs_cur.common_prefix]]);
  591. for (size_t j = hs_cur.common_prefix; j < hs_cur.seq_tokens[s].size() - 1; j++) {
  592. hs_cur.ending_logprob[s] += eval_results[ir++];
  593. hs_cur.ending_logprob_count[s]++;
  594. }
  595. hs_cur.ending_logprob[s] /= hs_cur.ending_logprob_count[s];
  596. }
  597. // Find the ending with maximum logprob
  598. size_t ending_logprob_max_idx = 0;
  599. double ending_logprob_max_val = hs_cur.ending_logprob[0];
  600. for (size_t s = 1; s < 4; s++) {
  601. if (hs_cur.ending_logprob[s] > ending_logprob_max_val) {
  602. ending_logprob_max_idx = s;
  603. ending_logprob_max_val = hs_cur.ending_logprob[s];
  604. }
  605. }
  606. //printf("max logprob ending idx %lu, gold ending idx %lu\n", ending_logprob_max_idx, hs_cur.gold_ending_idx);
  607. // If the gold ending got the maximum logprobe add one accuracy point
  608. if (ending_logprob_max_idx == hs_cur.gold_ending_idx) {
  609. acc += 1.0;
  610. }
  611. // Print the accumulated accuracy mean x 100
  612. printf("%zu\t%.8lf\n", i + 1, acc/double(i + 1)*100.0);
  613. fflush(stdout);
  614. }
  615. i0 = i1 - 1;
  616. }
  617. llama_batch_free(batch);
  618. printf("\n");
  619. }
  620. struct winogrande_entry {
  621. std::string first;
  622. std::string second;
  623. std::array<std::string, 2> choices;
  624. int answer;
  625. };
  626. static std::vector<winogrande_entry> load_winogrande_from_csv(const std::string& prompt) {
  627. std::vector<winogrande_entry> result;
  628. std::istringstream in(prompt);
  629. std::string line;
  630. std::array<int, 4> comma_pos;
  631. while (true) {
  632. std::getline(in, line);
  633. if (in.fail() || in.eof()) break;
  634. int ipos = 0;
  635. bool quote_open = false;
  636. for (int i = 0; i < int(line.size()); ++i) {
  637. if (!quote_open) {
  638. if (line[i] == ',') {
  639. comma_pos[ipos++] = i;
  640. if (ipos == 4) break;
  641. }
  642. else if (line[i] == '"') {
  643. quote_open = true;
  644. }
  645. }
  646. else {
  647. if (line[i] == '"') {
  648. quote_open = false;
  649. }
  650. }
  651. }
  652. if (ipos != 4) {
  653. printf("%s: failed to find comma separators in <%s>\n", __func__, line.c_str());
  654. continue;
  655. }
  656. auto sentence = line[comma_pos[0]+1] == '"' ? line.substr(comma_pos[0]+2, comma_pos[1] - comma_pos[0] - 3)
  657. : line.substr(comma_pos[0]+1, comma_pos[1] - comma_pos[0] - 1);
  658. auto choice1 = line.substr(comma_pos[1]+1, comma_pos[2] - comma_pos[1] - 1);
  659. auto choice2 = line.substr(comma_pos[2]+1, comma_pos[3] - comma_pos[2] - 1);
  660. auto answer = line.substr(comma_pos[3]+1, line.size() - comma_pos[3] - 1);
  661. auto index = line.substr(0, comma_pos[0]);
  662. int where = 0;
  663. for ( ; where < int(sentence.size()); ++where) {
  664. if (sentence[where] == '_') break;
  665. }
  666. if (where == int(sentence.size())) {
  667. printf("%s: no _ in <%s>\n", __func__, sentence.c_str());
  668. continue;
  669. }
  670. std::istringstream stream(answer.c_str());
  671. int i_answer; stream >> i_answer;
  672. if (stream.fail() || i_answer < 1 || i_answer > 2) {
  673. printf("%s: failed to parse answer <%s>\n", __func__, answer.c_str());
  674. continue;
  675. }
  676. result.emplace_back();
  677. auto& wg = result.back();
  678. wg.first = sentence.substr(0, where);
  679. wg.second = sentence.substr(where + 1, sentence.size() - where - 1);
  680. wg.choices[0] = std::move(choice1);
  681. wg.choices[1] = std::move(choice2);
  682. wg.answer = i_answer;
  683. }
  684. return result;
  685. }
  686. /*
  687. * Evaluates the Winogrande score.
  688. * Uses a CSV containing task index, dentence, choice 1, choice 2, answer (1 or 2)
  689. * You can get one such dataset from e.g. https://huggingface.co/datasets/ikawrakow/winogrande-eval-for-llama.cpp
  690. * As an example, the 1st row in the above dataset is
  691. *
  692. * 0,Sarah was a much better surgeon than Maria so _ always got the easier cases.,Sarah,Maria,2
  693. *
  694. */
  695. static void winogrande_score(llama_context * ctx, const gpt_params & params) {
  696. constexpr int k_min_trailing_ctx = 3;
  697. auto data = load_winogrande_from_csv(params.prompt);
  698. if (data.empty()) {
  699. fprintf(stderr, "%s: no tasks\n", __func__);
  700. return;
  701. }
  702. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, data.size());
  703. if (params.winogrande_tasks > 0 && params.winogrande_tasks < data.size()) {
  704. fprintf(stderr, "%s : selecting %zu random tasks\n", __func__, params.winogrande_tasks);
  705. std::mt19937 rng(1);
  706. std::vector<int> aux(data.size());
  707. for (int i = 0; i < int(data.size()); ++i) {
  708. aux[i] = i;
  709. }
  710. float scale = 1/(1.f + (float)rng.max());
  711. std::vector<winogrande_entry> selected;
  712. selected.reserve(params.winogrande_tasks);
  713. for (int i = 0; i < int(params.winogrande_tasks); ++i) {
  714. int j = int(scale*rng()*aux.size());
  715. selected[i] = std::move(data[aux[j]]);
  716. aux[j] = aux.back();
  717. aux.pop_back();
  718. }
  719. data = std::move(selected);
  720. }
  721. // This is needed as usual for LLaMA models
  722. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  723. fprintf(stderr, "%s : calculating winogrande score over selected tasks.\n", __func__);
  724. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  725. const int n_ctx = llama_n_ctx(ctx);
  726. std::vector<float> tok_logits(n_vocab);
  727. int n_correct = 0;
  728. int n_done = 0;
  729. for (size_t task_idx = 0; task_idx < data.size(); task_idx++) {
  730. const auto& task = data[task_idx];
  731. auto base_context = ::llama_tokenize(ctx, task.first, add_bos);
  732. auto base_ctx_1st = ::llama_tokenize(ctx, task.first + task.choices[0], add_bos);
  733. auto base_ctx_2nd = ::llama_tokenize(ctx, task.first + task.choices[1], add_bos);
  734. auto sentence_1st = task.first + task.choices[0] + task.second;
  735. auto sentence_2nd = task.first + task.choices[1] + task.second;
  736. auto query_1st = ::llama_tokenize(ctx, sentence_1st, add_bos);
  737. auto query_2nd = ::llama_tokenize(ctx, sentence_2nd, add_bos);
  738. if (query_1st.size() > (size_t)n_ctx || query_2nd.size() > (size_t)n_ctx) {
  739. fprintf(stderr, "%s : number of tokens in queries %zu, %zu > n_ctxl\n", __func__, query_1st.size(), query_2nd.size());
  740. return;
  741. }
  742. auto query_1st_size = query_1st.size();
  743. auto query_2nd_size = query_2nd.size();
  744. // Speedup small evaluations by evaluating atleast 32 tokens
  745. // For Winogrande this seems to slow it down rather than speed it up.
  746. //if (query_1st.size() < 32) query_1st.resize(32);
  747. //if (query_2nd.size() < 32) query_2nd.resize(32);
  748. llama_kv_cache_clear(ctx);
  749. auto logits_1st = evaluate_tokens(ctx, query_1st, 0, params.n_batch, n_vocab);
  750. llama_kv_cache_clear(ctx);
  751. auto logits_2nd = evaluate_tokens(ctx, query_2nd, 0, params.n_batch, n_vocab);
  752. if (logits_1st.empty() || logits_2nd.empty()) {
  753. fprintf(stderr, "%s : failed to eval\n", __func__);
  754. return;
  755. }
  756. bool skip_choice = query_1st_size - base_ctx_1st.size() > k_min_trailing_ctx &&
  757. query_2nd_size - base_ctx_2nd.size() > k_min_trailing_ctx;
  758. float score_1st = 0;
  759. bool is_nan_1st = false;
  760. const auto& base_1 = skip_choice ? base_ctx_1st : base_context;
  761. const int last_1st = query_1st_size - base_1.size() > 1 ? 1 : 0;
  762. for (size_t j = base_1.size()-1; j < query_1st_size-1-last_1st; ++j) {
  763. std::memcpy(tok_logits.data(), logits_1st.data() + j*n_vocab, n_vocab*sizeof(float));
  764. const float prob = softmax(tok_logits)[query_1st[j+1]];
  765. if (std::isnan(prob) || !prob) {
  766. fprintf(stderr, "%s: %g probability for token %zu when evaluating <%s>. Base context has %zu tokens\n", __func__,
  767. prob, j, sentence_1st.c_str(), base_context.size());
  768. is_nan_1st = true;
  769. break;
  770. }
  771. score_1st += std::log(prob);
  772. }
  773. score_1st /= (query_1st_size - base_1.size() - last_1st);
  774. float score_2nd = 0;
  775. bool is_nan_2nd = false;
  776. const auto& base_2 = skip_choice ? base_ctx_2nd : base_context;
  777. const int last_2nd = query_2nd_size - base_2.size() > 1 ? 1 : 0;
  778. for (size_t j = base_2.size()-1; j < query_2nd_size-1-last_2nd; ++j) {
  779. std::memcpy(tok_logits.data(), logits_2nd.data() + j*n_vocab, n_vocab*sizeof(float));
  780. const float prob = softmax(tok_logits)[query_2nd[j+1]];
  781. if (std::isnan(prob) || !prob) {
  782. fprintf(stderr, "%s: %g probability for token %zu when evaluating <%s>. Base context has %zu tokens\n", __func__,
  783. prob, j, sentence_2nd.c_str(), base_context.size());
  784. is_nan_2nd = true;
  785. break;
  786. }
  787. score_2nd += std::log(prob);
  788. }
  789. score_2nd /= (query_2nd_size - base_2.size() - last_2nd);
  790. if (is_nan_1st || is_nan_2nd) {
  791. continue;
  792. }
  793. if (std::isnan(score_1st) || std::isnan(score_2nd)) {
  794. printf("================== NaN score %g, %g) for:\n", score_1st, score_2nd);
  795. printf("Q1: <%s> - %zu tokens\n", sentence_1st.c_str(), query_1st_size);
  796. printf("Q2: <%s> - %zu tokens\n", sentence_2nd.c_str(), query_2nd_size);
  797. printf("B : <%s> - %zu tokens\n", task.first.c_str(), base_context.size());
  798. printf("base_1 has %zu tokens, base_2 has %zu tokens, skip_choice = %d\n", base_1.size(), base_2.size(), skip_choice);
  799. continue;
  800. }
  801. int result = score_1st > score_2nd ? 1 : 2;
  802. if (result == task.answer) {
  803. ++n_correct;
  804. }
  805. ++n_done;
  806. // Print the accumulated accuracy mean x 100
  807. printf("%zu\t%.4lf\t%10.6f %10.6f %d %d\n",task_idx+1, 100.0 * n_correct/n_done,score_1st,score_2nd,result,task.answer);
  808. fflush(stdout);
  809. }
  810. printf("\n");
  811. if (n_done < 100) return;
  812. const float p = 1.f*n_correct/n_done;
  813. const float sigma = 100.f*sqrt(p*(1-p)/(n_done-1));
  814. printf("Final Winogrande score(%d tasks): %.4lf +/- %.4lf\n", n_done, 100*p, sigma);
  815. }
  816. int main(int argc, char ** argv) {
  817. gpt_params params;
  818. params.n_batch = 512;
  819. if (!gpt_params_parse(argc, argv, params)) {
  820. return 1;
  821. }
  822. params.logits_all = true;
  823. params.n_batch = std::min(params.n_batch, params.n_ctx);
  824. if (params.ppl_stride > 0) {
  825. fprintf(stderr, "Will perform strided perplexity calculation -> adjusting context size from %d to %d\n",
  826. params.n_ctx, params.n_ctx + params.ppl_stride/2);
  827. params.n_ctx += params.ppl_stride/2;
  828. }
  829. print_build_info();
  830. if (params.seed == LLAMA_DEFAULT_SEED) {
  831. params.seed = time(NULL);
  832. }
  833. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  834. std::mt19937 rng(params.seed);
  835. if (params.random_prompt) {
  836. params.prompt = gpt_random_prompt(rng);
  837. }
  838. llama_backend_init(params.numa);
  839. llama_model * model;
  840. llama_context * ctx;
  841. // load the model and apply lora adapter, if any
  842. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  843. if (model == NULL) {
  844. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  845. return 1;
  846. }
  847. const int n_ctx_train = llama_n_ctx_train(model);
  848. if (params.n_ctx > n_ctx_train) {
  849. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  850. __func__, n_ctx_train, params.n_ctx);
  851. }
  852. // print system information
  853. {
  854. fprintf(stderr, "\n");
  855. fprintf(stderr, "%s\n", get_system_info(params).c_str());
  856. }
  857. struct results_perplexity results;
  858. if (params.hellaswag) {
  859. hellaswag_score(ctx, params);
  860. } else if (params.winogrande) {
  861. winogrande_score(ctx, params);
  862. } else {
  863. results = perplexity(ctx, params);
  864. }
  865. llama_print_timings(ctx);
  866. write_logfile(ctx, params, model, results);
  867. llama_free(ctx);
  868. llama_free_model(model);
  869. llama_backend_free();
  870. return 0;
  871. }