| 292 | } |
| 293 | |
| 294 | static results_perplexity perplexity_v2(llama_context * ctx, const common_params & params) { |
| 295 | // Download: https://huggingface.co/datasets/ggml-org/ci/resolve/main/wikitext-2-raw-v1.zip |
| 296 | // Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw` |
| 297 | // Output: `perplexity: 13.5106 [114/114]` |
| 298 | // BOS tokens will be added for each chunk before eval |
| 299 | |
| 300 | const llama_model * model = llama_get_model(ctx); |
| 301 | const llama_vocab * vocab = llama_model_get_vocab(model); |
| 302 | |
| 303 | const bool add_bos = llama_vocab_get_add_bos(vocab); |
| 304 | GGML_ASSERT(!llama_vocab_get_add_eos(vocab)); |
| 305 | |
| 306 | LOG_INF("%s: tokenizing the input ..\n", __func__); |
| 307 | |
| 308 | std::vector<llama_token> tokens = common_tokenize(ctx, params.prompt, true); |
| 309 | |
| 310 | const int n_ctx = llama_n_ctx(ctx); |
| 311 | |
| 312 | if (int(tokens.size()) < 2*n_ctx) { |
| 313 | LOG_ERR("%s: you need at least %d tokens to evaluate perplexity with a context of %d\n",__func__,2*n_ctx, |
| 314 | n_ctx); |
| 315 | LOG_ERR("%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size()); |
| 316 | return {std::move(tokens), 0., {}, {}}; |
| 317 | } |
| 318 | |
| 319 | std::vector<float> logit_history; |
| 320 | std::vector<float> prob_history; |
| 321 | |
| 322 | logit_history.resize(tokens.size()); |
| 323 | prob_history.resize(tokens.size()); |
| 324 | |
| 325 | if (params.ppl_stride <= 0) { |
| 326 | LOG_ERR("%s: stride is %d but must be greater than zero!\n",__func__,params.ppl_stride); |
| 327 | return {tokens, -1, logit_history, prob_history}; |
| 328 | } |
| 329 | |
| 330 | const int calc_chunk = n_ctx; |
| 331 | |
| 332 | LOG_INF("%s: have %zu tokens. Calculation chunk = %d\n", __func__, tokens.size(), calc_chunk); |
| 333 | |
| 334 | if (int(tokens.size()) <= calc_chunk) { |
| 335 | LOG_ERR("%s: there are only %zu tokens, this is not enough for a context size of %d and stride %d\n",__func__, |
| 336 | tokens.size(), n_ctx, params.ppl_stride); |
| 337 | return {tokens, -1, logit_history, prob_history}; |
| 338 | } |
| 339 | |
| 340 | const int n_chunk_max = (tokens.size() - calc_chunk + params.ppl_stride - 1) / params.ppl_stride; |
| 341 | |
| 342 | const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max); |
| 343 | const int n_batch = params.n_batch; |
| 344 | |
| 345 | const int n_vocab = llama_vocab_n_tokens(vocab); |
| 346 | |
| 347 | int count = 0; |
| 348 | double nll = 0.0; |
| 349 | |
| 350 | LOG_INF("%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch); |
| 351 |
no test coverage detected