sampling.cpp 17 KB

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