| 36 | }; |
| 37 | |
| 38 | static std::vector<float> softmax(const std::vector<float>& logits) { |
| 39 | std::vector<float> probs(logits.size()); |
| 40 | float max_logit = logits[0]; |
| 41 | for (float v : logits) { |
| 42 | max_logit = std::max(max_logit, v); |
| 43 | } |
| 44 | double sum_exp = 0.0; |
| 45 | for (size_t i = 0; i < logits.size(); i++) { |
| 46 | // Subtract the maximum logit value from the current logit value for numerical stability |
| 47 | const float logit = logits[i] - max_logit; |
| 48 | const float exp_logit = expf(logit); |
| 49 | sum_exp += exp_logit; |
| 50 | probs[i] = exp_logit; |
| 51 | } |
| 52 | for (size_t i = 0; i < probs.size(); i++) { |
| 53 | probs[i] /= sum_exp; |
| 54 | } |
| 55 | return probs; |
| 56 | } |
| 57 | |
| 58 | static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) { |
| 59 | float max_logit = logits[0]; |
no test coverage detected