sampling.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #include "sampling.h"
  2. #include "common.h"
  3. #include <cmath>
  4. #include <unordered_map>
  5. // the ring buffer works similarly to std::deque, but with a fixed capacity
  6. // TODO: deduplicate with llama-impl.h
  7. template<typename T>
  8. struct ring_buffer {
  9. ring_buffer(size_t cap) : capacity(cap), data(cap) {}
  10. T & front() {
  11. if (sz == 0) {
  12. throw std::runtime_error("ring buffer is empty");
  13. }
  14. return data[first];
  15. }
  16. const T & front() const {
  17. if (sz == 0) {
  18. throw std::runtime_error("ring buffer is empty");
  19. }
  20. return data[first];
  21. }
  22. T & back() {
  23. if (sz == 0) {
  24. throw std::runtime_error("ring buffer is empty");
  25. }
  26. return data[pos];
  27. }
  28. const T & back() const {
  29. if (sz == 0) {
  30. throw std::runtime_error("ring buffer is empty");
  31. }
  32. return data[pos];
  33. }
  34. void push_back(const T & value) {
  35. if (sz == capacity) {
  36. // advance the start when buffer is full
  37. first = (first + 1) % capacity;
  38. } else {
  39. sz++;
  40. }
  41. data[pos] = value;
  42. pos = (pos + 1) % capacity;
  43. }
  44. T pop_front() {
  45. if (sz == 0) {
  46. throw std::runtime_error("ring buffer is empty");
  47. }
  48. T value = data[first];
  49. first = (first + 1) % capacity;
  50. sz--;
  51. return value;
  52. }
  53. const T & rat(size_t i) const {
  54. if (i >= sz) {
  55. throw std::runtime_error("ring buffer: index out of bounds");
  56. }
  57. return data[(first + sz - i - 1) % capacity];
  58. }
  59. std::vector<T> to_vector() const {
  60. std::vector<T> result;
  61. result.reserve(sz);
  62. for (size_t i = 0; i < sz; i++) {
  63. result.push_back(data[(first + i) % capacity]);
  64. }
  65. return result;
  66. }
  67. void clear() {
  68. // here only reset the status of the buffer
  69. sz = 0;
  70. first = 0;
  71. pos = 0;
  72. }
  73. bool empty() const {
  74. return sz == 0;
  75. }
  76. size_t size() const {
  77. return sz;
  78. }
  79. size_t capacity = 0;
  80. size_t sz = 0;
  81. size_t first = 0;
  82. size_t pos = 0;
  83. std::vector<T> data;
  84. };
  85. struct gpt_sampler {
  86. gpt_sampler_params params;
  87. struct llama_sampler * grmr;
  88. struct llama_sampler * chain;
  89. ring_buffer<llama_token> prev;
  90. std::vector<llama_token_data> cur;
  91. llama_token_data_array cur_p;
  92. void set_logits(struct llama_context * ctx, int idx) {
  93. const auto * logits = llama_get_logits_ith(ctx, idx);
  94. const int n_vocab = llama_n_vocab(llama_get_model(ctx));
  95. cur.resize(n_vocab);
  96. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  97. cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
  98. }
  99. cur_p = { cur.data(), cur.size(), -1, false };
  100. }
  101. };
  102. std::string gpt_sampler_params::print() const {
  103. char result[1024];
  104. snprintf(result, sizeof(result),
  105. "\trepeat_last_n = %d, repeat_penalty = %.3f, frequency_penalty = %.3f, presence_penalty = %.3f\n"
  106. "\ttop_k = %d, tfs_z = %.3f, top_p = %.3f, min_p = %.3f, typical_p = %.3f, temp = %.3f\n"
  107. "\tmirostat = %d, mirostat_lr = %.3f, mirostat_ent = %.3f",
  108. penalty_last_n, penalty_repeat, penalty_freq, penalty_present,
  109. top_k, tfs_z, top_p, min_p, typ_p, temp,
  110. mirostat, mirostat_eta, mirostat_tau);
  111. return std::string(result);
  112. }
  113. struct gpt_sampler * gpt_sampler_init(const struct llama_model * model, const struct gpt_sampler_params & params) {
  114. llama_sampler_chain_params lparams = llama_sampler_chain_default_params();
  115. lparams.no_perf = false; // TODO: control via params
  116. auto * result = new gpt_sampler {
  117. /* .params = */ params,
  118. /* .grmr = */ llama_sampler_init_grammar(model, params.grammar.c_str(), "root"),
  119. /* .chain = */ llama_sampler_chain_init(lparams),
  120. /* .prev = */ ring_buffer<llama_token>(std::max(32, params.n_prev)),
  121. /* .cur = */ {},
  122. /* .cur_p = */ {},
  123. };
  124. llama_sampler_chain_add(result->chain,
  125. llama_sampler_init_logit_bias(
  126. llama_n_vocab(model),
  127. params.logit_bias.size(),
  128. params.logit_bias.data()));
  129. llama_sampler_chain_add(result->chain,
  130. llama_sampler_init_penalties(
  131. llama_n_vocab (model),
  132. llama_token_eos(model),
  133. llama_token_nl (model),
  134. params.penalty_last_n,
  135. params.penalty_repeat,
  136. params.penalty_freq,
  137. params.penalty_present,
  138. params.penalize_nl,
  139. params.ignore_eos));
  140. if (params.temp > 0.0f) {
  141. if (params.mirostat == 0) {
  142. for (const auto & cnstr : params.samplers) {
  143. switch (cnstr) {
  144. case GPT_SAMPLER_TYPE_TOP_K:
  145. llama_sampler_chain_add(result->chain, llama_sampler_init_top_k (params.top_k));
  146. break;
  147. case GPT_SAMPLER_TYPE_TOP_P:
  148. llama_sampler_chain_add(result->chain, llama_sampler_init_top_p (params.top_p, params.min_keep));
  149. break;
  150. case GPT_SAMPLER_TYPE_MIN_P:
  151. llama_sampler_chain_add(result->chain, llama_sampler_init_min_p (params.min_p, params.min_keep));
  152. break;
  153. case GPT_SAMPLER_TYPE_TFS_Z:
  154. llama_sampler_chain_add(result->chain, llama_sampler_init_tail_free(params.tfs_z, params.min_keep));
  155. break;
  156. case GPT_SAMPLER_TYPE_TYPICAL_P:
  157. llama_sampler_chain_add(result->chain, llama_sampler_init_typical (params.typ_p, params.min_keep));
  158. break;
  159. case GPT_SAMPLER_TYPE_TEMPERATURE:
  160. llama_sampler_chain_add(result->chain, llama_sampler_init_temp_ext (params.temp, params.dynatemp_range, params.dynatemp_exponent));
  161. break;
  162. default:
  163. GGML_ASSERT(false && "unknown sampler type");
  164. }
  165. }
  166. llama_sampler_chain_add(result->chain, llama_sampler_init_softmax());
  167. llama_sampler_chain_add(result->chain, llama_sampler_init_dist(params.seed));
  168. } else if (params.mirostat == 1) {
  169. llama_sampler_chain_add(result->chain, llama_sampler_init_temp(params.temp));
  170. llama_sampler_chain_add(result->chain, llama_sampler_init_mirostat(llama_n_vocab(model), params.seed, params.mirostat_tau, params.mirostat_eta, 100));
  171. } else if (params.mirostat == 2) {
  172. llama_sampler_chain_add(result->chain, llama_sampler_init_temp(params.temp));
  173. llama_sampler_chain_add(result->chain, llama_sampler_init_mirostat_v2(params.seed, params.mirostat_tau, params.mirostat_eta));
  174. } else {
  175. GGML_ASSERT(false && "unknown mirostat version");
  176. }
  177. } else {
  178. llama_sampler_chain_add(result->chain, llama_sampler_init_softmax());
  179. llama_sampler_chain_add(result->chain, llama_sampler_init_greedy());
  180. }
  181. return result;
  182. }
  183. void gpt_sampler_free(struct gpt_sampler * gsmpl) {
  184. if (gsmpl) {
  185. llama_sampler_free(gsmpl->grmr);
  186. llama_sampler_free(gsmpl->chain);
  187. delete gsmpl;
  188. }
  189. }
  190. void gpt_sampler_accept(struct gpt_sampler * gsmpl, llama_token token, bool accept_grammar) {
  191. if (accept_grammar) {
  192. llama_sampler_accept(gsmpl->grmr, token);
  193. }
  194. llama_sampler_accept(gsmpl->chain, token);
  195. gsmpl->prev.push_back(token);
  196. }
  197. void gpt_sampler_reset(struct gpt_sampler * gsmpl) {
  198. llama_sampler_reset(gsmpl->grmr);
  199. llama_sampler_reset(gsmpl->chain);
  200. }
  201. struct gpt_sampler * gpt_sampler_clone(gpt_sampler * gsmpl) {
  202. return new gpt_sampler {
  203. /* .params = */ gsmpl->params,
  204. /* .grmr = */ llama_sampler_clone(gsmpl->grmr),
  205. /* .chain = */ llama_sampler_clone(gsmpl->chain),
  206. /* .prev = */ gsmpl->prev,
  207. /* .cur = */ gsmpl->cur,
  208. /* .cur_p = */ gsmpl->cur_p,
  209. };
  210. }
  211. void gpt_perf_print(const struct llama_context * ctx, const struct gpt_sampler * gsmpl) {
  212. // TODO: measure grammar performance
  213. if (gsmpl) {
  214. llama_perf_print(gsmpl->chain, LLAMA_PERF_TYPE_SAMPLER_CHAIN);
  215. }
  216. if (ctx) {
  217. llama_perf_print(ctx, LLAMA_PERF_TYPE_CONTEXT);
  218. }
  219. }
  220. llama_token gpt_sampler_sample(struct gpt_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
  221. gsmpl->set_logits(ctx, idx);
  222. auto & grmr = gsmpl->grmr;
  223. auto & chain = gsmpl->chain;
  224. auto & cur_p = gsmpl->cur_p; // initialized by set_logits
  225. if (grammar_first) {
  226. llama_sampler_apply(grmr, &cur_p);
  227. }
  228. llama_sampler_apply(chain, &cur_p);
  229. GGML_ASSERT(cur_p.selected != -1 && "no selected token during sampling - check your sampling configuration");
  230. const llama_token id = cur_p.data[cur_p.selected].id;
  231. if (grammar_first) {
  232. return id;
  233. }
  234. // check if it the sampled token fits the grammar
  235. {
  236. llama_token_data single_token_data = { id, 1.0f, 0.0f };
  237. llama_token_data_array single_token_data_array = { &single_token_data, 1, -1, false };
  238. llama_sampler_apply(grmr, &single_token_data_array);
  239. const bool is_valid = single_token_data_array.data[0].logit != -INFINITY;
  240. if (is_valid) {
  241. return id;
  242. }
  243. }
  244. // resampling:
  245. // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain
  246. gsmpl->set_logits(ctx, idx);
  247. llama_sampler_apply(grmr, &cur_p);
  248. llama_sampler_apply(chain, &cur_p);
  249. GGML_ASSERT(cur_p.selected != -1 && "no selected token during re-sampling - check your sampling configuration");
  250. return cur_p.data[cur_p.selected].id;
  251. }
  252. // helpers
  253. llama_token_data_array * gpt_sampler_get_candidates(struct gpt_sampler * gsmpl) {
  254. return &gsmpl->cur_p;
  255. }
  256. llama_token gpt_sampler_last(const struct gpt_sampler * gsmpl) {
  257. return gsmpl->prev.rat(0);
  258. }
  259. std::string gpt_sampler_print(const struct gpt_sampler * gsmpl) {
  260. std::string result = "\tlogits ";
  261. for (int i = 0; i < llama_sampler_chain_n(gsmpl->chain); i++) {
  262. const auto * smpl = llama_sampler_chain_get(gsmpl->chain, i);
  263. result += std::string("-> ") + llama_sampler_name(smpl) + " ";
  264. }
  265. return result;
  266. }
  267. std::string gpt_sampler_prev_str(gpt_sampler * gsmpl, llama_context * ctx_main, int n) {
  268. n = std::min(n, (int) gsmpl->prev.size());
  269. if (n <= 0) {
  270. return "";
  271. }
  272. std::string result;
  273. result.reserve(8*n); // 8 is the average length of a token [citation needed], TODO: compute this from the vocab
  274. for (int i = n - 1; i >= 0; i--) {
  275. const llama_token id = gsmpl->prev.rat(i);
  276. GGML_ASSERT(id != LLAMA_TOKEN_NULL && "null token in the sampling history - should not happen");
  277. result += llama_token_to_piece(ctx_main, id);
  278. }
  279. return result;
  280. }
  281. char gpt_sampler_type_to_chr(enum gpt_sampler_type cnstr) {
  282. switch (cnstr) {
  283. case GPT_SAMPLER_TYPE_TOP_K: return 'k';
  284. case GPT_SAMPLER_TYPE_TFS_Z: return 'f';
  285. case GPT_SAMPLER_TYPE_TYPICAL_P: return 'y';
  286. case GPT_SAMPLER_TYPE_TOP_P: return 'p';
  287. case GPT_SAMPLER_TYPE_MIN_P: return 'm';
  288. case GPT_SAMPLER_TYPE_TEMPERATURE: return 't';
  289. default : return '?';
  290. }
  291. }
  292. std::string gpt_sampler_type_to_str(enum gpt_sampler_type cnstr) {
  293. switch (cnstr) {
  294. case GPT_SAMPLER_TYPE_TOP_K: return "top_k";
  295. case GPT_SAMPLER_TYPE_TFS_Z: return "tfs_z";
  296. case GPT_SAMPLER_TYPE_TYPICAL_P: return "typ_p";
  297. case GPT_SAMPLER_TYPE_TOP_P: return "top_p";
  298. case GPT_SAMPLER_TYPE_MIN_P: return "min_p";
  299. case GPT_SAMPLER_TYPE_TEMPERATURE: return "temperature";
  300. default : return "";
  301. }
  302. }
  303. std::vector<gpt_sampler_type> gpt_sampler_types_from_names(const std::vector<std::string> & names, bool allow_alt_names) {
  304. std::unordered_map<std::string, gpt_sampler_type> sampler_canonical_name_map {
  305. { "top_k", GPT_SAMPLER_TYPE_TOP_K },
  306. { "top_p", GPT_SAMPLER_TYPE_TOP_P },
  307. { "typ_p", GPT_SAMPLER_TYPE_TYPICAL_P },
  308. { "min_p", GPT_SAMPLER_TYPE_MIN_P },
  309. { "tfs_z", GPT_SAMPLER_TYPE_TFS_Z },
  310. { "temperature", GPT_SAMPLER_TYPE_TEMPERATURE },
  311. };
  312. // since samplers names are written multiple ways
  313. // make it ready for both system names and input names
  314. std::unordered_map<std::string, gpt_sampler_type> sampler_alt_name_map {
  315. { "top-k", GPT_SAMPLER_TYPE_TOP_K },
  316. { "top-p", GPT_SAMPLER_TYPE_TOP_P },
  317. { "nucleus", GPT_SAMPLER_TYPE_TOP_P },
  318. { "typical-p", GPT_SAMPLER_TYPE_TYPICAL_P },
  319. { "typical", GPT_SAMPLER_TYPE_TYPICAL_P },
  320. { "typ-p", GPT_SAMPLER_TYPE_TYPICAL_P },
  321. { "typ", GPT_SAMPLER_TYPE_TYPICAL_P },
  322. { "min-p", GPT_SAMPLER_TYPE_MIN_P },
  323. { "tfs-z", GPT_SAMPLER_TYPE_TFS_Z },
  324. { "tfs", GPT_SAMPLER_TYPE_TFS_Z },
  325. { "temp", GPT_SAMPLER_TYPE_TEMPERATURE },
  326. };
  327. std::vector<gpt_sampler_type> samplers;
  328. samplers.reserve(names.size());
  329. for (const auto & name : names) {
  330. auto sampler = sampler_canonical_name_map.find(name);
  331. if (sampler != sampler_canonical_name_map.end()) {
  332. samplers.push_back(sampler->second);
  333. } else {
  334. if (allow_alt_names) {
  335. sampler = sampler_alt_name_map.find(name);
  336. if (sampler != sampler_alt_name_map.end()) {
  337. samplers.push_back(sampler->second);
  338. }
  339. }
  340. }
  341. }
  342. return samplers;
  343. }
  344. std::vector<gpt_sampler_type> gpt_sampler_types_from_chars(const std::string & chars) {
  345. std::unordered_map<char, gpt_sampler_type> sampler_name_map = {
  346. { gpt_sampler_type_to_chr(GPT_SAMPLER_TYPE_TOP_K), GPT_SAMPLER_TYPE_TOP_K },
  347. { gpt_sampler_type_to_chr(GPT_SAMPLER_TYPE_TFS_Z), GPT_SAMPLER_TYPE_TFS_Z },
  348. { gpt_sampler_type_to_chr(GPT_SAMPLER_TYPE_TYPICAL_P), GPT_SAMPLER_TYPE_TYPICAL_P },
  349. { gpt_sampler_type_to_chr(GPT_SAMPLER_TYPE_TOP_P), GPT_SAMPLER_TYPE_TOP_P },
  350. { gpt_sampler_type_to_chr(GPT_SAMPLER_TYPE_MIN_P), GPT_SAMPLER_TYPE_MIN_P },
  351. { gpt_sampler_type_to_chr(GPT_SAMPLER_TYPE_TEMPERATURE), GPT_SAMPLER_TYPE_TEMPERATURE }
  352. };
  353. std::vector<gpt_sampler_type> samplers;
  354. samplers.reserve(chars.size());
  355. for (const auto & c : chars) {
  356. const auto sampler = sampler_name_map.find(c);
  357. if (sampler != sampler_name_map.end()) {
  358. samplers.push_back(sampler->second);
  359. }
  360. }
  361. return samplers;
  362. }