| 77 | } |
| 78 | |
| 79 | static std::vector<float> softmax(const std::vector<float>& logits) { |
| 80 | std::vector<float> probs(logits.size()); |
| 81 | float max_logit = logits[0]; |
| 82 | for (float v : logits) { |
| 83 | max_logit = std::max(max_logit, v); |
| 84 | } |
| 85 | double sum_exp = 0.0; |
| 86 | for (size_t i = 0; i < logits.size(); i++) { |
| 87 | // Subtract the maximum logit value from the current logit value for numerical stability |
| 88 | const float logit = logits[i] - max_logit; |
| 89 | const float exp_logit = expf(logit); |
| 90 | sum_exp += exp_logit; |
| 91 | probs[i] = exp_logit; |
| 92 | } |
| 93 | for (size_t i = 0; i < probs.size(); i++) { |
| 94 | probs[i] /= sum_exp; |
| 95 | } |
| 96 | return probs; |
| 97 | } |
| 98 | |
| 99 | static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) { |
| 100 | float max_logit = logits[0]; |
no test coverage detected