| 8192 | } |
| 8193 | |
| 8194 | void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) { |
| 8195 | if (p >= 1.0f) { |
| 8196 | return; |
| 8197 | } |
| 8198 | |
| 8199 | llama_sample_softmax(ctx, candidates); |
| 8200 | |
| 8201 | const int64_t t_start_sample_us = ggml_time_us(); |
| 8202 | |
| 8203 | // Compute the cumulative probabilities |
| 8204 | float cum_sum = 0.0f; |
| 8205 | size_t last_idx = candidates->size; |
| 8206 | |
| 8207 | for (size_t i = 0; i < candidates->size; ++i) { |
| 8208 | cum_sum += candidates->data[i].p; |
| 8209 | |
| 8210 | // Check if the running sum is at least p or if we have kept at least min_keep tokens |
| 8211 | // we set the last index to i+1 to indicate that the current iterate should be included in the set |
| 8212 | if (cum_sum >= p && i + 1 >= min_keep) { |
| 8213 | last_idx = i + 1; |
| 8214 | break; |
| 8215 | } |
| 8216 | } |
| 8217 | |
| 8218 | // Resize the output vector to keep only the top-p tokens |
| 8219 | candidates->size = last_idx; |
| 8220 | |
| 8221 | if (ctx) { |
| 8222 | ctx->t_sample_us += ggml_time_us() - t_start_sample_us; |
| 8223 | } |
| 8224 | } |
| 8225 | |
| 8226 | void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) { |
| 8227 | if (p <= 0.0f || !candidates->size) { |