| 8524 | } |
| 8525 | |
| 8526 | llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) { |
| 8527 | GGML_ASSERT(ctx); |
| 8528 | |
| 8529 | auto N = float(llama_n_vocab(llama_get_model(ctx))); |
| 8530 | int64_t t_start_sample_us; |
| 8531 | t_start_sample_us = ggml_time_us(); |
| 8532 | |
| 8533 | llama_sample_softmax(nullptr, candidates); |
| 8534 | |
| 8535 | // Estimate s_hat using the most probable m tokens |
| 8536 | float s_hat = 0.0; |
| 8537 | float sum_ti_bi = 0.0; |
| 8538 | float sum_ti_sq = 0.0; |
| 8539 | for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) { |
| 8540 | float t_i = logf(float(i + 2) / float(i + 1)); |
| 8541 | float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p); |
| 8542 | sum_ti_bi += t_i * b_i; |
| 8543 | sum_ti_sq += t_i * t_i; |
| 8544 | } |
| 8545 | s_hat = sum_ti_bi / sum_ti_sq; |
| 8546 | |
| 8547 | // Compute k from the estimated s_hat and target surprise value |
| 8548 | float epsilon_hat = s_hat - 1; |
| 8549 | float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat); |
| 8550 | |
| 8551 | // Sample the next word X using top-k sampling |
| 8552 | llama_sample_top_k(nullptr, candidates, int(k), 1); |
| 8553 | if (ctx) { |
| 8554 | ctx->t_sample_us += ggml_time_us() - t_start_sample_us; |
| 8555 | } |
| 8556 | llama_token X = llama_sample_token(ctx, candidates); |
| 8557 | t_start_sample_us = ggml_time_us(); |
| 8558 | |
| 8559 | // Compute error as the difference between observed surprise and target surprise value |
| 8560 | size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) { |
| 8561 | return candidate.id == X; |
| 8562 | })); |
| 8563 | float observed_surprise = -log2f(candidates->data[X_idx].p); |
| 8564 | float e = observed_surprise - tau; |
| 8565 | |
| 8566 | // Update mu using the learning rate and error |
| 8567 | *mu = *mu - eta * e; |
| 8568 | |
| 8569 | if (ctx) { |
| 8570 | ctx->t_sample_us += ggml_time_us() - t_start_sample_us; |
| 8571 | } |
| 8572 | return X; |
| 8573 | } |
| 8574 | |
| 8575 | llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) { |
| 8576 | int64_t t_start_sample_us; |
no test coverage detected