| 1012 | } |
| 1013 | |
| 1014 | static void llama_sampler_temp_ext_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) { |
| 1015 | const auto * ctx = (llama_sampler_temp_ext *) smpl->ctx; |
| 1016 | if (ctx->delta > 0) { |
| 1017 | const float min_temp = std::max(0.0f, ctx->temp - ctx->delta); |
| 1018 | const float max_temp = ctx->temp + ctx->delta; |
| 1019 | |
| 1020 | float exponent_val = ctx->exponent; |
| 1021 | |
| 1022 | // no need to do anything if there is only one (or zero) candidates |
| 1023 | if (cur_p->size <= 1) { |
| 1024 | return; |
| 1025 | } |
| 1026 | |
| 1027 | // Calculate maximum possible entropy |
| 1028 | float max_entropy = -logf(1.0f / cur_p->size); |
| 1029 | |
| 1030 | llama_sampler_softmax_impl(cur_p); |
| 1031 | |
| 1032 | // Calculate entropy of the softmax probabilities |
| 1033 | float entropy = 0.0f; |
| 1034 | for (size_t i = 0; i < cur_p->size; ++i) { |
| 1035 | float prob = cur_p->data[i].p; |
| 1036 | if (prob > 0.0f) { // Ensure no log(0) |
| 1037 | entropy -= prob * logf(prob); |
| 1038 | } |
| 1039 | } |
| 1040 | |
| 1041 | // Normalize the entropy (max_entropy cannot be 0 here because we checked cur_p->size != 1 above) |
| 1042 | float normalized_entropy = entropy / max_entropy; |
| 1043 | |
| 1044 | // Map the normalized entropy to the desired temperature range using the power function |
| 1045 | float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val); |
| 1046 | |
| 1047 | #ifdef DEBUG |
| 1048 | LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp); |
| 1049 | LLAMA_LOG_INFO("Entropy: %f\n", entropy); |
| 1050 | LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy); |
| 1051 | LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy); |
| 1052 | LLAMA_LOG_INFO("Exponent: %f\n", exponent_val); |
| 1053 | LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp); |
| 1054 | #endif |
| 1055 | |
| 1056 | // Apply the dynamically calculated temperature scaling |
| 1057 | llama_sampler_temp_impl(cur_p, dyn_temp); |
| 1058 | |
| 1059 | // Re-compute softmax probabilities after scaling logits with dynamic temperature |
| 1060 | const double max_l_double = cur_p->data[0].logit; |
| 1061 | |
| 1062 | double cum_sum_double = 0.0; |
| 1063 | for (size_t i = 0; i < cur_p->size; ++i) { |
| 1064 | double p = exp(cur_p->data[i].logit - max_l_double); |
| 1065 | cur_p->data[i].p = p; // Store the scaled probability |
| 1066 | cum_sum_double += p; |
| 1067 | } |
| 1068 | |
| 1069 | for (size_t i = 0; i < cur_p->size; ++i) { |
| 1070 | cur_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities |
| 1071 | } |
nothing calls this directly
no test coverage detected