| 1229 | } |
| 1230 | |
| 1231 | static void llama_sampler_mirostat_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) { |
| 1232 | auto * ctx = (llama_sampler_mirostat *) smpl->ctx; |
| 1233 | |
| 1234 | llama_sampler_softmax_impl(cur_p); |
| 1235 | |
| 1236 | // Estimate s_hat using the most probable m tokens |
| 1237 | float s_hat = 0.0; |
| 1238 | float sum_ti_bi = 0.0; |
| 1239 | float sum_ti_sq = 0.0; |
| 1240 | for (size_t i = 0; i < size_t(ctx->m - 1) && i < cur_p->size - 1; ++i) { |
| 1241 | float t_i = logf(float(i + 2) / float(i + 1)); |
| 1242 | float b_i = logf(cur_p->data[i].p / cur_p->data[i + 1].p); |
| 1243 | sum_ti_bi += t_i * b_i; |
| 1244 | sum_ti_sq += t_i * t_i; |
| 1245 | } |
| 1246 | s_hat = sum_ti_bi / sum_ti_sq; |
| 1247 | |
| 1248 | // Compute k from the estimated s_hat and target surprise value |
| 1249 | float epsilon_hat = s_hat - 1; |
| 1250 | float k = powf((epsilon_hat * powf(2, ctx->mu)) / (1 - powf(ctx->n_vocab, -epsilon_hat)), 1 / s_hat); |
| 1251 | |
| 1252 | llama_sampler_top_k_impl(cur_p, std::max(int(k), 1)); |
| 1253 | llama_sampler_softmax_impl(cur_p); |
| 1254 | |
| 1255 | const int idx = llama_sample_dist(cur_p, ctx->rng); |
| 1256 | |
| 1257 | cur_p->selected = idx; |
| 1258 | |
| 1259 | float observed_surprise = -log2f(cur_p->data[idx].p); |
| 1260 | float e = observed_surprise - ctx->tau; |
| 1261 | |
| 1262 | // Update mu using the learning rate and error |
| 1263 | ctx->mu = ctx->mu - ctx->eta * e; |
| 1264 | } |
| 1265 | |
| 1266 | static struct llama_sampler * llama_sampler_mirostat_clone(const struct llama_sampler * smpl) { |
| 1267 | const auto * ctx = (const llama_sampler_mirostat *) smpl->ctx; |
nothing calls this directly
no test coverage detected