perplexity.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. #include <cmath>
  5. #include <ctime>
  6. #include <sstream>
  7. #include <cstring>
  8. #include <thread>
  9. #include <mutex>
  10. #if defined(_MSC_VER)
  11. #pragma warning(disable: 4244 4267) // possible loss of data
  12. #endif
  13. std::vector<float> softmax(const std::vector<float>& logits) {
  14. std::vector<float> probs(logits.size());
  15. float max_logit = logits[0];
  16. for (float v : logits) max_logit = std::max(max_logit, v);
  17. double sum_exp = 0.0;
  18. for (size_t i = 0; i < logits.size(); i++) {
  19. // Subtract the maximum logit value from the current logit value for numerical stability
  20. const float logit = logits[i] - max_logit;
  21. const float exp_logit = expf(logit);
  22. sum_exp += exp_logit;
  23. probs[i] = exp_logit;
  24. }
  25. for (size_t i = 0; i < probs.size(); i++) probs[i] /= sum_exp;
  26. return probs;
  27. }
  28. float log_softmax(int n_vocab, const float * logits, int tok) {
  29. float max_logit = logits[0];
  30. for (int i = 1; i < n_vocab; ++i) max_logit = std::max(max_logit, logits[i]);
  31. double sum_exp = 0.0;
  32. for (int i = 0; i < n_vocab; ++i) sum_exp += expf(logits[i] - max_logit);
  33. return logits[tok] - max_logit - log(sum_exp);
  34. }
  35. void process_logits(int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread>& workers,
  36. double& nll, double& nll2) {
  37. std::mutex mutex;
  38. int counter = 0;
  39. auto compute = [&mutex, &counter, &nll, &nll2, n_vocab, logits, tokens, n_token] () {
  40. double local_nll = 0, local_nll2 = 0;
  41. while (true) {
  42. std::unique_lock<std::mutex> lock(mutex);
  43. int i = counter++;
  44. if (i >= n_token) {
  45. nll += local_nll; nll2 += local_nll2;
  46. break;
  47. }
  48. lock.unlock();
  49. double v = -log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
  50. local_nll += v;
  51. local_nll2 += v*v;
  52. }
  53. };
  54. for (auto& w : workers) w = std::thread(compute);
  55. compute();
  56. for (auto& w : workers) w.join();
  57. }
  58. void perplexity_v2(llama_context * ctx, const gpt_params & params) {
  59. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  60. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  61. // Output: `perplexity: 13.5106 [114/114]`
  62. // BOS tokens will be added for each chunk before eval
  63. if (params.ppl_stride <= 0) {
  64. fprintf(stderr, "%s: stride is %d but must be greater than zero!\n",__func__,params.ppl_stride);
  65. return;
  66. }
  67. const bool is_spm = llama_vocab_type(ctx) == LLAMA_VOCAB_TYPE_SPM;
  68. const bool add_bos = is_spm;
  69. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  70. auto tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  71. const int calc_chunk = params.n_ctx;
  72. fprintf(stderr, "%s: have %zu tokens. Calculation chunk = %d\n", __func__, tokens.size(), calc_chunk);
  73. if (int(tokens.size()) <= calc_chunk) {
  74. fprintf(stderr, "%s: there are only %zu tokens, this is not enough for a context size of %d and stride %d\n",__func__,
  75. tokens.size(), params.n_ctx, params.ppl_stride);
  76. return;
  77. }
  78. const int n_chunk_max = (tokens.size() - calc_chunk + params.ppl_stride - 1) / params.ppl_stride;
  79. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  80. const int n_vocab = llama_n_vocab(ctx);
  81. const int n_batch = params.n_batch;
  82. int count = 0;
  83. double nll = 0.0;
  84. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  85. for (int i = 0; i < n_chunk; ++i) {
  86. const int start = i * params.ppl_stride;
  87. const int end = start + calc_chunk;
  88. const int num_batches = (calc_chunk + n_batch - 1) / n_batch;
  89. //fprintf(stderr, "%s: evaluating %d...%d using %d batches\n", __func__, start, end, num_batches);
  90. std::vector<float> logits;
  91. const auto t_start = std::chrono::high_resolution_clock::now();
  92. for (int j = 0; j < num_batches; ++j) {
  93. const int batch_start = start + j * n_batch;
  94. const int batch_size = std::min(end - batch_start, n_batch);
  95. //fprintf(stderr, " Batch %d: starts at %d, size is %d, n_past is %d\n",j,batch_start,batch_size,j * n_batch);
  96. if (llama_eval(ctx, tokens.data() + batch_start, batch_size, j * n_batch, params.n_threads)) {
  97. //fprintf(stderr, "%s : failed to eval\n", __func__);
  98. return;
  99. }
  100. // save original token and restore it after eval
  101. const auto token_org = tokens[batch_start];
  102. // add BOS token for the first batch of each chunk
  103. if (add_bos && j == 0) {
  104. tokens[batch_start] = llama_token_bos(ctx);
  105. }
  106. const auto batch_logits = llama_get_logits(ctx);
  107. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  108. if (j == 0) {
  109. tokens[batch_start] = token_org;
  110. }
  111. }
  112. const auto t_end = std::chrono::high_resolution_clock::now();
  113. if (i == 0) {
  114. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  115. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  116. int total_seconds = (int)(t_total * n_chunk);
  117. if (total_seconds >= 60*60) {
  118. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  119. total_seconds = total_seconds % (60*60);
  120. }
  121. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  122. }
  123. //fprintf(stderr, "%s: using tokens %d...%d\n",__func__,params.n_ctx - params.ppl_stride + start, params.n_ctx + start);
  124. for (int j = params.n_ctx - params.ppl_stride - 1; j < params.n_ctx - 1; ++j) {
  125. // Calculate probability of next token, given the previous ones.
  126. const std::vector<float> tok_logits(
  127. logits.begin() + (j + 0) * n_vocab,
  128. logits.begin() + (j + 1) * n_vocab);
  129. const float prob = softmax(tok_logits)[tokens[start + j + 1]];
  130. nll += -std::log(prob);
  131. ++count;
  132. }
  133. // perplexity is e^(average negative log-likelihood)
  134. if (params.ppl_output_type == 0) {
  135. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  136. } else {
  137. printf("%8d %.4lf\n", i*params.ppl_stride, std::exp(nll / count));
  138. }
  139. fflush(stdout);
  140. }
  141. printf("\n");
  142. }
  143. void perplexity(llama_context * ctx, const gpt_params & params) {
  144. if (params.ppl_stride > 0) {
  145. perplexity_v2(ctx, params);
  146. return;
  147. }
  148. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  149. // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  150. // Output: `perplexity: 13.5106 [114/114]`
  151. // BOS tokens will be added for each chunk before eval
  152. const bool is_spm = llama_vocab_type(ctx) == LLAMA_VOCAB_TYPE_SPM;
  153. const bool add_bos = is_spm;
  154. fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
  155. auto tokens = ::llama_tokenize(ctx, params.prompt, add_bos);
  156. const int n_chunk_max = tokens.size() / params.n_ctx;
  157. const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
  158. const int n_vocab = llama_n_vocab(ctx);
  159. const int n_batch = params.n_batch;
  160. int count = 0;
  161. double nll = 0.0;
  162. double nll2 = 0.0;
  163. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  164. std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
  165. for (int i = 0; i < n_chunk; ++i) {
  166. const int start = i * params.n_ctx;
  167. const int end = start + params.n_ctx;
  168. const int num_batches = (params.n_ctx + n_batch - 1) / n_batch;
  169. std::vector<float> logits;
  170. const auto t_start = std::chrono::high_resolution_clock::now();
  171. for (int j = 0; j < num_batches; ++j) {
  172. const int batch_start = start + j * n_batch;
  173. const int batch_size = std::min(end - batch_start, n_batch);
  174. // save original token and restore it after eval
  175. const auto token_org = tokens[batch_start];
  176. // add BOS token for the first batch of each chunk
  177. if (add_bos && j == 0) {
  178. tokens[batch_start] = llama_token_bos(ctx);
  179. }
  180. if (llama_eval(ctx, tokens.data() + batch_start, batch_size, j * n_batch, params.n_threads)) {
  181. fprintf(stderr, "%s : failed to eval\n", __func__);
  182. return;
  183. }
  184. // restore the original token in case it was set to BOS
  185. tokens[batch_start] = token_org;
  186. const auto batch_logits = llama_get_logits(ctx);
  187. logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
  188. }
  189. const auto t_end = std::chrono::high_resolution_clock::now();
  190. if (i == 0) {
  191. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  192. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  193. int total_seconds = (int)(t_total * n_chunk);
  194. if (total_seconds >= 60*60) {
  195. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  196. total_seconds = total_seconds % (60*60);
  197. }
  198. fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
  199. }
  200. // We get the logits for all the tokens in the context window (params.n_ctx)
  201. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  202. // calculate the perplexity over the last half of the window (so the model always has
  203. // some context to predict the token).
  204. //
  205. // We rely on the fact that attention in the forward pass only looks at previous
  206. // tokens here, so the logits returned for each token are an accurate representation
  207. // of what the model would have predicted at that point.
  208. //
  209. // Example, we have a context window of 512, we will compute perplexity for each of the
  210. // last 256 tokens. Then, we split the input up into context window size chunks to
  211. // process the entire prompt.
  212. const int first = std::min(512, params.n_ctx/2);
  213. process_logits(n_vocab, logits.data() + first*n_vocab, tokens.data() + start + first, params.n_ctx - 1 - first, workers, nll, nll2);
  214. count += params.n_ctx - first - 1;
  215. // perplexity is e^(average negative log-likelihood)
  216. if (params.ppl_output_type == 0) {
  217. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  218. } else {
  219. double av = nll/count;
  220. double av2 = nll2/count - av*av;
  221. if (av2 > 0) av2 = sqrt(av2/(count-1));
  222. printf("%8d %.4lf %4lf %4lf\n", i*params.n_ctx, std::exp(nll / count), av, av2);
  223. }
  224. fflush(stdout);
  225. }
  226. printf("\n");
  227. nll2 /= count;
  228. nll /= count;
  229. nll2 -= nll * nll;
  230. if (nll2 > 0) {
  231. nll2 = sqrt(nll2/(count-1));
  232. double ppl = exp(nll);
  233. printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
  234. } else {
  235. printf("Unexpected negative standard deviation of log(prob)\n");
  236. }
  237. }
  238. std::vector<float> hellaswag_evaluate_tokens(llama_context * ctx, const std::vector<int>& tokens, int n_past, int n_batch,
  239. int n_vocab, int n_thread) {
  240. std::vector<float> result;
  241. result.reserve(tokens.size() * n_vocab);
  242. size_t n_chunk = (tokens.size() + n_batch - 1)/n_batch;
  243. for (size_t i_chunk = 0; i_chunk < n_chunk; ++i_chunk) {
  244. size_t n_tokens = tokens.size() - i_chunk * n_batch;
  245. n_tokens = std::min(n_tokens, size_t(n_batch));
  246. if (llama_eval(ctx, tokens.data() + i_chunk * n_batch, n_tokens, n_past, n_thread)) {
  247. fprintf(stderr, "%s : failed to eval\n", __func__);
  248. return {};
  249. }
  250. const auto logits = llama_get_logits(ctx);
  251. result.insert(result.end(), logits, logits + n_tokens * n_vocab);
  252. n_past += n_tokens;
  253. }
  254. return result;
  255. }
  256. void hellaswag_score(llama_context * ctx, const gpt_params & params) {
  257. // Calculates hellaswag score (acc_norm) from prompt
  258. //
  259. // Data extracted from the HellaSwag validation dataset (MIT license) https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl
  260. // All used data fields are preprocessed as in https://github.com/EleutherAI/lm-evaluation-harness/blob/df3da98c5405deafd519c2ddca52bb7c3fe36bef/lm_eval/tasks/hellaswag.py#L62-L68
  261. //
  262. // All 10042 tasks should be extracted to keep the results standardized like other implementations.
  263. //
  264. // Datafile layout:
  265. // ['??'] denotes json fields
  266. // 6 lines per task:
  267. // ['activity_label'] + ": " +['ctx'] - The first part of the query, the context
  268. // ['label'] - The index the best common sense ending aka gold ending
  269. // ['endings'][0] - Endings added to the first part of the query
  270. // ['endings'][1]
  271. // ['endings'][2]
  272. // ['endings'][3]
  273. std::vector<std::string> prompt_lines;
  274. std::istringstream strstream(params.prompt);
  275. std::string line;
  276. while (std::getline(strstream,line,'\n')) {
  277. prompt_lines.push_back(line);
  278. }
  279. if( prompt_lines.size() % 6 != 0) {
  280. fprintf(stderr, "%s : number of lines in prompt not a multiple of 6.\n", __func__);
  281. return;
  282. }
  283. size_t hs_task_count = prompt_lines.size()/6;
  284. fprintf(stderr, "%s : loaded %zu tasks from prompt.\n", __func__, hs_task_count);
  285. const bool is_spm = llama_vocab_type(ctx) == LLAMA_VOCAB_TYPE_SPM;
  286. // This is needed as usual for LLaMA models
  287. const bool add_bos = is_spm;
  288. // Number of tasks to use when computing the score
  289. if ( params.hellaswag_tasks < hs_task_count ) {
  290. hs_task_count = params.hellaswag_tasks;
  291. }
  292. // The tasks should be randomized so the score stabilizes quickly.
  293. bool randomize_tasks = true;
  294. // The random seed should not impact the final result if the computation is done over enough tasks, so kept hardcoded for now
  295. std::mt19937 rng(1);
  296. // Dataholder for hellaswag tasks
  297. struct hs_data_t {
  298. std::string context;
  299. size_t gold_ending_idx;
  300. std::string ending[4];
  301. size_t ending_logprob_count[4];
  302. double ending_logprob[4];
  303. };
  304. fprintf(stderr, "%s : selecting %zu %s tasks.\n", __func__, hs_task_count, (randomize_tasks?"randomized":"the first") );
  305. // Select and read data from prompt lines
  306. hs_data_t *hs_data = new hs_data_t[hs_task_count];
  307. for (size_t i=0; i < hs_task_count; i++) {
  308. size_t idx = i;
  309. // Select a random example of those left in the prompt
  310. if (randomize_tasks) {
  311. std::uniform_int_distribution<size_t> dist(0, prompt_lines.size()/6-1 ) ;
  312. idx = dist(rng);
  313. }
  314. hs_data[i].context = prompt_lines[idx*6];
  315. hs_data[i].gold_ending_idx = std::stoi( prompt_lines[idx*6+1] );
  316. for (size_t j=0; j < 4; j++) {
  317. hs_data[i].ending[j] = " " + prompt_lines[idx*6+2+j];
  318. }
  319. // Delete the selected random example from the prompt
  320. if (randomize_tasks) {
  321. prompt_lines.erase( std::next(prompt_lines.begin(),idx*6) , std::next(prompt_lines.begin(),idx*6+6) );
  322. }
  323. }
  324. fprintf(stderr, "%s : calculating hellaswag score over selected tasks.\n", __func__);
  325. printf("\ntask\tacc_norm\n");
  326. double acc = 0.0f;
  327. const int n_vocab = llama_n_vocab(ctx);
  328. std::vector<float> tok_logits(n_vocab);
  329. for (size_t task_idx = 0; task_idx < hs_task_count; task_idx++) {
  330. // Tokenize the context to count tokens
  331. std::vector<int> context_embd = ::llama_tokenize(ctx, hs_data[task_idx].context, add_bos);
  332. size_t context_size = context_embd.size();
  333. // Do the 1st ending
  334. // In this case we include the context when evaluating
  335. auto query_embd = ::llama_tokenize(ctx, hs_data[task_idx].context + hs_data[task_idx].ending[0], add_bos);
  336. auto query_size = query_embd.size();
  337. //printf("First query: %d\n",(int)query_size);
  338. // Stop if query wont fit the ctx window
  339. if (query_size > (size_t)params.n_ctx) {
  340. fprintf(stderr, "%s : number of tokens in query %zu > n_ctxl\n", __func__, query_size);
  341. return;
  342. }
  343. // Speedup small evaluations by evaluating atleast 32 tokens
  344. if (query_size < 32) {
  345. query_embd.resize(32);
  346. }
  347. auto logits = hellaswag_evaluate_tokens(ctx, query_embd, 0, params.n_batch, n_vocab, params.n_threads);
  348. if (logits.empty()) {
  349. fprintf(stderr, "%s : failed to eval\n", __func__);
  350. return;
  351. }
  352. std::memcpy(tok_logits.data(), logits.data() + (context_size-1)*n_vocab, n_vocab*sizeof(float));
  353. const auto first_probs = softmax(tok_logits);
  354. hs_data[task_idx].ending_logprob_count[0] = 1;
  355. hs_data[task_idx].ending_logprob[0] = std::log(first_probs[query_embd[context_size]]);
  356. // Calculate the logprobs over the ending
  357. for (size_t j = context_size; j < query_size - 1; j++) {
  358. std::memcpy(tok_logits.data(), logits.data() + j*n_vocab, n_vocab*sizeof(float));
  359. const float prob = softmax(tok_logits)[query_embd[j + 1]];
  360. hs_data[task_idx].ending_logprob[0] += std::log(prob);
  361. hs_data[task_idx].ending_logprob_count[0]++;
  362. }
  363. // Calculate the mean token logprob for acc_norm
  364. hs_data[task_idx].ending_logprob[0] /= hs_data[task_idx].ending_logprob_count[0];
  365. // Do the remaining endings
  366. // For these, we use the bare ending with n_past = context_size
  367. //
  368. for (size_t ending_idx = 1; ending_idx < 4; ending_idx++) {
  369. // Tokenize the query
  370. query_embd = ::llama_tokenize(ctx, hs_data[task_idx].ending[ending_idx], false);
  371. query_size = query_embd.size();
  372. // Stop if query wont fit the ctx window
  373. if (context_size + query_size > (size_t)params.n_ctx) {
  374. fprintf(stderr, "%s : number of tokens in query %zu > n_ctxl\n", __func__, query_size);
  375. return;
  376. }
  377. // Speedup small evaluations by evaluating atleast 32 tokens
  378. // No, resizing to 32 is actually slightly slower (at least on CUDA)
  379. //if (query_size < 32) {
  380. // query_embd.resize(32);
  381. //}
  382. // Evaluate the query
  383. logits = hellaswag_evaluate_tokens(ctx, query_embd, context_size, params.n_batch, n_vocab, params.n_threads);
  384. if (logits.empty()) {
  385. fprintf(stderr, "%s : failed to eval\n", __func__);
  386. return;
  387. }
  388. hs_data[task_idx].ending_logprob_count[ending_idx] = 1;
  389. hs_data[task_idx].ending_logprob[ending_idx] = std::log(first_probs[query_embd[0]]);
  390. // Calculate the logprobs over the ending
  391. for (size_t j = 0; j < query_size - 1; j++) {
  392. std::memcpy(tok_logits.data(), logits.data() + j*n_vocab, n_vocab*sizeof(float));
  393. const float prob = softmax(tok_logits)[query_embd[j + 1]];
  394. hs_data[task_idx].ending_logprob[ending_idx] += std::log(prob);
  395. hs_data[task_idx].ending_logprob_count[ending_idx]++;
  396. }
  397. // Calculate the mean token logprob for acc_norm
  398. hs_data[task_idx].ending_logprob[ending_idx] /= hs_data[task_idx].ending_logprob_count[ending_idx];
  399. // printf("task %lu, ending %lu, whole_len %lu, context_len %lu, ending_logprob_count %lu, ending_logprob %.4f\n",
  400. // task_idx,ending_idx,whole_size,context_size, hs_data[task_idx].ending_logprob_count[ending_idx], hs_data[task_idx].ending_logprob[ending_idx] );
  401. }
  402. // Find the ending with maximum logprob
  403. size_t ending_logprob_max_idx = 0;
  404. double ending_logprob_max_val = hs_data[task_idx].ending_logprob[0];
  405. for (size_t j = 1; j < 4; j++) {
  406. if (hs_data[task_idx].ending_logprob[j] > ending_logprob_max_val) {
  407. ending_logprob_max_idx = j;
  408. ending_logprob_max_val = hs_data[task_idx].ending_logprob[j];
  409. }
  410. }
  411. // printf("max logprob ending idx %lu, gold ending idx %lu\n", ending_logprob_max_idx, hs_data[task_idx].gold_ending_idx);
  412. // If the gold ending got the maximum logprobe add one accuracy point
  413. if (ending_logprob_max_idx == hs_data[task_idx].gold_ending_idx) {
  414. acc += 1.0;
  415. }
  416. // Print the accumulated accuracy mean x 100
  417. printf("%zu\t%.8lf\n",task_idx+1, acc/double(task_idx+1)*100.0);
  418. fflush(stdout);
  419. }
  420. delete [] hs_data;
  421. printf("\n");
  422. }
  423. int main(int argc, char ** argv) {
  424. gpt_params params;
  425. params.n_batch = 512;
  426. if (gpt_params_parse(argc, argv, params) == false) {
  427. return 1;
  428. }
  429. params.perplexity = true;
  430. params.n_batch = std::min(params.n_batch, params.n_ctx);
  431. if (params.ppl_stride > 0) {
  432. fprintf(stderr, "Will perform strided perplexity calculation -> adjusting context size from %d to %d\n",
  433. params.n_ctx, params.n_ctx + params.ppl_stride/2);
  434. params.n_ctx += params.ppl_stride/2;
  435. }
  436. if (params.n_ctx > 2048) {
  437. fprintf(stderr, "%s: warning: model might not support context sizes greater than 2048 tokens (%d specified);"
  438. "expect poor results\n", __func__, params.n_ctx);
  439. }
  440. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  441. if (params.seed == LLAMA_DEFAULT_SEED) {
  442. params.seed = time(NULL);
  443. }
  444. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  445. std::mt19937 rng(params.seed);
  446. if (params.random_prompt) {
  447. params.prompt = gpt_random_prompt(rng);
  448. }
  449. llama_backend_init(params.numa);
  450. llama_model * model;
  451. llama_context * ctx;
  452. // load the model and apply lora adapter, if any
  453. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  454. if (model == NULL) {
  455. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  456. return 1;
  457. }
  458. // print system information
  459. {
  460. fprintf(stderr, "\n");
  461. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  462. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  463. }
  464. if (params.hellaswag) {
  465. hellaswag_score(ctx, params);
  466. } else {
  467. perplexity(ctx, params);
  468. }
  469. llama_print_timings(ctx);
  470. llama_free(ctx);
  471. llama_free_model(model);
  472. llama_backend_free();
  473. return 0;
  474. }