perplexity.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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. const int num_batches = (n_ctx + n_batch - 1) / n_batch;
  264. std::vector<float> logits;
  265. if (num_batches > 1) {
  266. logits.reserve((size_t)n_ctx * n_vocab);
  267. }
  268. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  269. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  270. for (int i = 0; i < n_chunk; ++i) {
  271. const int start = i * n_ctx;
  272. const int end = start + n_ctx;
  273. const auto t_start = std::chrono::high_resolution_clock::now();
  274. // clear the KV cache
  275. llama_kv_cache_clear(ctx);
  276. for (int j = 0; j < num_batches; ++j) {
  277. const int batch_start = start + j * n_batch;
  278. const int batch_size = std::min(end - batch_start, n_batch);
  279. // save original token and restore it after eval
  280. const auto token_org = tokens[batch_start];
  281. // add BOS token for the first batch of each chunk
  282. if (add_bos && j == 0) {
  283. tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
  284. }
  285. if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
  286. fprintf(stderr, "%s : failed to eval\n", __func__);
  287. return {tokens, -1, logit_history, prob_history};
  288. }
  289. // restore the original token in case it was set to BOS
  290. tokens[batch_start] = token_org;
  291. if (num_batches > 1) {
  292. const auto * batch_logits = llama_get_logits(ctx);
  293. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  294. }
  295. }
  296. const auto t_end = std::chrono::high_resolution_clock::now();
  297. if (i == 0) {
  298. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  299. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  300. int total_seconds = (int)(t_total * n_chunk);
  301. if (total_seconds >= 60*60) {
  302. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  303. total_seconds = total_seconds % (60*60);
  304. }
  305. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  306. }
  307. // We get the logits for all the tokens in the context window (params.n_ctx)
  308. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  309. // calculate the perplexity over the last half of the window (so the model always has
  310. // some context to predict the token).
  311. //
  312. // We rely on the fact that attention in the forward pass only looks at previous
  313. // tokens here, so the logits returned for each token are an accurate representation
  314. // of what the model would have predicted at that point.
  315. //
  316. // Example, we have a context window of 512, we will compute perplexity for each of the
  317. // last 256 tokens. Then, we split the input up into context window size chunks to
  318. // process the entire prompt.
  319. const int first = n_ctx/2;
  320. const float * all_logits = num_batches > 1 ? logits.data() : llama_get_logits(ctx);
  321. process_logits(n_vocab, all_logits + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
  322. workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
  323. count += n_ctx - first - 1;
  324. // perplexity is e^(average negative log-likelihood)
  325. if (params.ppl_output_type == 0) {
  326. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  327. } else {
  328. double av = nll/count;
  329. double av2 = nll2/count - av*av;
  330. if (av2 > 0) av2 = sqrt(av2/(count-1));
  331. printf("%8d %.4lf %4lf %4lf\n", i*n_ctx, std::exp(nll / count), av, av2);
  332. }
  333. fflush(stdout);
  334. logits.clear();
  335. }
  336. printf("\n");
  337. nll2 /= count;
  338. nll /= count;
  339. const double ppl = exp(nll);
  340. nll2 -= nll * nll;
  341. if (nll2 > 0) {
  342. nll2 = sqrt(nll2/(count-1));
  343. printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  344. } else {
  345. printf("Unexpected negative standard deviation of log(prob)\n");
  346. }
  347. return {tokens, ppl, logit_history, prob_history};
  348. }
  349. static bool decode_helper(llama_context * ctx, llama_batch & batch, std::vector<float> & batch_logits, int32_t n_batch, int32_t n_vocab) {
  350. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch) {
  351. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  352. llama_batch batch_view = {
  353. n_tokens,
  354. batch.token + i,
  355. nullptr,
  356. batch.pos + i,
  357. batch.n_seq_id + i,
  358. batch.seq_id + i,
  359. batch.logits + i,
  360. 0, 0, 0, // unused
  361. };
  362. const int ret = llama_decode(ctx, batch_view);
  363. if (ret != 0) {
  364. LOG_TEE("failed to decode the batch, n_batch = %d, ret = %d\n", n_batch, ret);
  365. return false;
  366. }
  367. memcpy(batch_logits.data() + i*n_vocab, llama_get_logits(ctx), n_tokens*n_vocab*sizeof(float));
  368. }
  369. return true;
  370. }
  371. static void compute_logprobs(const float * batch_logits, int n_vocab, std::vector<std::thread>& workers,
  372. const std::vector<std::pair<size_t, llama_token>>& eval_pairs, std::vector<float>& eval_results) {
  373. constexpr int k_token_chunk = 4;
  374. if (eval_results.size() != eval_pairs.size()) {
  375. eval_results.resize(eval_pairs.size());
  376. }
  377. if (eval_pairs.empty()) return;
  378. size_t max_threads = std::min((eval_pairs.size() + k_token_chunk - 1)/k_token_chunk, workers.size());
  379. std::atomic<int> counter(0);
  380. auto compute = [&counter, &eval_pairs, &eval_results, batch_logits, n_vocab] () {
  381. float local_logprobs[k_token_chunk];
  382. while (true) {
  383. size_t first = counter.fetch_add(k_token_chunk, std::memory_order_relaxed);
  384. if (first >= eval_results.size()) break;
  385. size_t last = std::min(first + k_token_chunk, eval_results.size());
  386. for (size_t i = first; i < last; ++i) {
  387. auto logits = batch_logits + eval_pairs[i].first * n_vocab;
  388. float max_logit = logits[0];
  389. for (int j = 1; j < n_vocab; ++j) {
  390. max_logit = std::max(max_logit, logits[j]);
  391. }
  392. float sum_p = 0.f;
  393. for (int j = 0; j < n_vocab; ++j) {
  394. sum_p += expf(logits[j] - max_logit);
  395. }
  396. local_logprobs[i - first] = logits[eval_pairs[i].second] - max_logit - std::log(sum_p);
  397. }
  398. std::memcpy(eval_results.data() + first, local_logprobs, (last - first)*sizeof(float));
  399. }
  400. };
  401. for (size_t it = 0; it < max_threads; ++it) {
  402. workers[it] = std::thread(compute);
  403. }
  404. for (size_t it = 0; it < max_threads; ++it) {
  405. workers[it].join();
  406. }
  407. }
  408. static void hellaswag_score(llama_context * ctx, const gpt_params & params) {
  409. // Calculates hellaswag score (acc_norm) from prompt
  410. //
  411. // Data extracted from the HellaSwag validation dataset (MIT license) https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl
  412. // All used data fields are preprocessed as in https://github.com/EleutherAI/lm-evaluation-harness/blob/df3da98c5405deafd519c2ddca52bb7c3fe36bef/lm_eval/tasks/hellaswag.py#L62-L68
  413. //
  414. // All 10042 tasks should be extracted to keep the results standardized like other implementations.
  415. //
  416. // Datafile layout:
  417. // ['??'] denotes json fields
  418. // 6 lines per task:
  419. // ['activity_label'] + ": " +['ctx'] - The first part of the query, the context
  420. // ['label'] - The index the best common sense ending aka gold ending
  421. // ['endings'][0] - Endings added to the first part of the query
  422. // ['endings'][1]
  423. // ['endings'][2]
  424. // ['endings'][3]
  425. std::vector<std::string> prompt_lines;
  426. std::istringstream strstream(params.prompt);
  427. std::string line;
  428. while (std::getline(strstream,line,'\n')) {
  429. prompt_lines.push_back(line);
  430. }
  431. if (prompt_lines.size() % 6 != 0) {
  432. fprintf(stderr, "%s : number of lines in prompt not a multiple of 6.\n", __func__);
  433. return;
  434. }
  435. size_t hs_task_count = prompt_lines.size()/6;
  436. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, hs_task_count);
  437. const bool is_spm = llama_vocab_type(llama_get_model(ctx)) == LLAMA_VOCAB_TYPE_SPM;
  438. fprintf(stderr, "================================= is_spm = %d\n", is_spm);
  439. // This is needed as usual for LLaMA models
  440. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  441. // Number of tasks to use when computing the score
  442. if (params.hellaswag_tasks < hs_task_count) {
  443. hs_task_count = params.hellaswag_tasks;
  444. }
  445. // The tasks should be randomized so the score stabilizes quickly.
  446. bool randomize_tasks = true;
  447. // The random seed should not impact the final result if the computation is done over enough tasks, so kept hardcoded for now
  448. std::mt19937 rng(1);
  449. // Dataholder for hellaswag tasks
  450. struct hs_data_t {
  451. std::string context;
  452. size_t gold_ending_idx;
  453. std::string ending[4];
  454. size_t ending_logprob_count[4];
  455. double ending_logprob[4];
  456. size_t i_batch; // starting index in the llama_batch
  457. size_t common_prefix; // max number of initial tokens that are the same in all sentences
  458. size_t required_tokens; // needed number of tokens to evaluate all 4 endings
  459. std::vector<llama_token> seq_tokens[4];
  460. };
  461. fprintf(stderr, "%s : selecting %zu %s tasks.\n", __func__, hs_task_count, (randomize_tasks?"randomized":"the first") );
  462. // Select and read data from prompt lines
  463. std::vector<hs_data_t> hs_data(hs_task_count);
  464. for (size_t i = 0; i < hs_task_count; i++) {
  465. size_t idx = i;
  466. auto & hs_cur = hs_data[i];
  467. // Select a random example of those left in the prompt
  468. if (randomize_tasks) {
  469. std::uniform_int_distribution<size_t> dist(0, prompt_lines.size()/6-1 ) ;
  470. idx = dist(rng);
  471. }
  472. hs_cur.context = prompt_lines[idx*6];
  473. hs_cur.gold_ending_idx = std::stoi( prompt_lines[idx*6+1] );
  474. for (size_t j = 0; j < 4; j++) {
  475. hs_cur.ending[j] = prompt_lines[idx*6+2+j];
  476. hs_cur.seq_tokens[j] = ::llama_tokenize(ctx, hs_cur.context + " " + hs_cur.ending[j], add_bos);
  477. }
  478. // determine the common prefix of the endings
  479. hs_cur.common_prefix = 0;
  480. for (size_t k = 0; k < hs_cur.seq_tokens[0].size(); k++) {
  481. if (hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[1][k] ||
  482. hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[2][k] ||
  483. hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[3][k]) {
  484. break;
  485. }
  486. hs_cur.common_prefix++;
  487. }
  488. hs_cur.required_tokens = hs_cur.common_prefix +
  489. hs_cur.seq_tokens[0].size() - hs_cur.common_prefix +
  490. hs_cur.seq_tokens[1].size() - hs_cur.common_prefix +
  491. hs_cur.seq_tokens[2].size() - hs_cur.common_prefix +
  492. hs_cur.seq_tokens[3].size() - hs_cur.common_prefix;
  493. //GGML_ASSERT(hs_cur.common_prefix >= ::llama_tokenize(ctx, hs_cur.context, add_bos).size());
  494. // Delete the selected random example from the prompt
  495. if (randomize_tasks) {
  496. prompt_lines.erase( std::next(prompt_lines.begin(),idx*6) , std::next(prompt_lines.begin(),idx*6+6) );
  497. }
  498. }
  499. fprintf(stderr, "%s : calculating hellaswag score over selected tasks.\n", __func__);
  500. printf("\ntask\tacc_norm\n");
  501. double acc = 0.0f;
  502. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  503. const int n_ctx = llama_n_ctx(ctx);
  504. const int n_batch = params.n_batch;
  505. const int max_tasks_per_batch = 32;
  506. const int max_seq = 4*max_tasks_per_batch;
  507. llama_batch batch = llama_batch_init(n_ctx, 0, max_seq);
  508. std::vector<float> tok_logits(n_vocab);
  509. std::vector<float> batch_logits(n_vocab*n_ctx);
  510. std::vector<std::pair<size_t, llama_token>> eval_pairs;
  511. std::vector<float> eval_results;
  512. std::vector<std::thread> workers(std::thread::hardware_concurrency());
  513. for (size_t i0 = 0; i0 < hs_task_count; i0++) {
  514. int n_cur = 0;
  515. size_t i1 = i0;
  516. size_t i_batch = 0; // this tells us where in `llama_batch` we are currently
  517. llama_batch_clear(batch);
  518. // batch as much tasks as possible into the available context
  519. // each task has 4 unique seuqnce ids - one for each ending
  520. // the common prefix is shared among the 4 sequences to save tokens
  521. // we extract logits only from the last common token and from all ending tokens of each sequence
  522. while (n_cur + (int) hs_data[i1].required_tokens <= n_ctx) {
  523. auto & hs_cur = hs_data[i1];
  524. const int s0 = 4*(i1 - i0);
  525. if (s0 + 4 > max_seq) {
  526. break;
  527. }
  528. for (size_t i = 0; i < hs_cur.common_prefix; ++i) {
  529. llama_batch_add(batch, hs_cur.seq_tokens[0][i], i, { s0 + 0, s0 + 1, s0 + 2, s0 + 3}, false);
  530. }
  531. batch.logits[batch.n_tokens - 1] = true; // we need logits for the last token of the common prefix
  532. for (int s = 0; s < 4; ++s) {
  533. for (size_t i = hs_cur.common_prefix; i < hs_cur.seq_tokens[s].size(); ++i) {
  534. llama_batch_add(batch, hs_cur.seq_tokens[s][i], i, { s0 + s }, true);
  535. }
  536. }
  537. hs_cur.i_batch = i_batch;
  538. i_batch += hs_cur.required_tokens;
  539. n_cur += hs_data[i1].required_tokens;
  540. if (++i1 == hs_task_count) {
  541. break;
  542. }
  543. }
  544. if (i0 == i1) {
  545. fprintf(stderr, "%s : task %zu does not fit in the context window\n", __func__, i0);
  546. return;
  547. }
  548. llama_kv_cache_clear(ctx);
  549. // decode all tasks [i0, i1)
  550. if (!decode_helper(ctx, batch, batch_logits, n_batch, n_vocab)) {
  551. fprintf(stderr, "%s: llama_decode() failed\n", __func__);
  552. return;
  553. }
  554. // Compute log-probs in parallel
  555. // First we collect all tasks
  556. eval_pairs.clear();
  557. for (size_t i = i0; i < i1; ++i) {
  558. auto & hs_cur = hs_data[i];
  559. size_t li = hs_cur.common_prefix;
  560. for (int s = 0; s < 4; ++s) {
  561. for (size_t j = hs_cur.common_prefix; j < hs_cur.seq_tokens[s].size() - 1; j++) {
  562. eval_pairs.push_back(std::make_pair(hs_cur.i_batch + li++, hs_cur.seq_tokens[s][j + 1]));
  563. }
  564. ++li;
  565. }
  566. }
  567. // Then we do the actual calculation
  568. compute_logprobs(batch_logits.data(), n_vocab, workers, eval_pairs, eval_results);
  569. size_t ir = 0;
  570. // compute the logprobs for each ending of the decoded tasks
  571. for (size_t i = i0; i < i1; ++i) {
  572. auto & hs_cur = hs_data[i];
  573. std::memcpy(tok_logits.data(), batch_logits.data() + n_vocab*(hs_cur.i_batch + hs_cur.common_prefix - 1), n_vocab*sizeof(float));
  574. const auto first_probs = softmax(tok_logits);
  575. for (int s = 0; s < 4; ++s) {
  576. hs_cur.ending_logprob_count[s] = 1;
  577. hs_cur.ending_logprob[s] = std::log(first_probs[hs_cur.seq_tokens[s][hs_cur.common_prefix]]);
  578. for (size_t j = hs_cur.common_prefix; j < hs_cur.seq_tokens[s].size() - 1; j++) {
  579. hs_cur.ending_logprob[s] += eval_results[ir++];
  580. hs_cur.ending_logprob_count[s]++;
  581. }
  582. hs_cur.ending_logprob[s] /= hs_cur.ending_logprob_count[s];
  583. }
  584. // Find the ending with maximum logprob
  585. size_t ending_logprob_max_idx = 0;
  586. double ending_logprob_max_val = hs_cur.ending_logprob[0];
  587. for (size_t s = 1; s < 4; s++) {
  588. if (hs_cur.ending_logprob[s] > ending_logprob_max_val) {
  589. ending_logprob_max_idx = s;
  590. ending_logprob_max_val = hs_cur.ending_logprob[s];
  591. }
  592. }
  593. //printf("max logprob ending idx %lu, gold ending idx %lu\n", ending_logprob_max_idx, hs_cur.gold_ending_idx);
  594. // If the gold ending got the maximum logprobe add one accuracy point
  595. if (ending_logprob_max_idx == hs_cur.gold_ending_idx) {
  596. acc += 1.0;
  597. }
  598. // Print the accumulated accuracy mean x 100
  599. printf("%zu\t%.8lf\n", i + 1, acc/double(i + 1)*100.0);
  600. fflush(stdout);
  601. }
  602. i0 = i1 - 1;
  603. }
  604. llama_batch_free(batch);
  605. printf("\n");
  606. }
  607. struct winogrande_entry {
  608. std::string first;
  609. std::string second;
  610. std::array<std::string, 2> choices;
  611. int answer;
  612. size_t i_batch;
  613. size_t common_prefix;
  614. size_t required_tokens;
  615. size_t n_base1; // number of tokens for context + choice 1
  616. size_t n_base2; // number of tokens for context + choice 2
  617. std::vector<llama_token> seq_tokens[2];
  618. };
  619. static std::vector<winogrande_entry> load_winogrande_from_csv(const std::string& prompt) {
  620. std::vector<winogrande_entry> result;
  621. std::istringstream in(prompt);
  622. std::string line;
  623. std::array<int, 4> comma_pos;
  624. while (true) {
  625. std::getline(in, line);
  626. if (in.fail() || in.eof()) break;
  627. int ipos = 0;
  628. bool quote_open = false;
  629. for (int i = 0; i < int(line.size()); ++i) {
  630. if (!quote_open) {
  631. if (line[i] == ',') {
  632. comma_pos[ipos++] = i;
  633. if (ipos == 4) break;
  634. }
  635. else if (line[i] == '"') {
  636. quote_open = true;
  637. }
  638. }
  639. else {
  640. if (line[i] == '"') {
  641. quote_open = false;
  642. }
  643. }
  644. }
  645. if (ipos != 4) {
  646. printf("%s: failed to find comma separators in <%s>\n", __func__, line.c_str());
  647. continue;
  648. }
  649. auto sentence = line[comma_pos[0]+1] == '"' ? line.substr(comma_pos[0]+2, comma_pos[1] - comma_pos[0] - 3)
  650. : line.substr(comma_pos[0]+1, comma_pos[1] - comma_pos[0] - 1);
  651. auto choice1 = line.substr(comma_pos[1]+1, comma_pos[2] - comma_pos[1] - 1);
  652. auto choice2 = line.substr(comma_pos[2]+1, comma_pos[3] - comma_pos[2] - 1);
  653. auto answer = line.substr(comma_pos[3]+1, line.size() - comma_pos[3] - 1);
  654. auto index = line.substr(0, comma_pos[0]);
  655. int where = 0;
  656. for ( ; where < int(sentence.size()); ++where) {
  657. if (sentence[where] == '_') break;
  658. }
  659. if (where == int(sentence.size())) {
  660. printf("%s: no _ in <%s>\n", __func__, sentence.c_str());
  661. continue;
  662. }
  663. std::istringstream stream(answer.c_str());
  664. int i_answer; stream >> i_answer;
  665. if (stream.fail() || i_answer < 1 || i_answer > 2) {
  666. printf("%s: failed to parse answer <%s>\n", __func__, answer.c_str());
  667. continue;
  668. }
  669. result.emplace_back();
  670. auto& wg = result.back();
  671. wg.first = sentence.substr(0, where);
  672. wg.second = sentence.substr(where + 1, sentence.size() - where - 1);
  673. wg.choices[0] = std::move(choice1);
  674. wg.choices[1] = std::move(choice2);
  675. wg.answer = i_answer;
  676. }
  677. return result;
  678. }
  679. /*
  680. * Evaluates the Winogrande score.
  681. * Uses a CSV containing task index, dentence, choice 1, choice 2, answer (1 or 2)
  682. * You can get one such dataset from e.g. https://huggingface.co/datasets/ikawrakow/winogrande-eval-for-llama.cpp
  683. * As an example, the 1st row in the above dataset is
  684. *
  685. * 0,Sarah was a much better surgeon than Maria so _ always got the easier cases.,Sarah,Maria,2
  686. *
  687. */
  688. static void winogrande_score(llama_context * ctx, const gpt_params & params) {
  689. constexpr int k_min_trailing_ctx = 3;
  690. auto data = load_winogrande_from_csv(params.prompt);
  691. if (data.empty()) {
  692. fprintf(stderr, "%s: no tasks\n", __func__);
  693. return;
  694. }
  695. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, data.size());
  696. if (params.winogrande_tasks > 0 && params.winogrande_tasks < data.size()) {
  697. fprintf(stderr, "%s : selecting %zu random tasks\n", __func__, params.winogrande_tasks);
  698. std::mt19937 rng(1);
  699. std::vector<int> aux(data.size());
  700. for (int i = 0; i < int(data.size()); ++i) {
  701. aux[i] = i;
  702. }
  703. float scale = 1/(1.f + (float)rng.max());
  704. std::vector<winogrande_entry> selected;
  705. selected.resize(params.winogrande_tasks);
  706. for (int i = 0; i < int(params.winogrande_tasks); ++i) {
  707. int j = int(scale*rng()*aux.size());
  708. selected[i] = std::move(data[aux[j]]);
  709. aux[j] = aux.back();
  710. aux.pop_back();
  711. }
  712. data = std::move(selected);
  713. }
  714. fprintf(stderr, "%s : tokenizing selected tasks\n", __func__);
  715. // This is needed as usual for LLaMA models
  716. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
  717. for (auto & task : data) {
  718. task.seq_tokens[0] = ::llama_tokenize(ctx, task.first + task.choices[0] + task.second, add_bos);
  719. task.seq_tokens[1] = ::llama_tokenize(ctx, task.first + task.choices[1] + task.second, add_bos);
  720. task.common_prefix = 0;
  721. for (size_t k = 0; k < task.seq_tokens[0].size(); k++) {
  722. if (task.seq_tokens[0][k] != task.seq_tokens[1][k]) {
  723. break;
  724. }
  725. task.common_prefix++;
  726. }
  727. task.required_tokens = task.common_prefix +
  728. task.seq_tokens[0].size() - task.common_prefix +
  729. task.seq_tokens[1].size() - task.common_prefix;
  730. task.n_base1 = ::llama_tokenize(ctx, task.first + task.choices[0], add_bos).size();
  731. task.n_base2 = ::llama_tokenize(ctx, task.first + task.choices[1], add_bos).size();
  732. }
  733. fprintf(stderr, "%s : calculating winogrande score over selected tasks.\n", __func__);
  734. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  735. const int n_ctx = llama_n_ctx(ctx);
  736. const int n_batch = params.n_batch;
  737. const int max_tasks_per_batch = 128;
  738. const int max_seq = 2*max_tasks_per_batch;
  739. llama_batch batch = llama_batch_init(n_ctx, 0, max_seq);
  740. std::vector<float> tok_logits(n_vocab);
  741. std::vector<float> batch_logits(n_vocab*n_ctx);
  742. std::vector<std::pair<size_t, llama_token>> eval_pairs;
  743. std::vector<float> eval_results;
  744. std::vector<std::thread> workers(std::thread::hardware_concurrency());
  745. int n_correct = 0;
  746. int n_done = 0;
  747. for (size_t i0 = 0; i0 < data.size(); i0++) {
  748. int n_cur = 0;
  749. size_t i1 = i0;
  750. size_t i_batch = 0;
  751. llama_batch_clear(batch);
  752. while (n_cur + (int) data[i1].required_tokens <= n_ctx) {
  753. const int s0 = 2*(i1 - i0);
  754. if (s0 + 2 > max_seq) {
  755. break;
  756. }
  757. for (size_t i = 0; i < data[i1].common_prefix; ++i) {
  758. llama_batch_add(batch, data[i1].seq_tokens[0][i], i, { s0 + 0, s0 + 1}, false);
  759. }
  760. batch.logits[batch.n_tokens - 1] = true;
  761. for (int s = 0; s < 2; ++s) {
  762. for (size_t i = data[i1].common_prefix; i < data[i1].seq_tokens[s].size(); ++i) {
  763. llama_batch_add(batch, data[i1].seq_tokens[s][i], i, { s0 + s }, true);
  764. }
  765. }
  766. data[i1].i_batch = i_batch;
  767. i_batch += data[i1].required_tokens;
  768. n_cur += data[i1].required_tokens;
  769. if (++i1 == data.size()) {
  770. break;
  771. }
  772. }
  773. if (i0 == i1) {
  774. fprintf(stderr, "%s : task %zu does not fit in the context window\n", __func__, i0);
  775. return;
  776. }
  777. llama_kv_cache_clear(ctx);
  778. // decode all tasks [i0, i1)
  779. if (!decode_helper(ctx, batch, batch_logits, n_batch, n_vocab)) {
  780. fprintf(stderr, "%s: llama_decode() failed\n", __func__);
  781. return;
  782. }
  783. eval_pairs.clear();
  784. for (size_t i = i0; i < i1; ++i) {
  785. auto & task = data[i];
  786. const bool skip_choice =
  787. task.seq_tokens[0].size() - task.common_prefix > k_min_trailing_ctx &&
  788. task.seq_tokens[1].size() - task.common_prefix > k_min_trailing_ctx;
  789. const auto& n_base1 = skip_choice ? task.n_base1 : task.common_prefix;
  790. const int last_1st = task.seq_tokens[0].size() - n_base1 > 1 ? 1 : 0;
  791. size_t li = n_base1 - 1;
  792. for (size_t j = n_base1-1; j < task.seq_tokens[0].size()-1-last_1st; ++j) {
  793. eval_pairs.push_back(std::make_pair(task.i_batch + li++, task.seq_tokens[0][j+1]));
  794. }
  795. const auto& n_base2 = skip_choice ? task.n_base2 : task.common_prefix;
  796. const int last_2nd = task.seq_tokens[1].size() - n_base2 > 1 ? 1 : 0;
  797. li = task.seq_tokens[0].size() - task.common_prefix + n_base2 - 1;
  798. for (size_t j = n_base2-1; j < task.seq_tokens[1].size()-1-last_2nd; ++j) {
  799. eval_pairs.push_back(std::make_pair(task.i_batch + li++, task.seq_tokens[1][j+1]));
  800. }
  801. }
  802. compute_logprobs(batch_logits.data(), n_vocab, workers, eval_pairs, eval_results);
  803. size_t ir = 0;
  804. for (size_t i = i0; i < i1; ++i) {
  805. auto & task = data[i];
  806. const bool skip_choice =
  807. task.seq_tokens[0].size() - task.common_prefix > k_min_trailing_ctx &&
  808. task.seq_tokens[1].size() - task.common_prefix > k_min_trailing_ctx;
  809. float score_1st = 0;
  810. const auto& n_base1 = skip_choice ? task.n_base1 : task.common_prefix;
  811. const int last_1st = task.seq_tokens[0].size() - n_base1 > 1 ? 1 : 0;
  812. for (size_t j = n_base1-1; j < task.seq_tokens[0].size()-1-last_1st; ++j) {
  813. score_1st += eval_results[ir++];
  814. }
  815. score_1st /= (task.seq_tokens[0].size() - n_base1 - last_1st);
  816. float score_2nd = 0;
  817. const auto& n_base2 = skip_choice ? task.n_base2 : task.common_prefix;
  818. const int last_2nd = task.seq_tokens[1].size() - n_base2 > 1 ? 1 : 0;
  819. for (size_t j = n_base2-1; j < task.seq_tokens[1].size()-1-last_2nd; ++j) {
  820. score_2nd += eval_results[ir++];
  821. }
  822. score_2nd /= (task.seq_tokens[1].size() - n_base2 - last_2nd);
  823. int result = score_1st > score_2nd ? 1 : 2;
  824. if (result == task.answer) {
  825. ++n_correct;
  826. }
  827. ++n_done;
  828. // print the accumulated accuracy mean x 100
  829. printf("%zu\t%.4lf\t%10.6f %10.6f %d %d\n", i+1, 100.0 * n_correct/n_done, score_1st, score_2nd, result, task.answer);
  830. fflush(stdout);
  831. }
  832. i0 = i1 - 1;
  833. }
  834. printf("\n");
  835. if (n_done < 100) return;
  836. const float p = 1.f*n_correct/n_done;
  837. const float sigma = 100.f*sqrt(p*(1-p)/(n_done-1));
  838. printf("Final Winogrande score(%d tasks): %.4lf +/- %.4lf\n", n_done, 100*p, sigma);
  839. }
  840. int main(int argc, char ** argv) {
  841. gpt_params params;
  842. params.n_batch = 512;
  843. if (!gpt_params_parse(argc, argv, params)) {
  844. return 1;
  845. }
  846. params.logits_all = true;
  847. params.n_batch = std::min(params.n_batch, params.n_ctx);
  848. if (params.ppl_stride > 0) {
  849. fprintf(stderr, "Will perform strided perplexity calculation -> adjusting context size from %d to %d\n",
  850. params.n_ctx, params.n_ctx + params.ppl_stride/2);
  851. params.n_ctx += params.ppl_stride/2;
  852. }
  853. print_build_info();
  854. if (params.seed == LLAMA_DEFAULT_SEED) {
  855. params.seed = time(NULL);
  856. }
  857. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  858. std::mt19937 rng(params.seed);
  859. if (params.random_prompt) {
  860. params.prompt = gpt_random_prompt(rng);
  861. }
  862. llama_backend_init(params.numa);
  863. llama_model * model;
  864. llama_context * ctx;
  865. // load the model and apply lora adapter, if any
  866. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  867. if (model == NULL) {
  868. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  869. return 1;
  870. }
  871. const int n_ctx_train = llama_n_ctx_train(model);
  872. if (params.n_ctx > n_ctx_train) {
  873. fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
  874. __func__, n_ctx_train, params.n_ctx);
  875. }
  876. // print system information
  877. {
  878. fprintf(stderr, "\n");
  879. fprintf(stderr, "%s\n", get_system_info(params).c_str());
  880. }
  881. struct results_perplexity results;
  882. if (params.hellaswag) {
  883. hellaswag_score(ctx, params);
  884. } else if (params.winogrande) {
  885. winogrande_score(ctx, params);
  886. } else {
  887. results = perplexity(ctx, params);
  888. }
  889. llama_print_timings(ctx);
  890. write_logfile(ctx, params, model, results);
  891. llama_free(ctx);
  892. llama_free_model(model);
  893. llama_backend_free();
  894. return 0;
  895. }