|
| 1 | +// Copyright (C) 2023-2024 Intel Corporation |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +#include <algorithm> |
| 5 | +#include <cmath> |
| 6 | +#include <iostream> |
| 7 | +#include <numeric> |
| 8 | +#include <random> |
| 9 | +#include <regex> |
| 10 | +#include <vector> |
| 11 | + |
| 12 | +#include "generation_config_helper.hpp" |
| 13 | +#include "openvino/genai/llm_pipeline.hpp" |
| 14 | +#include "utils.hpp" |
| 15 | + |
| 16 | + |
| 17 | +namespace { |
| 18 | + |
| 19 | +struct TokenIdScore { |
| 20 | + int64_t id; |
| 21 | + float score; |
| 22 | + |
| 23 | + bool operator<(const TokenIdScore& other) const { |
| 24 | + return score < other.score; |
| 25 | + } |
| 26 | + |
| 27 | + bool operator>(const TokenIdScore& other) const { |
| 28 | + return score > other.score; |
| 29 | + } |
| 30 | +}; |
| 31 | + |
| 32 | +void apply_softmax_inplace(std::vector<TokenIdScore>& tokens) { |
| 33 | + float max_score = std::max_element(tokens.begin(), tokens.end())->score; |
| 34 | + float sum = 0.f; |
| 35 | + |
| 36 | + for (auto& token : tokens) { |
| 37 | + float s = std::exp(token.score - max_score); |
| 38 | + token.score = s; |
| 39 | + sum += s; |
| 40 | + } |
| 41 | + |
| 42 | + float inv_sum = 1.f / sum; |
| 43 | + |
| 44 | + for (auto& token : tokens) { |
| 45 | + token.score *= inv_sum; |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +TokenIdScore* sample_top_p(TokenIdScore* first, TokenIdScore* last, float top_p) { |
| 50 | + // sort score |
| 51 | + std::sort(first, last, std::greater<TokenIdScore>()); |
| 52 | + |
| 53 | + int tokens_size = last - first; |
| 54 | + std::vector<TokenIdScore> token_scores(tokens_size); |
| 55 | + for (size_t i = 0; i < tokens_size; i++) { |
| 56 | + token_scores[i] = first[i]; |
| 57 | + } |
| 58 | + |
| 59 | + // calculate softmax |
| 60 | + apply_softmax_inplace(token_scores); |
| 61 | + |
| 62 | + float prefix_sum = 0.0f; |
| 63 | + |
| 64 | + // top_p |
| 65 | + for (size_t i = 0; i < tokens_size; i++) { |
| 66 | + prefix_sum += token_scores[i].score; |
| 67 | + if (prefix_sum >= top_p) { |
| 68 | + return first + (i + 1); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return last; |
| 73 | +} |
| 74 | + |
| 75 | +void apply_repetition_penalty(float* first, float* last, const std::vector<int64_t>& input_ids, float penalty) { |
| 76 | + const float inv_penalty = 1.f / penalty; |
| 77 | + const int vocab_size = last - first; |
| 78 | + std::vector<bool> occurrence(vocab_size, false); |
| 79 | + for (const int64_t id : input_ids) { |
| 80 | + if (!occurrence[id]) { |
| 81 | + first[id] *= (first[id] > 0) ? inv_penalty : penalty; |
| 82 | + } |
| 83 | + occurrence[id] = true; |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +void apply_inv_temperature(float* first, float* last, float inv_temperature) { |
| 88 | + for (float* it = first; it != last; it++) { |
| 89 | + *it *= inv_temperature; |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +struct RandomSampling { |
| 94 | + const size_t top_k; |
| 95 | + const float top_p; |
| 96 | + const float inv_temperature; |
| 97 | + const float repetition_penalty; |
| 98 | + |
| 99 | + std::mt19937 gen{std::random_device{}()}; |
| 100 | + |
| 101 | + RandomSampling(ov::genai::GenerationConfig generation_config) |
| 102 | + : top_k{generation_config.top_k}, |
| 103 | + top_p{generation_config.top_p}, |
| 104 | + inv_temperature{1.f / generation_config.temperature}, |
| 105 | + repetition_penalty{generation_config.repetition_penalty} { |
| 106 | + // parameters validation |
| 107 | + OPENVINO_ASSERT(generation_config.top_k > 0, |
| 108 | + "top_k must be a strictly positive, but got ", |
| 109 | + generation_config.top_p); |
| 110 | + OPENVINO_ASSERT(generation_config.top_p > 0 || generation_config.top_p < 1.0f, |
| 111 | + "top_p must be a positive float > 0 and < 1, but got ", |
| 112 | + generation_config.top_p); |
| 113 | + OPENVINO_ASSERT(generation_config.temperature > 0, |
| 114 | + "Temperature must be a strictly positive float, but got ", |
| 115 | + generation_config.temperature); |
| 116 | + OPENVINO_ASSERT(generation_config.repetition_penalty > 0, |
| 117 | + "Repetition penalty must be a strictly positive float, but got ", |
| 118 | + generation_config.repetition_penalty); |
| 119 | + } |
| 120 | + |
| 121 | + TokenIdScore get_out_token(float* logits, size_t vocab_size, const std::vector<int64_t>& tokens) { |
| 122 | + // logits pre-process |
| 123 | + if (repetition_penalty != 1.0f) { |
| 124 | + apply_repetition_penalty(logits, logits + vocab_size, tokens, repetition_penalty); |
| 125 | + } |
| 126 | + |
| 127 | + if (inv_temperature != 1.0f) { |
| 128 | + apply_inv_temperature(logits, logits + vocab_size, inv_temperature); |
| 129 | + } |
| 130 | + |
| 131 | + std::vector<TokenIdScore> token_scores(vocab_size); |
| 132 | + for (size_t i = 0; i < vocab_size; i++) { |
| 133 | + token_scores[i] = TokenIdScore{int64_t(i), logits[i]}; |
| 134 | + } |
| 135 | + |
| 136 | + // top_k sampling |
| 137 | + if (0 < top_k && top_k < token_scores.size()) { |
| 138 | + std::nth_element(token_scores.data(), |
| 139 | + token_scores.data() + top_k, |
| 140 | + token_scores.data() + token_scores.size(), |
| 141 | + std::greater<TokenIdScore>()); |
| 142 | + token_scores.resize(top_k); |
| 143 | + } |
| 144 | + |
| 145 | + // top_p sampling |
| 146 | + if (0.f < top_p && top_p < 1.0f) { |
| 147 | + auto pos = sample_top_p(token_scores.data(), token_scores.data() + token_scores.size(), top_p); |
| 148 | + token_scores.resize(pos - token_scores.data()); |
| 149 | + } |
| 150 | + |
| 151 | + // sample next token |
| 152 | + apply_softmax_inplace(token_scores); |
| 153 | + for (size_t i = 0; i < token_scores.size(); i++) { |
| 154 | + logits[i] = token_scores[i].score; |
| 155 | + } |
| 156 | + |
| 157 | + std::discrete_distribution<> dist(logits, logits + token_scores.size()); |
| 158 | + return token_scores[dist(gen)]; |
| 159 | + } |
| 160 | +}; |
| 161 | +} // namespace |
| 162 | + |
| 163 | +namespace ov { |
| 164 | +namespace genai { |
| 165 | + |
| 166 | +ov::genai::EncodedResults multinominal_decoding(ov::InferRequest& m_model_runner, |
| 167 | + ov::Tensor input_ids, |
| 168 | + ov::Tensor attention_mask, |
| 169 | + ov::genai::GenerationConfig config, |
| 170 | + std::shared_ptr<ov::genai::StreamerBase> streamer) { |
| 171 | + ov::Shape prompts_shape = input_ids.get_shape(); |
| 172 | + size_t batch_size = prompts_shape[0]; |
| 173 | + |
| 174 | + OPENVINO_ASSERT(batch_size == 1, "Only batch size = 1 supported for multinomial decoding"); |
| 175 | + |
| 176 | + size_t prompt_len = prompts_shape[1]; |
| 177 | + |
| 178 | + ov::genai::EncodedResults results; |
| 179 | + results.scores.resize(batch_size, 0); |
| 180 | + results.tokens.resize(batch_size); |
| 181 | + |
| 182 | + // Initialize inputs |
| 183 | + m_model_runner.set_tensor("input_ids", input_ids); |
| 184 | + m_model_runner.set_tensor("attention_mask", attention_mask); |
| 185 | + |
| 186 | + ov::Tensor position_ids = m_model_runner.get_tensor("position_ids"); |
| 187 | + position_ids.set_shape(input_ids.get_shape()); |
| 188 | + std::iota(position_ids.data<int64_t>(), position_ids.data<int64_t>() + position_ids.get_size(), 0); |
| 189 | + |
| 190 | + // Input values are persistent between inference calls. |
| 191 | + // That allows to set values, which aren't going to change, only once |
| 192 | + m_model_runner.get_tensor("beam_idx").set_shape({batch_size}); |
| 193 | + m_model_runner.get_tensor("beam_idx").data<int32_t>()[0] = 0; |
| 194 | + |
| 195 | + m_model_runner.infer(); |
| 196 | + |
| 197 | + auto logits_tensor = m_model_runner.get_tensor("logits"); |
| 198 | + |
| 199 | + int64_t sequence_offset = logits_tensor.get_shape().at(1) - 1; |
| 200 | + size_t vocab_size = logits_tensor.get_shape().back(); |
| 201 | + |
| 202 | + float* logits = logits_tensor.data<float>() + sequence_offset * vocab_size; |
| 203 | + |
| 204 | + const int64_t* input_ids_data = input_ids.data<const int64_t>(); |
| 205 | + |
| 206 | + std::vector<int64_t> tokens{input_ids_data, input_ids_data + input_ids.get_size()}; |
| 207 | + |
| 208 | + RandomSampling sampling{config}; |
| 209 | + |
| 210 | + TokenIdScore out_token = sampling.get_out_token(logits, vocab_size, tokens); |
| 211 | + |
| 212 | + tokens.push_back(out_token.id); |
| 213 | + results.tokens[0].push_back(out_token.id); |
| 214 | + results.scores[0] += out_token.score; |
| 215 | + |
| 216 | + if (streamer) { |
| 217 | + streamer->put(out_token.id); |
| 218 | + } |
| 219 | + |
| 220 | + if (!config.ignore_eos && out_token.id == config.eos_token_id) { |
| 221 | + return results; |
| 222 | + } |
| 223 | + |
| 224 | + m_model_runner.get_tensor("input_ids").set_shape({batch_size, 1}); |
| 225 | + m_model_runner.get_tensor("position_ids").set_shape({batch_size, 1}); |
| 226 | + |
| 227 | + size_t max_new_tokens = config.get_max_new_tokens(prompt_len); |
| 228 | + |
| 229 | + for (size_t i = 0; i < max_new_tokens - 1; i++) { |
| 230 | + ov::genai::utils::update_position_ids(m_model_runner.get_tensor("position_ids"), |
| 231 | + m_model_runner.get_tensor("attention_mask")); |
| 232 | + m_model_runner.set_tensor("attention_mask", |
| 233 | + ov::genai::utils::extend_attention(m_model_runner.get_tensor("attention_mask"))); |
| 234 | + |
| 235 | + m_model_runner.get_tensor("input_ids").data<int64_t>()[0] = out_token.id; |
| 236 | + |
| 237 | + m_model_runner.infer(); |
| 238 | + |
| 239 | + logits = m_model_runner.get_tensor("logits").data<float>(); |
| 240 | + out_token = sampling.get_out_token(logits, vocab_size, tokens); |
| 241 | + |
| 242 | + tokens.push_back(out_token.id); |
| 243 | + results.tokens[0].push_back(out_token.id); |
| 244 | + results.scores[0] += out_token.score; |
| 245 | + |
| 246 | + if (streamer) { |
| 247 | + streamer->put(out_token.id); |
| 248 | + } |
| 249 | + |
| 250 | + if (!config.ignore_eos && out_token.id == config.eos_token_id) { |
| 251 | + break; |
| 252 | + } |
| 253 | + } |
| 254 | + |
| 255 | + if (streamer) { |
| 256 | + streamer->end(); |
| 257 | + } |
| 258 | + |
| 259 | + return results; |
| 260 | +} |
| 261 | +} // namespace genai |
| 262 | +} // namespace ov |
0 commit comments