sampling.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /**
  2. * llama.cpp - commit 6eeaeba126ff701f3e8f79f246805b7023709972 - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #define LLAMA_API_INTERNAL
  27. #include "sampling.h"
  28. #include <random>
  29. struct llama_sampling_context * llama_sampling_init(const struct llama_sampling_params & params) {
  30. struct llama_sampling_context * result = new llama_sampling_context();
  31. result->params = params;
  32. result->grammar = nullptr;
  33. // if there is a grammar, parse it
  34. if (!params.grammar.empty()) {
  35. result->parsed_grammar = grammar_parser::parse(params.grammar.c_str());
  36. // will be empty (default) if there are parse errors
  37. if (result->parsed_grammar.rules.empty()) {
  38. fprintf(stderr, "%s: failed to parse grammar\n", __func__);
  39. delete result;
  40. return nullptr;
  41. }
  42. // Ensure that there is a "root" node.
  43. if (result->parsed_grammar.symbol_ids.find("root") == result->parsed_grammar.symbol_ids.end()) {
  44. fprintf(stderr, "%s: grammar does not contain a 'root' symbol\n", __func__);
  45. delete result;
  46. return nullptr;
  47. }
  48. std::vector<const llama_grammar_element *> grammar_rules(result->parsed_grammar.c_rules());
  49. struct llama_grammar * grammar = llama_grammar_init(
  50. grammar_rules.data(),
  51. grammar_rules.size(), result->parsed_grammar.symbol_ids.at("root"));
  52. if (grammar == nullptr) {
  53. throw std::runtime_error("Failed to initialize llama_grammar");
  54. }
  55. result->grammar = grammar;
  56. }
  57. result->prev.resize(params.n_prev);
  58. result->n_valid = 0;
  59. llama_sampling_set_rng_seed(result, params.seed);
  60. return result;
  61. }
  62. void llama_sampling_free(struct llama_sampling_context * ctx) {
  63. if (ctx->grammar != NULL) {
  64. llama_grammar_free(ctx->grammar);
  65. }
  66. delete ctx;
  67. }
  68. void llama_sampling_reset(llama_sampling_context * ctx) {
  69. if (ctx->grammar != NULL) {
  70. llama_grammar_free(ctx->grammar);
  71. ctx->grammar = NULL;
  72. }
  73. if (!ctx->parsed_grammar.rules.empty()) {
  74. std::vector<const llama_grammar_element *> grammar_rules(ctx->parsed_grammar.c_rules());
  75. struct llama_grammar * grammar = llama_grammar_init(
  76. grammar_rules.data(),
  77. grammar_rules.size(), ctx->parsed_grammar.symbol_ids.at("root"));
  78. if (grammar == nullptr) {
  79. throw std::runtime_error("Failed to initialize llama_grammar");
  80. }
  81. ctx->grammar = grammar;
  82. }
  83. std::fill(ctx->prev.begin(), ctx->prev.end(), 0);
  84. ctx->cur.clear();
  85. ctx->n_valid = 0;
  86. }
  87. void llama_sampling_set_rng_seed(struct llama_sampling_context * ctx, uint32_t seed) {
  88. if (seed == LLAMA_DEFAULT_SEED) {
  89. seed = std::random_device{}();
  90. }
  91. ctx->rng.seed(seed);
  92. }
  93. void llama_sampling_cp(llama_sampling_context * src, llama_sampling_context * dst) {
  94. if (dst->grammar) {
  95. llama_grammar_free(dst->grammar);
  96. dst->grammar = nullptr;
  97. }
  98. if (src->grammar) {
  99. dst->grammar = llama_grammar_copy(src->grammar);
  100. }
  101. dst->prev = src->prev;
  102. }
  103. llama_token llama_sampling_last(llama_sampling_context * ctx) {
  104. return ctx->prev.back();
  105. }
  106. std::string llama_sampling_prev_str(llama_sampling_context * ctx_sampling, llama_context * ctx_main, int n) {
  107. const int size = ctx_sampling->prev.size();
  108. n = std::min(n, size);
  109. std::string result;
  110. for (int i = size - n; i < size; i++) {
  111. result += llama_token_to_piece(ctx_main, ctx_sampling->prev[i]);
  112. }
  113. return result;
  114. }
  115. std::string llama_sampling_print(const llama_sampling_params & params) {
  116. char result[1024];
  117. snprintf(result, sizeof(result),
  118. "\trepeat_last_n = %d, repeat_penalty = %.3f, frequency_penalty = %.3f, presence_penalty = %.3f\n"
  119. "\ttop_k = %d, tfs_z = %.3f, top_p = %.3f, min_p = %.3f, typical_p = %.3f, temp = %.3f\n"
  120. "\tmirostat = %d, mirostat_lr = %.3f, mirostat_ent = %.3f",
  121. params.penalty_last_n, params.penalty_repeat, params.penalty_freq, params.penalty_present,
  122. params.top_k, params.tfs_z, params.top_p, params.min_p, params.typical_p, params.temp,
  123. params.mirostat, params.mirostat_eta, params.mirostat_tau);
  124. return std::string(result);
  125. }
  126. std::string llama_sampling_order_print(const llama_sampling_params & params) {
  127. std::string result = "CFG -> Penalties ";
  128. if (params.mirostat == 0) {
  129. for (auto sampler_type : params.samplers_sequence) {
  130. const auto sampler_type_name = llama_sampling_type_to_str(sampler_type);
  131. if (!sampler_type_name.empty()) {
  132. result += "-> " + sampler_type_name + " ";
  133. }
  134. }
  135. } else {
  136. result += "-> mirostat ";
  137. }
  138. return result;
  139. }
  140. std::string llama_sampling_type_to_str(llama_sampler_type sampler_type) {
  141. switch (sampler_type) {
  142. case llama_sampler_type::TOP_K: return "top_k";
  143. case llama_sampler_type::TFS_Z: return "tfs_z";
  144. case llama_sampler_type::TYPICAL_P: return "typical_p";
  145. case llama_sampler_type::TOP_P: return "top_p";
  146. case llama_sampler_type::MIN_P: return "min_p";
  147. case llama_sampler_type::TEMPERATURE: return "temperature";
  148. default : return "";
  149. }
  150. }
  151. std::vector<llama_sampler_type> llama_sampling_types_from_names(const std::vector<std::string> & names, bool allow_alt_names) {
  152. std::unordered_map<std::string, llama_sampler_type> sampler_canonical_name_map {
  153. {"top_k", llama_sampler_type::TOP_K},
  154. {"top_p", llama_sampler_type::TOP_P},
  155. {"typical_p", llama_sampler_type::TYPICAL_P},
  156. {"min_p", llama_sampler_type::MIN_P},
  157. {"tfs_z", llama_sampler_type::TFS_Z},
  158. {"temperature", llama_sampler_type::TEMPERATURE}
  159. };
  160. // since samplers names are written multiple ways
  161. // make it ready for both system names and input names
  162. std::unordered_map<std::string, llama_sampler_type> sampler_alt_name_map {
  163. {"top-k", llama_sampler_type::TOP_K},
  164. {"top-p", llama_sampler_type::TOP_P},
  165. {"nucleus", llama_sampler_type::TOP_P},
  166. {"typical-p", llama_sampler_type::TYPICAL_P},
  167. {"typical", llama_sampler_type::TYPICAL_P},
  168. {"min-p", llama_sampler_type::MIN_P},
  169. {"tfs-z", llama_sampler_type::TFS_Z},
  170. {"tfs", llama_sampler_type::TFS_Z},
  171. {"temp", llama_sampler_type::TEMPERATURE}
  172. };
  173. std::vector<llama_sampler_type> sampler_types;
  174. sampler_types.reserve(names.size());
  175. for (const auto & name : names)
  176. {
  177. auto sampler_item = sampler_canonical_name_map.find(name);
  178. if (sampler_item != sampler_canonical_name_map.end())
  179. {
  180. sampler_types.push_back(sampler_item->second);
  181. }
  182. else
  183. {
  184. if (allow_alt_names)
  185. {
  186. sampler_item = sampler_alt_name_map.find(name);
  187. if (sampler_item != sampler_alt_name_map.end())
  188. {
  189. sampler_types.push_back(sampler_item->second);
  190. }
  191. }
  192. }
  193. }
  194. return sampler_types;
  195. }
  196. std::vector<llama_sampler_type> llama_sampling_types_from_chars(const std::string & names_string) {
  197. std::unordered_map<char, llama_sampler_type> sampler_name_map {
  198. {'k', llama_sampler_type::TOP_K},
  199. {'p', llama_sampler_type::TOP_P},
  200. {'y', llama_sampler_type::TYPICAL_P},
  201. {'m', llama_sampler_type::MIN_P},
  202. {'f', llama_sampler_type::TFS_Z},
  203. {'t', llama_sampler_type::TEMPERATURE}
  204. };
  205. std::vector<llama_sampler_type> sampler_types;
  206. sampler_types.reserve(names_string.size());
  207. for (const auto & c : names_string) {
  208. const auto sampler_item = sampler_name_map.find(c);
  209. if (sampler_item != sampler_name_map.end()) {
  210. sampler_types.push_back(sampler_item->second);
  211. }
  212. }
  213. return sampler_types;
  214. }
  215. // no reasons to expose this function in header
  216. static void sampler_queue(
  217. struct llama_context * ctx_main,
  218. const llama_sampling_params & params,
  219. llama_token_data_array & cur_p,
  220. size_t min_keep) {
  221. const float temp = params.temp;
  222. const float dynatemp_range = params.dynatemp_range;
  223. const float dynatemp_exponent = params.dynatemp_exponent;
  224. const int32_t top_k = params.top_k;
  225. const float top_p = params.top_p;
  226. const float min_p = params.min_p;
  227. const float tfs_z = params.tfs_z;
  228. const float typical_p = params.typical_p;
  229. const std::vector<llama_sampler_type> & samplers_sequence = params.samplers_sequence;
  230. for (auto sampler_type : samplers_sequence) {
  231. switch (sampler_type) {
  232. case llama_sampler_type::TOP_K : llama_sample_top_k (ctx_main, &cur_p, top_k, min_keep); break;
  233. case llama_sampler_type::TFS_Z : llama_sample_tail_free(ctx_main, &cur_p, tfs_z, min_keep); break;
  234. case llama_sampler_type::TYPICAL_P: llama_sample_typical (ctx_main, &cur_p, typical_p, min_keep); break;
  235. case llama_sampler_type::TOP_P : llama_sample_top_p (ctx_main, &cur_p, top_p, min_keep); break;
  236. case llama_sampler_type::MIN_P : llama_sample_min_p (ctx_main, &cur_p, min_p, min_keep); break;
  237. case llama_sampler_type::TEMPERATURE:
  238. if (dynatemp_range > 0) {
  239. float dynatemp_min = std::max(0.0f, temp - dynatemp_range);
  240. float dynatemp_max = std::max(0.0f, temp + dynatemp_range);
  241. llama_sample_entropy(ctx_main, &cur_p, dynatemp_min, dynatemp_max, dynatemp_exponent);
  242. } else {
  243. llama_sample_temp(ctx_main, &cur_p, temp);
  244. }
  245. break;
  246. default : break;
  247. }
  248. }
  249. }
  250. static llama_token llama_sampling_sample_impl(
  251. struct llama_sampling_context * ctx_sampling,
  252. struct llama_context * ctx_main,
  253. struct llama_context * ctx_cfg,
  254. const int idx,
  255. bool is_resampling) {
  256. const llama_sampling_params & params = ctx_sampling->params;
  257. const float temp = params.temp;
  258. const int mirostat = params.mirostat;
  259. const float mirostat_tau = params.mirostat_tau;
  260. const float mirostat_eta = params.mirostat_eta;
  261. std::vector<float> original_logits;
  262. auto cur_p = llama_sampling_prepare(ctx_sampling, ctx_main, ctx_cfg, idx, /* apply_grammar= */ is_resampling, &original_logits);
  263. if (ctx_sampling->grammar != NULL && !is_resampling) {
  264. GGML_ASSERT(!original_logits.empty());
  265. }
  266. llama_token id = 0;
  267. if (temp < 0.0) {
  268. // greedy sampling, with probs
  269. llama_sample_softmax(ctx_main, &cur_p);
  270. id = cur_p.data[0].id;
  271. } else if (temp == 0.0) {
  272. // greedy sampling, no probs
  273. id = llama_sample_token_greedy(ctx_main, &cur_p);
  274. } else {
  275. if (mirostat == 1) {
  276. const int mirostat_m = 100;
  277. llama_sample_temp(ctx_main, &cur_p, temp);
  278. id = llama_sample_token_mirostat(ctx_main, &cur_p, mirostat_tau, mirostat_eta, mirostat_m, &ctx_sampling->mirostat_mu);
  279. } else if (mirostat == 2) {
  280. llama_sample_temp(ctx_main, &cur_p, temp);
  281. id = llama_sample_token_mirostat_v2(ctx_main, &cur_p, mirostat_tau, mirostat_eta, &ctx_sampling->mirostat_mu);
  282. } else {
  283. // temperature sampling
  284. size_t min_keep = std::max(1, params.min_keep);
  285. sampler_queue(ctx_main, params, cur_p, min_keep);
  286. id = llama_sample_token_with_rng(ctx_main, &cur_p, ctx_sampling->rng);
  287. //{
  288. // const int n_top = 10;
  289. // LOG("top %d candidates:\n", n_top);
  290. // for (int i = 0; i < n_top; i++) {
  291. // const llama_token id = cur_p.data[i].id;
  292. // (void)id; // To avoid a warning that id is unused when logging is disabled.
  293. // LOG(" - %5d: '%12s' (%.3f)\n", id, llama_token_to_piece(ctx_main, id).c_str(), cur_p.data[i].p);
  294. // }
  295. //}
  296. //LOG("sampled token: %5d: '%s'\n", id, llama_token_to_piece(ctx_main, id).c_str());
  297. }
  298. }
  299. if (ctx_sampling->grammar != NULL && !is_resampling) {
  300. // Get a pointer to the logits
  301. float * logits = llama_get_logits_ith(ctx_main, idx);
  302. // Create an array with a single token data element for the sampled id
  303. llama_token_data single_token_data = {id, logits[id], 0.0f};
  304. llama_token_data_array single_token_data_array = { &single_token_data, 1, false };
  305. // Apply grammar constraints to the single token
  306. llama_grammar_sample(ctx_sampling->grammar, ctx_main, &single_token_data_array);
  307. // Check if the token is valid according to the grammar by seeing if its logit has been set to -INFINITY
  308. bool is_valid = single_token_data_array.data[0].logit != -INFINITY;
  309. // If the token is not valid according to the grammar, perform resampling
  310. if (!is_valid) {
  311. LOG("Resampling because token %d: '%s' does not meet grammar rules\n", id, llama_token_to_piece(ctx_main, id).c_str());
  312. // Restore logits from the copy
  313. std::copy(original_logits.begin(), original_logits.end(), logits);
  314. return llama_sampling_sample_impl(ctx_sampling, ctx_main, ctx_cfg, idx, /* is_resampling= */ true);
  315. }
  316. }
  317. ctx_sampling->n_valid = temp == 0.0f ? 0 : cur_p.size;
  318. return id;
  319. }
  320. static llama_token_data_array llama_sampling_prepare_impl(
  321. struct llama_sampling_context * ctx_sampling,
  322. struct llama_context * ctx_main,
  323. struct llama_context * ctx_cfg,
  324. const int idx,
  325. bool apply_grammar,
  326. std::vector<float> * original_logits) {
  327. const llama_sampling_params & params = ctx_sampling->params;
  328. const int n_vocab = llama_n_vocab(llama_get_model(ctx_main));
  329. const int32_t penalty_last_n = params.penalty_last_n < 0 ? params.n_prev : params.penalty_last_n;
  330. const float penalty_repeat = params.penalty_repeat;
  331. const float penalty_freq = params.penalty_freq;
  332. const float penalty_present = params.penalty_present;
  333. const bool penalize_nl = params.penalize_nl;
  334. auto & prev = ctx_sampling->prev;
  335. auto & cur = ctx_sampling->cur;
  336. // Get a pointer to the logits
  337. float * logits = llama_get_logits_ith(ctx_main, idx);
  338. if (ctx_sampling->grammar != NULL && !apply_grammar) {
  339. GGML_ASSERT(original_logits != NULL);
  340. // Only make a copy of the original logits if we are not applying grammar checks, not sure if I actually have to do this.
  341. *original_logits = {logits, logits + n_vocab};
  342. }
  343. // apply params.logit_bias map
  344. for (auto it = params.logit_bias.begin(); it != params.logit_bias.end(); it++) {
  345. logits[it->first] += it->second;
  346. }
  347. if (ctx_cfg) {
  348. float * logits_guidance = llama_get_logits_ith(ctx_cfg, idx);
  349. llama_sample_apply_guidance(ctx_main, logits, logits_guidance, params.cfg_scale);
  350. }
  351. cur.resize(n_vocab);
  352. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  353. cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
  354. }
  355. llama_token_data_array cur_p = { cur.data(), cur.size(), false };
  356. // apply penalties
  357. const auto& penalty_tokens = params.use_penalty_prompt_tokens ? params.penalty_prompt_tokens : prev;
  358. const int penalty_tokens_used_size = std::min((int)penalty_tokens.size(), penalty_last_n);
  359. if (penalty_tokens_used_size) {
  360. const float nl_logit = logits[llama_token_nl(llama_get_model(ctx_main))];
  361. llama_sample_repetition_penalties(ctx_main, &cur_p,
  362. penalty_tokens.data() + penalty_tokens.size() - penalty_tokens_used_size,
  363. penalty_tokens_used_size, penalty_repeat, penalty_freq, penalty_present);
  364. if (!penalize_nl) {
  365. for (size_t idx = 0; idx < cur_p.size; idx++) {
  366. if (cur_p.data[idx].id == llama_token_nl(llama_get_model(ctx_main))) {
  367. cur_p.data[idx].logit = nl_logit;
  368. break;
  369. }
  370. }
  371. }
  372. }
  373. // apply grammar checks before sampling logic
  374. if (apply_grammar && ctx_sampling->grammar != NULL) {
  375. llama_grammar_sample(ctx_sampling->grammar, ctx_main, &cur_p);
  376. }
  377. return cur_p;
  378. }
  379. llama_token llama_sampling_sample(
  380. struct llama_sampling_context * ctx_sampling,
  381. struct llama_context * ctx_main,
  382. struct llama_context * ctx_cfg,
  383. const int idx) {
  384. // Call the implementation function with is_resampling set to false by default
  385. return llama_sampling_sample_impl(ctx_sampling, ctx_main, ctx_cfg, idx, /* is_resampling= */ false);
  386. }
  387. llama_token_data_array llama_sampling_prepare(
  388. struct llama_sampling_context * ctx_sampling,
  389. struct llama_context * ctx_main,
  390. struct llama_context * ctx_cfg,
  391. const int idx,
  392. bool apply_grammar,
  393. std::vector<float> * original_logits) {
  394. return llama_sampling_prepare_impl(ctx_sampling,ctx_main, ctx_cfg, idx, apply_grammar, original_logits);
  395. }
  396. void llama_sampling_accept(
  397. struct llama_sampling_context * ctx_sampling,
  398. struct llama_context * ctx_main,
  399. llama_token id,
  400. bool apply_grammar) {
  401. ctx_sampling->prev.erase(ctx_sampling->prev.begin());
  402. ctx_sampling->prev.push_back(id);
  403. if (ctx_sampling->grammar != NULL && apply_grammar) {
  404. llama_grammar_accept_token(ctx_sampling->grammar, ctx_main, id);
  405. }
  406. }