| 8138 | } |
| 8139 | |
| 8140 | void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) { |
| 8141 | GGML_ASSERT(candidates->size > 0); |
| 8142 | |
| 8143 | const int64_t t_start_sample_us = ggml_time_us(); |
| 8144 | |
| 8145 | // Sort the logits in descending order |
| 8146 | if (!candidates->sorted) { |
| 8147 | std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) { |
| 8148 | return a.logit > b.logit; |
| 8149 | }); |
| 8150 | candidates->sorted = true; |
| 8151 | } |
| 8152 | |
| 8153 | float max_l = candidates->data[0].logit; |
| 8154 | float cum_sum = 0.0f; |
| 8155 | for (size_t i = 0; i < candidates->size; ++i) { |
| 8156 | float p = expf(candidates->data[i].logit - max_l); |
| 8157 | candidates->data[i].p = p; |
| 8158 | cum_sum += p; |
| 8159 | } |
| 8160 | for (size_t i = 0; i < candidates->size; ++i) { |
| 8161 | candidates->data[i].p /= cum_sum; |
| 8162 | } |
| 8163 | |
| 8164 | if (ctx) { |
| 8165 | ctx->t_sample_us += ggml_time_us() - t_start_sample_us; |
| 8166 | } |
| 8167 | } |
| 8168 | |
| 8169 | void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) { |
| 8170 | const int64_t t_start_sample_us = ggml_time_us(); |