KBaba7/llama.cpp
0
1#include "arg.h"2#include "common.h"3#include "log.h"4#include "llama.h"5 6#include <algorithm>7#include <array>8#include <atomic>9#include <cmath>10#include <cstdio>11#include <cstring>12#include <ctime>13#include <fstream>14#include <mutex>15#include <random>16#include <sstream>17#include <thread>18#include <vector>19 20#if defined(_MSC_VER)21#pragma warning(disable: 4244 4267) // possible loss of data22#endif23 24struct results_perplexity {25 std::vector<llama_token> tokens;26 double ppl_value;27 std::vector<float> logits;28 std::vector<float> probs;29};30 31struct results_log_softmax {32 double log_softmax;33 float logit;34 float prob;35};36 37static std::vector<float> softmax(const std::vector<float>& logits) {38 std::vector<float> probs(logits.size());39 float max_logit = logits[0];40 for (float v : logits) {41 max_logit = std::max(max_logit, v);42 }43 double sum_exp = 0.0;44 for (size_t i = 0; i < logits.size(); i++) {45 // Subtract the maximum logit value from the current logit value for numerical stability46 const float logit = logits[i] - max_logit;47 const float exp_logit = expf(logit);48 sum_exp += exp_logit;49 probs[i] = exp_logit;50 }51 for (size_t i = 0; i < probs.size(); i++) {52 probs[i] /= sum_exp;53 }54 return probs;55}56 57static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {58 float max_logit = logits[0];59 for (int i = 1; i < n_vocab; ++i) {60 max_logit = std::max(max_logit, logits[i]);61 }62 double sum_exp = 0.0;63 for (int i = 0; i < n_vocab; ++i) {64 sum_exp += expf(logits[i] - max_logit);65 }66 return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};67}68 69static inline int nearest_int(float fval) {70 //assert(fval <= 4194303.f);71 float val = fval + 12582912.f;72 int i; memcpy(&i, &val, sizeof(int));73 return (i & 0x007fffff) - 0x00400000;74}75 76static double log_softmax(int n_vocab, const float * logits, uint16_t * log_prob, int tok) {77 float max_logit = logits[0];78 float min_logit = logits[0];79 for (int i = 1; i < n_vocab; ++i) {80 max_logit = std::max(max_logit, logits[i]);81 min_logit = std::min(min_logit, logits[i]);82 }83 min_logit = std::max(min_logit, max_logit - 16);84 double sum_exp = 0.0;85 for (int i = 0; i < n_vocab; ++i) {86 sum_exp += expf(logits[i] - max_logit);87 }88 const float log_sum_exp = log(sum_exp);89 const float min_log_prob = min_logit - max_logit - log_sum_exp;90 const float scale = (max_logit - min_logit)/65535.f;91 float * d = (float *)log_prob;92 d[0] = scale;93 d[1] = min_log_prob;94 log_prob += 4;95 if (scale) {96 const float inv_scale = 1/scale;97 for (int i = 0; i < n_vocab; ++i) {98 log_prob[i] = logits[i] > min_logit ? nearest_int(inv_scale*(logits[i] - min_logit)) : 0;99 }100 } else {101 std::memset(log_prob, 0, n_vocab*sizeof(uint16_t));102 }103 return max_logit + log_sum_exp - logits[tok];104}105 106static void process_logits(107 int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,108 double & nll, double & nll2, float * logit_history, float * prob_history109) {110 std::mutex mutex;111 int counter = 0;112 auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {113 double local_nll = 0;114 double local_nll2 = 0;115 while (true) {116 std::unique_lock<std::mutex> lock(mutex);117 int i = counter++;118 if (i >= n_token) {119 nll += local_nll; nll2 += local_nll2;120 break;121 }122 lock.unlock();123 const results_log_softmax results = log_softmax(n_vocab, logits + size_t(i)*n_vocab, tokens[i+1]);124 const double v = -results.log_softmax;125 local_nll += v;126 local_nll2 += v*v;127 128 logit_history[i] = results.logit;129 prob_history[i] = results.prob;130 }131 };132 for (auto & w : workers) {133 w = std::thread(compute);134 }135 compute();136 for (auto & w : workers) {137 w.join();138 }139}140 141static void process_logits(std::ostream& out, int n_vocab, const float * logits, const int * tokens, int n_token,142 std::vector<std::thread> & workers, std::vector<uint16_t> & log_probs, double & nll, double & nll2) {143 std::mutex mutex;144 const int nv = 2*((n_vocab + 1)/2) + 4;145 int counter = 0;146 auto compute = [&mutex, &counter, &log_probs, &nll, &nll2, n_vocab, logits, tokens, n_token, nv] () {147 double local_nll = 0;148 double local_nll2 = 0;149 while (true) {150 std::unique_lock<std::mutex> lock(mutex);151 int i = counter++;152 if (i >= n_token) {153 nll += local_nll; nll2 += local_nll2;154 break;155 }156 lock.unlock();157 const double v = log_softmax(n_vocab, logits + size_t(i)*n_vocab, log_probs.data() + i*nv, tokens[i+1]);158 local_nll += v;159 local_nll2 += v*v;160 }161 };162 for (auto & w : workers) {163 w = std::thread(compute);164 }165 compute();166 for (auto & w : workers) {167 w.join();168 }169 out.write((const char *)log_probs.data(), n_token*nv*sizeof(uint16_t));170}171 172struct kl_divergence_result {173 double sum_nll = 0.0;174 double sum_nll2 = 0.0;175 double sum_nll_base = 0.0;176 double sum_nll_base2 = 0.0;177 double sum_nll_nll_base = 0.0;178 double sum_kld = 0.0;179 double sum_kld2 = 0.0;180 double sum_p_diff = 0.0;181 double sum_p_diff2 = 0.0;182 double sum_p_diff4 = 0.0;183 float max_p_diff = 0.0f;184 size_t n_same_top = 0.0;185 size_t count = 0.0;186};187 188static std::pair<double, float> log_softmax(int n_vocab, const float * logits, const uint16_t * base_log_prob, int tok, kl_divergence_result & kld) {189 float max_logit = logits[0];190 int imax = 0;191 for (int i = 1; i < n_vocab; ++i) {192 if (logits[i] > max_logit) {193 max_logit = logits[i];194 imax = i;195 }196 }197 double sum_exp = 0.0;198 for (int i = 0; i < n_vocab; ++i) {199 sum_exp += expf(logits[i] - max_logit);200 }201 const float log_sum_exp = log(sum_exp);202 const float * d = (const float *)base_log_prob;203 const float scale = d[0];204 const float min_log_prob = d[1];205 base_log_prob += 4;206 207 const float nll = max_logit + log_sum_exp - logits[tok];208 kld.sum_nll += nll;209 kld.sum_nll2 += nll*nll;210 211 const float nll_base = -(scale*base_log_prob[tok] + min_log_prob);212 kld.sum_nll_base += nll_base;213 kld.sum_nll_base2 += nll_base*nll_base;214 215 kld.sum_nll_nll_base += nll*nll_base;216 217 max_logit += log_sum_exp;218 double sum = 0;219 int imax_base = -1;220 float p_log_base_max = 0;221 for (int i = 0; i < n_vocab; ++i) {222 const float p_log_base = scale*base_log_prob[i] + min_log_prob;223 if (i == 0 || p_log_base > p_log_base_max) {224 p_log_base_max = p_log_base;225 imax_base = i;226 }227 if (p_log_base > -16.f) {228 const float p_base = expf(p_log_base);229 sum += p_base * (p_log_base - logits[i] + max_logit);230 }231 }232 kld.sum_kld += sum;233 kld.sum_kld2 += sum*sum;234 ++kld.count;235 if (imax == imax_base) {236 ++kld.n_same_top;237 }238 239 const float p_base = expf(-nll_base);240 const float p = expf(-nll);241 const float p_diff = p - p_base;242 kld.sum_p_diff += p_diff;243 const double p_diff2 = p_diff*p_diff;244 kld.sum_p_diff2 += p_diff2;245 kld.sum_p_diff4 += p_diff2*p_diff2;246 kld.max_p_diff = std::max(kld.max_p_diff, std::fabs(p_diff));247 248 return std::make_pair(sum, p_diff);249}250 251static void process_logits(int n_vocab, const float * logits, const int * tokens, int n_token,252 std::vector<std::thread> & workers, const std::vector<uint16_t> & base_log_probs, kl_divergence_result & kld,253 float * kld_values, float * p_diff_values) {254 std::mutex mutex;255 const int nv = 2*((n_vocab + 1)/2) + 4;256 int counter = 0;257 auto compute = [&mutex, &counter, &base_log_probs, &kld, n_vocab, logits, tokens, n_token, nv, kld_values, p_diff_values] () {258 kl_divergence_result local_kld;259 while (true) {260 std::unique_lock<std::mutex> lock(mutex);261 int i = counter++;262 if (i >= n_token) {263 kld.sum_nll += local_kld.sum_nll;264 kld.sum_nll2 += local_kld.sum_nll2;265 kld.sum_nll_base += local_kld.sum_nll_base;266 kld.sum_nll_base2 += local_kld.sum_nll_base2;267 kld.sum_nll_nll_base += local_kld.sum_nll_nll_base;268 kld.sum_kld += local_kld.sum_kld;269 kld.sum_kld2 += local_kld.sum_kld2;270 kld.sum_p_diff += local_kld.sum_p_diff;271 kld.sum_p_diff2 += local_kld.sum_p_diff2;272 kld.sum_p_diff4 += local_kld.sum_p_diff4;273 kld.n_same_top += local_kld.n_same_top;274 kld.max_p_diff = std::max(kld.max_p_diff, local_kld.max_p_diff);275 kld.count += local_kld.count;276 break;277 }278 lock.unlock();279 std::pair<double, float> v = log_softmax(n_vocab, logits + size_t(i)*n_vocab, base_log_probs.data() + i*nv, tokens[i+1], local_kld);280 kld_values[i] = (float)v.first;281 p_diff_values[i] = v.second;282 }283 };284 for (auto & w : workers) {285 w = std::thread(compute);286 }287 compute();288 for (auto & w : workers) {289 w.join();290 }291}292 293static results_perplexity perplexity_v2(llama_context * ctx, const common_params & params) {294 // Download: https://huggingface.co/datasets/ggml-org/ci/resolve/main/wikitext-2-raw-v1.zip295 // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`296 // Output: `perplexity: 13.5106 [114/114]`297 // BOS tokens will be added for each chunk before eval298 299 const llama_model * model = llama_get_model(ctx);300 const llama_vocab * vocab = llama_model_get_vocab(model);301 302 const bool add_bos = llama_vocab_get_add_bos(vocab);303 GGML_ASSERT(!llama_vocab_get_add_eos(vocab));304 305 LOG_INF("%s: tokenizing the input ..\n", __func__);306 307 std::vector<llama_token> tokens = common_tokenize(ctx, params.prompt, true);308 309 const int n_ctx = llama_n_ctx(ctx);310 311 if (int(tokens.size()) < 2*n_ctx) {312 LOG_ERR("%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*n_ctx,313 n_ctx);314 LOG_ERR("%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());315 return {std::move(tokens), 0., {}, {}};316 }317 318 std::vector<float> logit_history;319 std::vector<float> prob_history;320 321 logit_history.resize(tokens.size());322 prob_history.resize(tokens.size());323 324 if (params.ppl_stride <= 0) {325 LOG_ERR("%s: stride is %d but must be greater than zero!\n",__func__,params.ppl_stride);326 return {tokens, -1, logit_history, prob_history};327 }328 329 const int calc_chunk = n_ctx;330 331 LOG_INF("%s: have %zu tokens. Calculation chunk = %d\n", __func__, tokens.size(), calc_chunk);332 333 if (int(tokens.size()) <= calc_chunk) {334 LOG_ERR("%s: there are only %zu tokens, this is not enough for a context size of %d and stride %d\n",__func__,335 tokens.size(), n_ctx, params.ppl_stride);336 return {tokens, -1, logit_history, prob_history};337 }338 339 const int n_chunk_max = (tokens.size() - calc_chunk + params.ppl_stride - 1) / params.ppl_stride;340 341 const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);342 const int n_batch = params.n_batch;343 344 const int n_vocab = llama_vocab_n_tokens(vocab);345 346 int count = 0;347 double nll = 0.0;348 349 LOG_INF("%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);350 351 for (int i = 0; i < n_chunk; ++i) {352 const int start = i * params.ppl_stride;353 const int end = start + calc_chunk;354 355 const int num_batches = (calc_chunk + n_batch - 1) / n_batch;356 //LOG_DBG("%s: evaluating %d...%d using %d batches\n", __func__, start, end, num_batches);357 358 std::vector<float> logits;359 360 const auto t_start = std::chrono::high_resolution_clock::now();361 362 // clear the KV cache363 llama_kv_cache_clear(ctx);364 365 llama_batch batch = llama_batch_init(n_batch, 0, 1);366 367 for (int j = 0; j < num_batches; ++j) {368 const int batch_start = start + j * n_batch;369 const int batch_size = std::min(end - batch_start, n_batch);370 371 common_batch_clear(batch);372 for (int i = 0; i < batch_size; i++) {373 common_batch_add(batch, tokens[batch_start + i], j*n_batch + i, {0}, true);374 }375 376 //LOG_DBG(" Batch %d: starts at %d, size is %d, n_past is %d\n",j,batch_start,batch_size,j * n_batch);377 if (llama_decode(ctx, batch)) {378 //LOG_ERR("%s : failed to eval\n", __func__);379 llama_batch_free(batch);380 return {tokens, -1, logit_history, prob_history};381 }382 383 // save original token and restore it after eval384 const auto token_org = tokens[batch_start];385 386 // add BOS token for the first batch of each chunk387 if (add_bos && j == 0) {388 tokens[batch_start] = llama_vocab_bos(vocab);389 }390 391 const auto * batch_logits = llama_get_logits(ctx);392 logits.insert(logits.end(), batch_logits, batch_logits + size_t(batch_size) * n_vocab);393 394 if (j == 0) {395 tokens[batch_start] = token_org;396 }397 }398 399 llama_batch_free(batch);400 401 const auto t_end = std::chrono::high_resolution_clock::now();402 403 if (i == 0) {404 const float t_total = std::chrono::duration<float>(t_end - t_start).count();405 LOG_INF("%s: %.2f seconds per pass - ETA ", __func__, t_total);406 int total_seconds = (int)(t_total * n_chunk);407 if (total_seconds >= 60*60) {408 LOG("%d hours ", total_seconds / (60*60));409 total_seconds = total_seconds % (60*60);410 }411 LOG("%.2f minutes\n", total_seconds / 60.0);412 }413 414 //LOG_DBG("%s: using tokens %d...%d\n",__func__,params.n_ctx - params.ppl_stride + start, params.n_ctx + start);415 for (int j = n_ctx - params.ppl_stride - 1; j < n_ctx - 1; ++j) {416 // Calculate probability of next token, given the previous ones.417 const std::vector<float> tok_logits(418 logits.begin() + size_t(j + 0) * n_vocab,419 logits.begin() + size_t(j + 1) * n_vocab);420 421 const float prob = softmax(tok_logits)[tokens[start + j + 1]];422 logit_history[start + j + 1] = tok_logits[tokens[start + j + 1]];423 prob_history[start + j + 1] = prob;424 425 nll += -std::log(prob);426 ++count;427 }428 // perplexity is e^(average negative log-likelihood)429 if (params.ppl_output_type == 0) {430 LOG("[%d]%.4lf,", i + 1, std::exp(nll / count));431 } else {432 LOG("%8d %.4lf\n", i*params.ppl_stride, std::exp(nll / count));433 }434 }435 LOG("\n");436 437 return {tokens, std::exp(nll / count), logit_history, prob_history};438}439 440static results_perplexity perplexity(llama_context * ctx, const common_params & params, const int32_t n_ctx) {441 if (params.ppl_stride > 0) {442 return perplexity_v2(ctx, params);443 }444 445 // Download: https://huggingface.co/datasets/ggml-org/ci/resolve/main/wikitext-2-raw-v1.zip446 // Run `./llama-perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`447 // Output: `perplexity: 13.5106 [114/114]`448 // BOS tokens will be added for each chunk before eval449 450 const llama_model * model = llama_get_model(ctx);451 const llama_vocab * vocab = llama_model_get_vocab(model);452 453 const bool add_bos = llama_vocab_get_add_bos(vocab);454 GGML_ASSERT(!llama_vocab_get_add_eos(vocab));455 456 std::ofstream logits_stream;457 if (!params.logits_file.empty()) {458 logits_stream.open(params.logits_file.c_str(), std::ios::binary);459 if (!logits_stream.is_open()) {460 LOG_ERR("%s: failed to open %s for writing\n", __func__, params.logits_file.c_str());461 return {};462 }463 LOG_INF("%s: saving all logits to %s\n", __func__, params.logits_file.c_str());464 logits_stream.write("_logits_", 8);465 logits_stream.write(reinterpret_cast<const char *>(&n_ctx), sizeof(n_ctx));466 }467 468 auto tim1 = std::chrono::high_resolution_clock::now();469 LOG_INF("%s: tokenizing the input ..\n", __func__);470 471 std::vector<llama_token> tokens = common_tokenize(ctx, params.prompt, true);472 473 auto tim2 = std::chrono::high_resolution_clock::now();474 LOG_INF("%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());475 476 if (int(tokens.size()) < 2*n_ctx) {477 LOG_ERR("%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*n_ctx,478 n_ctx);479 LOG_ERR("%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());480 return {std::move(tokens), 0., {}, {}};481 }482 483 std::vector<float> logit_history;484 logit_history.resize(tokens.size());485 486 std::vector<float> prob_history;487 prob_history.resize(tokens.size());488 489 const int n_chunk_max = tokens.size() / n_ctx;490 491 const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);492 const int n_batch = params.n_batch;493 494 const int n_vocab = llama_vocab_n_tokens(vocab);495 496 int count = 0;497 double nll = 0.0;498 double nll2 = 0.0;499 500 const int num_batches = (n_ctx + n_batch - 1) / n_batch;501 const int n_seq = std::max(1, n_batch / n_ctx);502 503 GGML_ASSERT(n_batch < n_ctx || n_batch % n_ctx == 0);504 GGML_ASSERT(params.n_ctx == n_seq * n_ctx);505 506 llama_batch batch = llama_batch_init(std::min(n_batch, n_ctx*n_seq), 0, 1);507 508 std::vector<float> logits;509 if (num_batches > 1) {510 logits.reserve(size_t(n_ctx) * n_vocab);511 }512 513 LOG_INF("%s: calculating perplexity over %d chunks, n_ctx=%d, batch_size=%d, n_seq=%d\n", __func__, n_chunk, n_ctx, n_batch, n_seq);514 515 std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);516 517 std::vector<uint16_t> log_probs;518 if (!params.logits_file.empty()) {519 logits_stream.write((const char *)&n_vocab, sizeof(n_vocab));520 logits_stream.write((const char *)&n_chunk, sizeof(n_chunk));521 logits_stream.write((const char *)tokens.data(), n_chunk*n_ctx*sizeof(tokens[0]));522 const int nv = 2*((n_vocab + 1)/2) + 4;523 log_probs.resize(n_ctx * nv);524 }525 526 // We get the logits for all the tokens in the context window (params.n_ctx)527 // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,528 // calculate the perplexity over the last half of the window (so the model always has529 // some context to predict the token).530 //531 // We rely on the fact that attention in the forward pass only looks at previous532 // tokens here, so the logits returned for each token are an accurate representation533 // of what the model would have predicted at that point.534 //535 // Example, we have a context window of 512, we will compute perplexity for each of the536 // last 256 tokens. Then, we split the input up into context window size chunks to537 // process the entire prompt.538 const int first = n_ctx/2;539 540 for (int i = 0; i < n_chunk; i += n_seq) {541 const int start = i * n_ctx;542 const int end = start + n_ctx;543 544 const int n_seq_batch = std::min(n_seq, n_chunk - i);545 546 const auto t_start = std::chrono::high_resolution_clock::now();547 548 // clear the KV cache549 llama_kv_cache_clear(ctx);550 551 for (int j = 0; j < num_batches; ++j) {552 const int batch_start = start + j * n_batch;553 const int batch_size = std::min(end - batch_start, n_batch);554 555 int n_outputs = 0;556 557 batch.n_tokens = 0;558 for (int seq = 0; seq < n_seq_batch; seq++) {559 int seq_start = batch_start + seq*n_ctx;560 561 // save original token and restore it after eval562 const auto token_org = tokens[seq_start];563 564 // add BOS token for the first batch of each chunk565 if (add_bos && j == 0) {566 tokens[seq_start] = llama_vocab_bos(vocab);567 }568 569 for (int k = 0; k < batch_size; ++k) {570 const int idx = seq*n_ctx + k;571 batch.token [idx] = tokens[seq_start + k];572 batch.pos [idx] = j*n_batch + k;573 batch.n_seq_id[idx] = 1;574 batch.seq_id [idx][0] = seq;575 batch.logits [idx] = batch.pos[idx] >= first ? 1 : 0;576 577 n_outputs += batch.logits[idx] != 0;578 }579 batch.n_tokens += batch_size;580 581 // restore the original token in case it was set to BOS582 tokens[seq_start] = token_org;583 }584 585 if (llama_decode(ctx, batch)) {586 LOG_INF("%s : failed to eval\n", __func__);587 return {tokens, -1, logit_history, prob_history};588 }589 590 if (num_batches > 1 && n_outputs > 0) {591 const auto * batch_logits = llama_get_logits(ctx);592 logits.insert(logits.end(), batch_logits, batch_logits + size_t(n_outputs) * n_vocab);593 }594 }595 596 597 if (i == 0) {598 llama_synchronize(ctx);599 const auto t_end = std::chrono::high_resolution_clock::now();600 const float t_total = std::chrono::duration<float>(t_end - t_start).count();601 LOG_INF("%s: %.2f seconds per pass - ETA ", __func__, t_total);602 int total_seconds = (int)(t_total*n_chunk/n_seq);603 if (total_seconds >= 60*60) {604 LOG("%d hours ", total_seconds / (60*60));605 total_seconds = total_seconds % (60*60);606 }607 LOG("%.2f minutes\n", total_seconds / 60.0);608 }609 610 for (int seq = 0; seq < n_seq_batch; seq++) {611 const float * all_logits = num_batches > 1 ? logits.data() : llama_get_logits_ith(ctx, seq*n_ctx + first);612 613 llama_token * tokens_data = tokens.data() + start + seq*n_ctx + first;614 if (!params.logits_file.empty()) {615 process_logits(logits_stream, n_vocab, all_logits,616 tokens_data, n_ctx - 1 - first,617 workers, log_probs, nll, nll2);618 } else {619 process_logits(n_vocab, all_logits,620 tokens_data, n_ctx - 1 - first,621 workers, nll, nll2,622 logit_history.data() + start + seq*n_ctx + first,623 prob_history.data() + start + seq*n_ctx + first);624 }625 count += n_ctx - first - 1;626 627 // perplexity is e^(average negative log-likelihood)628 if (params.ppl_output_type == 0) {629 LOG("[%d]%.4lf,", i + seq + 1, std::exp(nll / count));630 } else {631 double av = nll/count;632 double av2 = nll2/count - av*av;633 if (av2 > 0) {634 av2 = sqrt(av2/(count-1));635 }636 LOG("%8d %.4lf %4lf %4lf\n", i*n_ctx, std::exp(nll / count), av, av2);637 }638 }639 640 logits.clear();641 }642 LOG("\n");643 644 nll2 /= count;645 nll /= count;646 const double ppl = exp(nll);647 nll2 -= nll * nll;648 if (nll2 > 0) {649 nll2 = sqrt(nll2/(count-1));650 LOG_INF("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);651 } else {652 LOG_ERR("Unexpected negative standard deviation of log(prob)\n");653 }654 655 llama_batch_free(batch);656 657 return {tokens, ppl, logit_history, prob_history};658}659 660static bool decode_helper(llama_context * ctx, llama_batch & batch, std::vector<float> & batch_logits, int n_batch, int n_vocab) {661 int prev_outputs = 0;662 for (int i = 0; i < (int) batch.n_tokens; i += n_batch) {663 const int n_tokens = std::min<int>(n_batch, batch.n_tokens - i);664 665 llama_batch batch_view = {666 n_tokens,667 batch.token + i,668 nullptr,669 batch.pos + i,670 batch.n_seq_id + i,671 batch.seq_id + i,672 batch.logits + i,673 };674 675 const int ret = llama_decode(ctx, batch_view);676 if (ret != 0) {677 LOG_ERR("failed to decode the batch, n_batch = %d, ret = %d\n", n_batch, ret);678 return false;679 }680 681 int n_outputs = 0;682 for (int i = 0; i < n_tokens; ++i) {683 n_outputs += batch_view.logits[i] != 0;684 }685 686 memcpy(batch_logits.data() + size_t(prev_outputs)*n_vocab, llama_get_logits(ctx), size_t(n_outputs)*n_vocab*sizeof(float));687 688 prev_outputs += n_outputs;689 }690 691 return true;692}693 694#define K_TOKEN_CHUNK 4695 696static void compute_logprobs(const float * batch_logits, int n_vocab, std::vector<std::thread>& workers,697 const std::vector<std::pair<size_t, llama_token>>& eval_pairs, std::vector<float>& eval_results) {698 if (eval_results.size() != eval_pairs.size()) {699 eval_results.resize(eval_pairs.size());700 }701 if (eval_pairs.empty()) {702 return;703 }704 705 size_t max_threads = std::min((eval_pairs.size() + K_TOKEN_CHUNK - 1)/K_TOKEN_CHUNK, workers.size());706 707 std::atomic<int> counter(0);708 auto compute = [&counter, &eval_pairs, &eval_results, batch_logits, n_vocab] () {709 float local_logprobs[K_TOKEN_CHUNK];710 while (true) {711 const size_t first = counter.fetch_add(K_TOKEN_CHUNK, std::memory_order_relaxed);712 if (first >= eval_results.size()) {713 break;714 }715 const size_t last = std::min(first + K_TOKEN_CHUNK, eval_results.size());716 for (size_t i = first; i < last; ++i) {717 const auto * logits = batch_logits + eval_pairs[i].first * n_vocab;718 float max_logit = logits[0];719 for (int j = 1; j < n_vocab; ++j) {720 max_logit = std::max(max_logit, logits[j]);721 }722 float sum_p = 0.f;723 for (int j = 0; j < n_vocab; ++j) {724 sum_p += expf(logits[j] - max_logit);725 }726 local_logprobs[i - first] = logits[eval_pairs[i].second] - max_logit - std::log(sum_p);727 }728 std::memcpy(eval_results.data() + first, local_logprobs, (last - first)*sizeof(float));729 }730 };731 732 for (size_t it = 0; it < max_threads; ++it) {733 workers[it] = std::thread(compute);734 }735 for (size_t it = 0; it < max_threads; ++it) {736 workers[it].join();737 }738}739 740static void hellaswag_score(llama_context * ctx, const common_params & params) {741 const llama_model * model = llama_get_model(ctx);742 const llama_vocab * vocab = llama_model_get_vocab(model);743 744 // Calculates hellaswag score (acc_norm) from prompt745 //746 // Data extracted from the HellaSwag validation dataset (MIT license) https://github.com/rowanz/hellaswag/blob/master/data/hellaswag_val.jsonl747 // All used data fields are preprocessed as in https://github.com/EleutherAI/lm-evaluation-harness/blob/df3da98c5405deafd519c2ddca52bb7c3fe36bef/lm_eval/tasks/hellaswag.py#L62-L68748 //749 // All 10042 tasks should be extracted to keep the results standardized like other implementations.750 //751 // Datafile layout:752 // ['??'] denotes json fields753 // 6 lines per task:754 // ['activity_label'] + ": " +['ctx'] - The first part of the query, the context755 // ['label'] - The index the best common sense ending aka gold ending756 // ['endings'][0] - Endings added to the first part of the query757 // ['endings'][1]758 // ['endings'][2]759 // ['endings'][3]760 761 std::vector<std::string> prompt_lines;762 std::istringstream strstream(params.prompt);763 std::string line;764 765 while (std::getline(strstream,line,'\n')) {766 prompt_lines.push_back(line);767 }768 769 if (prompt_lines.size() % 6 != 0) {770 LOG_ERR("%s : number of lines in prompt not a multiple of 6.\n", __func__);771 return;772 }773 774 size_t hs_task_count = prompt_lines.size()/6;775 LOG_INF("%s : loaded %zu tasks from prompt.\n", __func__, hs_task_count);776 777 const bool is_spm = llama_vocab_type(vocab) == LLAMA_VOCAB_TYPE_SPM;778 LOG_INF("================================= is_spm = %d\n", is_spm);779 780 // The tasks should be randomized so the score stabilizes quickly.781 bool randomize_tasks = true;782 783 // Number of tasks to use when computing the score784 if (params.hellaswag_tasks < hs_task_count) {785 hs_task_count = params.hellaswag_tasks;786 }787 788 // The random seed should not impact the final result if the computation is done over enough tasks, so kept hardcoded for now789 std::mt19937 rng(1);790 791 // Dataholder for hellaswag tasks792 struct hs_data_t {793 std::string context;794 size_t gold_ending_idx;795 std::string ending[4];796 size_t ending_logprob_count[4];797 double ending_logprob[4];798 799 size_t i_logits; // starting index of logits in the llama_batch800 size_t common_prefix; // max number of initial tokens that are the same in all sentences801 size_t required_tokens; // needed number of tokens to evaluate all 4 endings802 std::vector<llama_token> seq_tokens[4];803 };804 805 LOG_INF("%s : selecting %zu %s tasks.\n", __func__, hs_task_count, (randomize_tasks?"randomized":"the first") );806 807 // Select and read data from prompt lines808 std::vector<hs_data_t> hs_data(hs_task_count);809 for (size_t i = 0; i < hs_task_count; i++) {810 size_t idx = i;811 812 auto & hs_cur = hs_data[i];813 814 // Select a random example of those left in the prompt815 if (randomize_tasks) {816 std::uniform_int_distribution<size_t> dist(0, prompt_lines.size()/6-1 ) ;817 idx = dist(rng);818 }819 820 hs_cur.context = prompt_lines[idx*6];821 hs_cur.gold_ending_idx = std::stoi( prompt_lines[idx*6+1] );822 for (size_t j = 0; j < 4; j++) {823 hs_cur.ending[j] = prompt_lines[idx*6+2+j];824 hs_cur.seq_tokens[j] = common_tokenize(ctx, hs_cur.context + " " + hs_cur.ending[j], true);825 }826 827 // determine the common prefix of the endings828 hs_cur.common_prefix = 0;829 for (size_t k = 0; k < hs_cur.seq_tokens[0].size(); k++) {830 if (hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[1][k] ||831 hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[2][k] ||832 hs_cur.seq_tokens[0][k] != hs_cur.seq_tokens[3][k]) {833 break;834 }835 hs_cur.common_prefix++;836 }837 hs_cur.required_tokens = hs_cur.common_prefix +838 hs_cur.seq_tokens[0].size() - hs_cur.common_prefix +839 hs_cur.seq_tokens[1].size() - hs_cur.common_prefix +840 hs_cur.seq_tokens[2].size() - hs_cur.common_prefix +841 hs_cur.seq_tokens[3].size() - hs_cur.common_prefix;842 843 //GGML_ASSERT(hs_cur.common_prefix >= ::llama_tokenize(ctx, hs_cur.context, true).size());844 845 // Delete the selected random example from the prompt846 if (randomize_tasks) {847 prompt_lines.erase( std::next(prompt_lines.begin(),idx*6) , std::next(prompt_lines.begin(),idx*6+6) );848 }849 }850 851 LOG_INF("%s : calculating hellaswag score over selected tasks.\n", __func__);852 853 LOG("\ntask\tacc_norm\n");854 855 double acc = 0.0f;856 857 const int n_ctx = llama_n_ctx(ctx);858 const int n_batch = params.n_batch;859 860 const int n_vocab = llama_vocab_n_tokens(vocab);861 862 const int max_tasks_per_batch = 32;863 const int max_seq = std::min(4*max_tasks_per_batch, (int) llama_n_seq_max(ctx));864 865 llama_batch batch = llama_batch_init(n_ctx, 0, 4);866 867 std::vector<float> tok_logits(n_vocab);868 // TODO: this could be made smaller; it's currently the worst-case size869 std::vector<float> batch_logits(size_t(n_ctx)*n_vocab);870 871 std::vector<std::pair<size_t, llama_token>> eval_pairs;872 std::vector<float> eval_results;873 std::vector<std::thread> workers(std::thread::hardware_concurrency());874 875 for (size_t i0 = 0; i0 < hs_task_count; i0++) {876 int n_cur = 0;877 878 size_t i1 = i0;879 size_t i_logits = 0; // this tells us how many logits were needed before this point in the batch880 881 common_batch_clear(batch);882 883 // batch as much tasks as possible into the available context884 // each task has 4 unique sequence ids - one for each ending885 // the common prefix is shared among the 4 sequences to save tokens886 // we extract logits only from the last common token and from all ending tokens of each sequence887 while (n_cur + (int) hs_data[i1].required_tokens <= n_ctx) {888 auto & hs_cur = hs_data[i1];889 int n_logits = 0;890 891 const int s0 = 4*(i1 - i0);892 if (s0 + 4 > max_seq) {893 break;894 }895 896 for (size_t i = 0; i < hs_cur.common_prefix; ++i) {897 common_batch_add(batch, hs_cur.seq_tokens[0][i], i, { s0 + 0, s0 + 1, s0 + 2, s0 + 3 }, false);898 }899 batch.logits[batch.n_tokens - 1] = true; // we need logits for the last token of the common prefix900 n_logits += 1;901 902 for (int s = 0; s < 4; ++s) {903 const size_t seq_tokens_size = hs_cur.seq_tokens[s].size();904 // TODO: don't evaluate the last token of each sequence905 for (size_t i = hs_cur.common_prefix; i < seq_tokens_size; ++i) {906 const bool needs_logits = i < seq_tokens_size - 1;907 common_batch_add(batch, hs_cur.seq_tokens[s][i], i, { s0 + s }, needs_logits);908 n_logits += needs_logits;909 }910 }911 912 hs_cur.i_logits = i_logits;913 i_logits += n_logits;914 915 n_cur += hs_data[i1].required_tokens;916 if (++i1 == hs_task_count) {917 break;918 }919 }920 921 if (i0 == i1) {922 LOG_ERR("%s : task %zu does not fit in the context window\n", __func__, i0);923 return;924 }925 926 llama_kv_cache_clear(ctx);927 928 // decode all tasks [i0, i1)929 if (!decode_helper(ctx, batch, batch_logits, n_batch, n_vocab)) {930 LOG_ERR("%s: llama_decode() failed\n", __func__);931 return;932 }933 934 // Compute log-probs in parallel935 // First we collect all tasks936 eval_pairs.clear();937 for (size_t i = i0; i < i1; ++i) {938 auto & hs_cur = hs_data[i];939 size_t li = 1; // skip the last logit of the common prefix (computed separately below)940 for (int s = 0; s < 4; ++s) {941 for (size_t j = hs_cur.common_prefix; j < hs_cur.seq_tokens[s].size() - 1; j++) {942 eval_pairs.emplace_back(hs_cur.i_logits + li++, hs_cur.seq_tokens[s][j + 1]);943 }944 }945 }946 // Then we do the actual calculation947 compute_logprobs(batch_logits.data(), n_vocab, workers, eval_pairs, eval_results);948 949 size_t ir = 0;950 951 // compute the logprobs for each ending of the decoded tasks952 for (size_t i = i0; i < i1; ++i) {953 auto & hs_cur = hs_data[i];954 955 // get the logits of the last token of the common prefix956 std::memcpy(tok_logits.data(), batch_logits.data() + hs_cur.i_logits*n_vocab, n_vocab*sizeof(float));957 958 const auto first_probs = softmax(tok_logits);959 960 for (int s = 0; s < 4; ++s) {961 hs_cur.ending_logprob_count[s] = 1;962 hs_cur.ending_logprob[s] = std::log(first_probs[hs_cur.seq_tokens[s][hs_cur.common_prefix]]);963 for (size_t j = hs_cur.common_prefix; j < hs_cur.seq_tokens[s].size() - 1; j++) {964 hs_cur.ending_logprob[s] += eval_results[ir++];965 hs_cur.ending_logprob_count[s]++;966 }967 hs_cur.ending_logprob[s] /= hs_cur.ending_logprob_count[s];968 }969 970 // Find the ending with maximum logprob971 size_t ending_logprob_max_idx = 0;972 double ending_logprob_max_val = hs_cur.ending_logprob[0];973 for (size_t s = 1; s < 4; s++) {974 if (hs_cur.ending_logprob[s] > ending_logprob_max_val) {975 ending_logprob_max_idx = s;976 ending_logprob_max_val = hs_cur.ending_logprob[s];977 }978 }979 980 //LOG("max logprob ending idx %lu, gold ending idx %lu\n", ending_logprob_max_idx, hs_cur.gold_ending_idx);981 982 // If the gold ending got the maximum logprobe add one accuracy point983 if (ending_logprob_max_idx == hs_cur.gold_ending_idx) {984 acc += 1.0;985 }986 987 // Print the accumulated accuracy mean x 100988 LOG("%zu\t%.8lf\n", i + 1, acc/double(i + 1)*100.0);989 }990 991 i0 = i1 - 1;992 }993 994 llama_batch_free(batch);995 996 LOG("\n");997}998 999struct winogrande_entry {1000 std::string first;1001 std::string second;1002 std::array<std::string, 2> choices;1003 int answer;1004 1005 size_t i_logits;1006 size_t common_prefix;1007 size_t required_tokens;1008 size_t n_base1; // number of tokens for context + choice 11009 size_t n_base2; // number of tokens for context + choice 21010 std::vector<llama_token> seq_tokens[2];1011};1012 1013static std::vector<winogrande_entry> load_winogrande_from_csv(const std::string & prompt) {1014 std::vector<winogrande_entry> result;1015 std::istringstream in(prompt);1016 std::string line;1017 std::array<int, 4> comma_pos;1018 while (true) {1019 std::getline(in, line);1020 if (in.fail() || in.eof()) break;1021 int ipos = 0;1022 bool quote_open = false;1023 for (int i = 0; i < int(line.size()); ++i) {1024 if (!quote_open) {1025 if (line[i] == ',') {1026 comma_pos[ipos++] = i;1027 if (ipos == 4) break;1028 }1029 else if (line[i] == '"') {1030 quote_open = true;1031 }1032 }1033 else {1034 if (line[i] == '"') {1035 quote_open = false;1036 }1037 }1038 }1039 if (ipos != 4) {1040 LOG_ERR("%s: failed to find comma separators in <%s>\n", __func__, line.c_str());1041 continue;1042 }1043 auto sentence = line[comma_pos[0]+1] == '"' ? line.substr(comma_pos[0]+2, comma_pos[1] - comma_pos[0] - 3)1044 : line.substr(comma_pos[0]+1, comma_pos[1] - comma_pos[0] - 1);1045 auto choice1 = line.substr(comma_pos[1]+1, comma_pos[2] - comma_pos[1] - 1);1046 auto choice2 = line.substr(comma_pos[2]+1, comma_pos[3] - comma_pos[2] - 1);1047 auto answer = line.substr(comma_pos[3]+1, line.size() - comma_pos[3] - 1);1048 auto index = line.substr(0, comma_pos[0]);1049 int where = 0;1050 for ( ; where < int(sentence.size()); ++where) {1051 if (sentence[where] == '_') break;1052 }1053 if (where == int(sentence.size())) {1054 LOG_ERR("%s: no _ in <%s>\n", __func__, sentence.c_str());1055 continue;1056 }1057 std::istringstream stream(answer.c_str());1058 int i_answer; stream >> i_answer;1059 if (stream.fail() || i_answer < 1 || i_answer > 2) {1060 LOG_ERR("%s: failed to parse answer <%s>\n", __func__, answer.c_str());1061 continue;1062 }1063 result.emplace_back();1064 auto& wg = result.back();1065 wg.first = sentence.substr(0, where);1066 wg.second = sentence.substr(where + 1, sentence.size() - where - 1);1067 wg.choices[0] = std::move(choice1);1068 wg.choices[1] = std::move(choice2);1069 wg.answer = i_answer;1070 }1071 return result;1072}1073 1074/*1075 * Evaluates the Winogrande score.1076 * Uses a CSV containing task index, dentence, choice 1, choice 2, answer (1 or 2)1077 * You can get one such dataset from e.g. https://huggingface.co/datasets/ikawrakow/winogrande-eval-for-llama.cpp1078 * As an example, the 1st row in the above dataset is1079 *1080 * 0,Sarah was a much better surgeon than Maria so _ always got the easier cases.,Sarah,Maria,21081 *1082 */1083static void winogrande_score(llama_context * ctx, const common_params & params) {1084 const llama_model * model = llama_get_model(ctx);1085 const llama_vocab * vocab = llama_model_get_vocab(model);1086 1087 constexpr int k_min_trailing_ctx = 3;1088 1089 auto data = load_winogrande_from_csv(params.prompt);1090 if (data.empty()) {1091 LOG_ERR("%s: no tasks\n", __func__);1092 return;1093 }1094 1095 LOG_INF("%s : loaded %zu tasks from prompt.\n", __func__, data.size());1096 1097 if (params.winogrande_tasks > 0 && params.winogrande_tasks < data.size()) {1098 LOG_INF("%s : selecting %zu random tasks\n", __func__, params.winogrande_tasks);1099 std::mt19937 rng(1);1100 std::vector<int> aux(data.size());1101 for (int i = 0; i < int(data.size()); ++i) {1102 aux[i] = i;1103 }1104 float scale = 1/(1.f + (float)rng.max());1105 std::vector<winogrande_entry> selected;1106 selected.resize(params.winogrande_tasks);1107 for (int i = 0; i < int(params.winogrande_tasks); ++i) {1108 int j = int(scale*rng()*aux.size());1109 selected[i] = std::move(data[aux[j]]);1110 aux[j] = aux.back();1111 aux.pop_back();1112 }1113 data = std::move(selected);1114 }1115 1116 LOG_INF("%s : tokenizing selected tasks\n", __func__);1117 1118 for (auto & task : data) {1119 task.seq_tokens[0] = common_tokenize(ctx, task.first + task.choices[0] + task.second, true);1120 task.seq_tokens[1] = common_tokenize(ctx, task.first + task.choices[1] + task.second, true);1121 1122 task.common_prefix = 0;1123 for (size_t k = 0; k < task.seq_tokens[0].size(); k++) {1124 if (task.seq_tokens[0][k] != task.seq_tokens[1][k]) {1125 break;1126 }1127 task.common_prefix++;1128 }1129 1130 // TODO: the last token of each of the sequences don't need to be evaluated1131 task.required_tokens = task.common_prefix +1132 task.seq_tokens[0].size() - task.common_prefix +1133 task.seq_tokens[1].size() - task.common_prefix;1134 1135 task.n_base1 = common_tokenize(ctx, task.first + task.choices[0], true).size();1136 task.n_base2 = common_tokenize(ctx, task.first + task.choices[1], true).size();1137 }1138 1139 LOG_INF("%s : calculating winogrande score over selected tasks.\n", __func__);1140 1141 const int n_ctx = llama_n_ctx(ctx);1142 const int n_batch = params.n_batch;1143 1144 const int n_vocab = llama_vocab_n_tokens(vocab);1145 1146 const int max_tasks_per_batch = 128;1147 const int max_seq = std::min(2*max_tasks_per_batch, (int) llama_n_seq_max(ctx));1148 1149 llama_batch batch = llama_batch_init(n_ctx, 0, 2);1150 1151 std::vector<float> tok_logits(n_vocab);1152 // TODO: this could be made smaller; it's currently the worst-case size1153 std::vector<float> batch_logits(size_t(n_ctx)*n_vocab);1154 1155 std::vector<std::pair<size_t, llama_token>> eval_pairs;1156 std::vector<float> eval_results;1157 std::vector<std::thread> workers(std::thread::hardware_concurrency());1158 1159 int n_correct = 0;1160 int n_done = 0;1161 1162 for (size_t i0 = 0; i0 < data.size(); i0++) {1163 int n_cur = 0;1164 1165 size_t i1 = i0;1166 size_t i_logits = 0;1167 1168 common_batch_clear(batch);1169 1170 while (n_cur + (int) data[i1].required_tokens <= n_ctx) {1171 int n_logits = 0;1172 const int s0 = 2*(i1 - i0);1173 if (s0 + 2 > max_seq) {1174 break;1175 }1176 1177 for (size_t i = 0; i < data[i1].common_prefix; ++i) {1178 common_batch_add(batch, data[i1].seq_tokens[0][i], i, { s0 + 0, s0 + 1 }, false);1179 }1180 batch.logits[batch.n_tokens - 1] = true;1181 n_logits += 1;1182 1183 for (int s = 0; s < 2; ++s) {1184 // TODO: end before the last token, no need to predict past the end of the sequences1185 for (size_t i = data[i1].common_prefix; i < data[i1].seq_tokens[s].size(); ++i) {1186 common_batch_add(batch, data[i1].seq_tokens[s][i], i, { s0 + s }, true);1187 n_logits += 1;1188 }1189 }1190 1191 data[i1].i_logits = i_logits;1192 i_logits += n_logits;1193 1194 n_cur += data[i1].required_tokens;1195 if (++i1 == data.size()) {1196 break;1197 }1198 }1199 1200 if (i0 == i1) {