1
0

sampling.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. #include "sampling.h"
  2. struct llama_sampling_context * llama_sampling_init(const struct llama_sampling_params & params) {
  3. struct llama_sampling_context * result = new llama_sampling_context();
  4. result->params = params;
  5. result->grammar = nullptr;
  6. // if there is a grammar, parse it
  7. if (!params.grammar.empty()) {
  8. result->parsed_grammar = grammar_parser::parse(params.grammar.c_str());
  9. // will be empty (default) if there are parse errors
  10. if (result->parsed_grammar.rules.empty()) {
  11. fprintf(stderr, "%s: failed to parse grammar\n", __func__);
  12. return nullptr;
  13. }
  14. std::vector<const llama_grammar_element *> grammar_rules(result->parsed_grammar.c_rules());
  15. result->grammar = llama_grammar_init(
  16. grammar_rules.data(),
  17. grammar_rules.size(), result->parsed_grammar.symbol_ids.at("root"));
  18. }
  19. result->prev.resize(params.n_prev);
  20. return result;
  21. }
  22. void llama_sampling_free(struct llama_sampling_context * ctx) {
  23. if (ctx->grammar != NULL) {
  24. llama_grammar_free(ctx->grammar);
  25. }
  26. delete ctx;
  27. }
  28. void llama_sampling_reset(llama_sampling_context * ctx) {
  29. if (ctx->grammar != NULL) {
  30. llama_grammar_free(ctx->grammar);
  31. ctx->grammar = NULL;
  32. }
  33. if (!ctx->parsed_grammar.rules.empty()) {
  34. std::vector<const llama_grammar_element *> grammar_rules(ctx->parsed_grammar.c_rules());
  35. ctx->grammar = llama_grammar_init(
  36. grammar_rules.data(),
  37. grammar_rules.size(), ctx->parsed_grammar.symbol_ids.at("root"));
  38. }
  39. std::fill(ctx->prev.begin(), ctx->prev.end(), 0);
  40. ctx->cur.clear();
  41. }
  42. void llama_sampling_cp(llama_sampling_context * src, llama_sampling_context * dst) {
  43. if (dst->grammar) {
  44. llama_grammar_free(dst->grammar);
  45. dst->grammar = nullptr;
  46. }
  47. if (src->grammar) {
  48. dst->grammar = llama_grammar_copy(src->grammar);
  49. }
  50. dst->prev = src->prev;
  51. }
  52. llama_token llama_sampling_last(llama_sampling_context * ctx) {
  53. return ctx->prev.back();
  54. }
  55. std::string llama_sampling_prev_str(llama_sampling_context * ctx_sampling, llama_context * ctx_main, int n) {
  56. const int size = ctx_sampling->prev.size();
  57. n = std::min(n, size);
  58. std::string result;
  59. for (int i = size - n; i < size; i++) {
  60. result += llama_token_to_piece(ctx_main, ctx_sampling->prev[i]);
  61. }
  62. return result;
  63. }
  64. std::string llama_sampling_print(const llama_sampling_params & params) {
  65. char result[1024];
  66. snprintf(result, sizeof(result),
  67. "\trepeat_last_n = %d, repeat_penalty = %.3f, frequency_penalty = %.3f, presence_penalty = %.3f\n"
  68. "\ttop_k = %d, tfs_z = %.3f, top_p = %.3f, min_p = %.3f, typical_p = %.3f, temp = %.3f\n"
  69. "\tmirostat = %d, mirostat_lr = %.3f, mirostat_ent = %.3f",
  70. params.penalty_last_n, params.penalty_repeat, params.penalty_freq, params.penalty_present,
  71. params.top_k, params.tfs_z, params.top_p, params.min_p, params.typical_p, params.temp,
  72. params.mirostat, params.mirostat_eta, params.mirostat_tau);
  73. return std::string(result);
  74. }
  75. std::string llama_sampling_order_print(const llama_sampling_params & params) {
  76. std::string result = "CFG -> Penalties ";
  77. if (params.mirostat == 0) {
  78. for (auto s : params.samplers_sequence) {
  79. switch (s) {
  80. case 'k': result += "-> top_k "; break;
  81. case 'f': result += "-> tfs_z "; break;
  82. case 'y': result += "-> typical_p "; break;
  83. case 'p': result += "-> top_p "; break;
  84. case 'm': result += "-> min_p "; break;
  85. case 't': result += "-> temp "; break;
  86. default : break;
  87. }
  88. }
  89. } else result += "-> mirostat ";
  90. return result;
  91. }
  92. // no reasons to expose this function in header
  93. void sampler_queue(
  94. struct llama_context * ctx_main,
  95. const llama_sampling_params & params,
  96. llama_token_data_array & cur_p,
  97. size_t & min_keep) {
  98. const int n_vocab = llama_n_vocab(llama_get_model(ctx_main));
  99. const float temp = params.temp;
  100. const int32_t top_k = params.top_k <= 0 ? n_vocab : params.top_k;
  101. const float top_p = params.top_p;
  102. const float min_p = params.min_p;
  103. const float tfs_z = params.tfs_z;
  104. const float typical_p = params.typical_p;
  105. const std::string & samplers_sequence = params.samplers_sequence;
  106. for (auto s : samplers_sequence) {
  107. switch (s){
  108. case 'k': llama_sample_top_k (ctx_main, &cur_p, top_k, min_keep); break;
  109. case 'f': llama_sample_tail_free(ctx_main, &cur_p, tfs_z, min_keep); break;
  110. case 'y': llama_sample_typical (ctx_main, &cur_p, typical_p, min_keep); break;
  111. case 'p': llama_sample_top_p (ctx_main, &cur_p, top_p, min_keep); break;
  112. case 'm': llama_sample_min_p (ctx_main, &cur_p, min_p, min_keep); break;
  113. case 't': llama_sample_temp (ctx_main, &cur_p, temp); break;
  114. default : break;
  115. }
  116. }
  117. }
  118. llama_token llama_sampling_sample(
  119. struct llama_sampling_context * ctx_sampling,
  120. struct llama_context * ctx_main,
  121. struct llama_context * ctx_cfg,
  122. const int idx) {
  123. const llama_sampling_params & params = ctx_sampling->params;
  124. const int n_vocab = llama_n_vocab(llama_get_model(ctx_main));
  125. const float temp = params.temp;
  126. const int32_t penalty_last_n = params.penalty_last_n < 0 ? params.n_prev : params.penalty_last_n;
  127. const float penalty_repeat = params.penalty_repeat;
  128. const float penalty_freq = params.penalty_freq;
  129. const float penalty_present = params.penalty_present;
  130. const int mirostat = params.mirostat;
  131. const float mirostat_tau = params.mirostat_tau;
  132. const float mirostat_eta = params.mirostat_eta;
  133. const bool penalize_nl = params.penalize_nl;
  134. auto & prev = ctx_sampling->prev;
  135. auto & cur = ctx_sampling->cur;
  136. llama_token id = 0;
  137. float * logits = llama_get_logits_ith(ctx_main, idx);
  138. // apply params.logit_bias map
  139. for (auto it = params.logit_bias.begin(); it != params.logit_bias.end(); it++) {
  140. logits[it->first] += it->second;
  141. }
  142. cur.clear();
  143. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  144. cur.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  145. }
  146. llama_token_data_array cur_p = { cur.data(), cur.size(), false };
  147. if (ctx_cfg) {
  148. llama_sample_classifier_free_guidance(ctx_main, &cur_p, ctx_cfg, params.cfg_scale);
  149. }
  150. // apply penalties
  151. if (!prev.empty()) {
  152. const float nl_logit = logits[llama_token_nl(llama_get_model(ctx_main))];
  153. llama_sample_repetition_penalties(ctx_main, &cur_p,
  154. prev.data() + prev.size() - penalty_last_n,
  155. penalty_last_n, penalty_repeat, penalty_freq, penalty_present);
  156. if (!penalize_nl) {
  157. for (size_t idx = 0; idx < cur_p.size; idx++) {
  158. if (cur_p.data[idx].id == llama_token_nl(llama_get_model(ctx_main))) {
  159. cur_p.data[idx].logit = nl_logit;
  160. break;
  161. }
  162. }
  163. }
  164. }
  165. if (ctx_sampling->grammar != NULL) {
  166. llama_sample_grammar(ctx_main, &cur_p, ctx_sampling->grammar);
  167. }
  168. if (temp < 0.0) {
  169. // greedy sampling, with probs
  170. llama_sample_softmax(ctx_main, &cur_p);
  171. id = cur_p.data[0].id;
  172. } else if (temp == 0.0) {
  173. // greedy sampling, no probs
  174. id = llama_sample_token_greedy(ctx_main, &cur_p);
  175. } else {
  176. if (mirostat == 1) {
  177. const int mirostat_m = 100;
  178. llama_sample_temp(ctx_main, &cur_p, temp);
  179. id = llama_sample_token_mirostat(ctx_main, &cur_p, mirostat_tau, mirostat_eta, mirostat_m, &ctx_sampling->mirostat_mu);
  180. } else if (mirostat == 2) {
  181. llama_sample_temp(ctx_main, &cur_p, temp);
  182. id = llama_sample_token_mirostat_v2(ctx_main, &cur_p, mirostat_tau, mirostat_eta, &ctx_sampling->mirostat_mu);
  183. } else {
  184. // temperature sampling
  185. size_t min_keep = std::max(1, params.n_probs);
  186. sampler_queue(ctx_main, params, cur_p, min_keep);
  187. id = llama_sample_token(ctx_main, &cur_p);
  188. //{
  189. // const int n_top = 10;
  190. // LOG("top %d candidates:\n", n_top);
  191. // for (int i = 0; i < n_top; i++) {
  192. // const llama_token id = cur_p.data[i].id;
  193. // (void)id; // To avoid a warning that id is unused when logging is disabled.
  194. // LOG(" - %5d: '%12s' (%.3f)\n", id, llama_token_to_piece(ctx_main, id).c_str(), cur_p.data[i].p);
  195. // }
  196. //}
  197. LOG("sampled token: %5d: '%s'\n", id, llama_token_to_piece(ctx_main, id).c_str());
  198. }
  199. }
  200. return id;
  201. }
  202. void llama_sampling_accept(
  203. struct llama_sampling_context * ctx_sampling,
  204. struct llama_context * ctx_main,
  205. llama_token id,
  206. bool apply_grammar) {
  207. ctx_sampling->prev.erase(ctx_sampling->prev.begin());
  208. ctx_sampling->prev.push_back(id);
  209. if (ctx_sampling->grammar != NULL && apply_grammar) {
  210. llama_grammar_accept_token(ctx_main, ctx_sampling->grammar, id);
  211. }
  212. }