sampling.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /**
  2. * llama.cpp - commit ba1cb19cdd0d92e012e0f6e009e0620f854b6afd - 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 common_sampler {
  111. common_params_sampling 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 common_params_sampling::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. "\tdry_multiplier = %.3f, dry_base = %.3f, dry_allowed_length = %d, dry_penalty_last_n = %d\n"
  132. "\ttop_k = %d, top_p = %.3f, min_p = %.3f, xtc_probability = %.3f, xtc_threshold = %.3f, typical_p = %.3f, temp = %.3f\n"
  133. "\tmirostat = %d, mirostat_lr = %.3f, mirostat_ent = %.3f",
  134. penalty_last_n, penalty_repeat, penalty_freq, penalty_present,
  135. dry_multiplier, dry_base, dry_allowed_length, dry_penalty_last_n,
  136. top_k, top_p, min_p, xtc_probability, xtc_threshold, typ_p, temp,
  137. mirostat, mirostat_eta, mirostat_tau);
  138. return std::string(result);
  139. }
  140. struct common_sampler * common_sampler_init(const struct llama_model * model, const struct common_params_sampling & params) {
  141. llama_sampler_chain_params lparams = llama_sampler_chain_default_params();
  142. lparams.no_perf = params.no_perf;
  143. auto * result = new common_sampler {
  144. /* .params = */ params,
  145. /* .grmr = */ llama_sampler_init_grammar(model, params.grammar.c_str(), "root"),
  146. /* .chain = */ llama_sampler_chain_init(lparams),
  147. /* .prev = */ ring_buffer<llama_token>(std::max(32, params.n_prev)),
  148. /* .cur = */ {},
  149. /* .cur_p = */ {},
  150. };
  151. llama_sampler_chain_add(result->chain,
  152. llama_sampler_init_logit_bias(
  153. llama_n_vocab(model),
  154. params.logit_bias.size(),
  155. params.logit_bias.data()));
  156. llama_sampler_chain_add(result->chain,
  157. llama_sampler_init_penalties(
  158. llama_n_vocab (model),
  159. llama_token_eos(model),
  160. llama_token_nl (model),
  161. params.penalty_last_n,
  162. params.penalty_repeat,
  163. params.penalty_freq,
  164. params.penalty_present,
  165. params.penalize_nl,
  166. params.ignore_eos));
  167. if (params.mirostat == 0) {
  168. for (const auto & cnstr : params.samplers) {
  169. switch (cnstr) {
  170. case COMMON_SAMPLER_TYPE_DRY:
  171. {
  172. std::vector<const char*> c_breakers;
  173. c_breakers.reserve(params.dry_sequence_breakers.size());
  174. for (const auto& str : params.dry_sequence_breakers) {
  175. c_breakers.push_back(str.c_str());
  176. }
  177. llama_sampler_chain_add(result->chain, llama_sampler_init_dry (model, params.dry_multiplier, params.dry_base, params.dry_allowed_length, params.dry_penalty_last_n, c_breakers.data(), c_breakers.size()));
  178. }
  179. break;
  180. case COMMON_SAMPLER_TYPE_TOP_K:
  181. llama_sampler_chain_add(result->chain, llama_sampler_init_top_k (params.top_k));
  182. break;
  183. case COMMON_SAMPLER_TYPE_TOP_P:
  184. llama_sampler_chain_add(result->chain, llama_sampler_init_top_p (params.top_p, params.min_keep));
  185. break;
  186. case COMMON_SAMPLER_TYPE_MIN_P:
  187. llama_sampler_chain_add(result->chain, llama_sampler_init_min_p (params.min_p, params.min_keep));
  188. break;
  189. case COMMON_SAMPLER_TYPE_XTC:
  190. llama_sampler_chain_add(result->chain, llama_sampler_init_xtc (params.xtc_probability, params.xtc_threshold, params.min_keep, params.seed));
  191. break;
  192. case COMMON_SAMPLER_TYPE_TYPICAL_P:
  193. llama_sampler_chain_add(result->chain, llama_sampler_init_typical (params.typ_p, params.min_keep));
  194. break;
  195. case COMMON_SAMPLER_TYPE_TEMPERATURE:
  196. llama_sampler_chain_add(result->chain, llama_sampler_init_temp_ext (params.temp, params.dynatemp_range, params.dynatemp_exponent));
  197. break;
  198. case COMMON_SAMPLER_TYPE_INFILL:
  199. llama_sampler_chain_add(result->chain, llama_sampler_init_infill (model));
  200. break;
  201. default:
  202. GGML_ASSERT(false && "unknown sampler type");
  203. }
  204. }
  205. llama_sampler_chain_add(result->chain, llama_sampler_init_dist(params.seed));
  206. } else if (params.mirostat == 1) {
  207. llama_sampler_chain_add(result->chain, llama_sampler_init_temp(params.temp));
  208. llama_sampler_chain_add(result->chain, llama_sampler_init_mirostat(llama_n_vocab(model), params.seed, params.mirostat_tau, params.mirostat_eta, 100));
  209. } else if (params.mirostat == 2) {
  210. llama_sampler_chain_add(result->chain, llama_sampler_init_temp(params.temp));
  211. llama_sampler_chain_add(result->chain, llama_sampler_init_mirostat_v2(params.seed, params.mirostat_tau, params.mirostat_eta));
  212. } else {
  213. GGML_ASSERT(false && "unknown mirostat version");
  214. }
  215. return result;
  216. }
  217. void common_sampler_free(struct common_sampler * gsmpl) {
  218. if (gsmpl) {
  219. llama_sampler_free(gsmpl->grmr);
  220. llama_sampler_free(gsmpl->chain);
  221. delete gsmpl;
  222. }
  223. }
  224. void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool accept_grammar) {
  225. if (accept_grammar) {
  226. llama_sampler_accept(gsmpl->grmr, token);
  227. }
  228. llama_sampler_accept(gsmpl->chain, token);
  229. gsmpl->prev.push_back(token);
  230. }
  231. void common_sampler_reset(struct common_sampler * gsmpl) {
  232. llama_sampler_reset(gsmpl->grmr);
  233. llama_sampler_reset(gsmpl->chain);
  234. }
  235. struct common_sampler * common_sampler_clone(common_sampler * gsmpl) {
  236. return new common_sampler {
  237. /* .params = */ gsmpl->params,
  238. /* .grmr = */ llama_sampler_clone(gsmpl->grmr),
  239. /* .chain = */ llama_sampler_clone(gsmpl->chain),
  240. /* .prev = */ gsmpl->prev,
  241. /* .cur = */ gsmpl->cur,
  242. /* .cur_p = */ gsmpl->cur_p,
  243. };
  244. }
  245. void common_perf_print(const struct llama_context * ctx, const struct common_sampler * gsmpl) {
  246. // TODO: measure grammar performance
  247. if (gsmpl) {
  248. llama_perf_sampler_print(gsmpl->chain);
  249. }
  250. if (ctx) {
  251. llama_perf_context_print(ctx);
  252. }
  253. }
  254. llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
  255. gsmpl->set_logits(ctx, idx);
  256. auto & grmr = gsmpl->grmr;
  257. auto & chain = gsmpl->chain;
  258. auto & cur_p = gsmpl->cur_p; // initialized by set_logits
  259. if (grammar_first) {
  260. llama_sampler_apply(grmr, &cur_p);
  261. }
  262. llama_sampler_apply(chain, &cur_p);
  263. GGML_ASSERT(cur_p.selected != -1 && "no selected token during sampling - check your sampling configuration");
  264. const llama_token id = cur_p.data[cur_p.selected].id;
  265. if (grammar_first) {
  266. return id;
  267. }
  268. // check if it the sampled token fits the grammar
  269. {
  270. llama_token_data single_token_data = { id, 1.0f, 0.0f };
  271. llama_token_data_array single_token_data_array = { &single_token_data, 1, -1, false };
  272. llama_sampler_apply(grmr, &single_token_data_array);
  273. const bool is_valid = single_token_data_array.data[0].logit != -INFINITY;
  274. if (is_valid) {
  275. return id;
  276. }
  277. }
  278. // resampling:
  279. // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain
  280. gsmpl->set_logits(ctx, idx);
  281. llama_sampler_apply(grmr, &cur_p);
  282. llama_sampler_apply(chain, &cur_p);
  283. GGML_ASSERT(cur_p.selected != -1 && "no selected token during re-sampling - check your sampling configuration");
  284. return cur_p.data[cur_p.selected].id;
  285. }
  286. std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector<int> & idxs, const llama_tokens & draft, bool grammar_first) {
  287. GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1");
  288. std::vector<llama_token> result;
  289. result.reserve(idxs.size());
  290. size_t i = 0;
  291. for (; i < draft.size(); i++) {
  292. const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
  293. common_sampler_accept(gsmpl, id, true);
  294. result.push_back(id);
  295. if (draft[i] != id) {
  296. break;
  297. }
  298. }
  299. if (i == draft.size()) {
  300. const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
  301. common_sampler_accept(gsmpl, id, true);
  302. result.push_back(id);
  303. }
  304. return result;
  305. }
  306. std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const llama_tokens & draft, bool grammar_first) {
  307. std::vector<int> idxs(draft.size() + 1);
  308. for (size_t i = 0; i < idxs.size(); ++i) {
  309. idxs[i] = i;
  310. }
  311. return common_sampler_sample_and_accept_n(gsmpl, ctx, idxs, draft, grammar_first);
  312. }
  313. uint32_t common_sampler_get_seed(const struct common_sampler * gsmpl) {
  314. return llama_sampler_get_seed(gsmpl->chain);
  315. }
  316. // helpers
  317. llama_token_data_array * common_sampler_get_candidates(struct common_sampler * gsmpl) {
  318. return &gsmpl->cur_p;
  319. }
  320. llama_token common_sampler_last(const struct common_sampler * gsmpl) {
  321. return gsmpl->prev.rat(0);
  322. }
  323. std::string common_sampler_print(const struct common_sampler * gsmpl) {
  324. std::string result = "logits ";
  325. for (int i = 0; i < llama_sampler_chain_n(gsmpl->chain); i++) {
  326. const auto * smpl = llama_sampler_chain_get(gsmpl->chain, i);
  327. result += std::string("-> ") + llama_sampler_name(smpl) + " ";
  328. }
  329. return result;
  330. }
  331. std::string common_sampler_prev_str(common_sampler * gsmpl, llama_context * ctx_main, int n) {
  332. n = std::min(n, (int) gsmpl->prev.size());
  333. if (n <= 0) {
  334. return "";
  335. }
  336. std::string result;
  337. result.reserve(8*n); // 8 is the average length of a token [citation needed], TODO: compute this from the vocab
  338. for (int i = n - 1; i >= 0; i--) {
  339. const llama_token id = gsmpl->prev.rat(i);
  340. GGML_ASSERT(id != LLAMA_TOKEN_NULL && "null token in the sampling history - should not happen");
  341. result += common_token_to_piece(ctx_main, id);
  342. }
  343. return result;
  344. }
  345. char common_sampler_type_to_chr(enum common_sampler_type cnstr) {
  346. switch (cnstr) {
  347. case COMMON_SAMPLER_TYPE_DRY: return 'd';
  348. case COMMON_SAMPLER_TYPE_TOP_K: return 'k';
  349. case COMMON_SAMPLER_TYPE_TYPICAL_P: return 'y';
  350. case COMMON_SAMPLER_TYPE_TOP_P: return 'p';
  351. case COMMON_SAMPLER_TYPE_MIN_P: return 'm';
  352. case COMMON_SAMPLER_TYPE_TEMPERATURE: return 't';
  353. case COMMON_SAMPLER_TYPE_XTC: return 'x';
  354. case COMMON_SAMPLER_TYPE_INFILL: return 'i';
  355. default : return '?';
  356. }
  357. }
  358. std::string common_sampler_type_to_str(enum common_sampler_type cnstr) {
  359. switch (cnstr) {
  360. case COMMON_SAMPLER_TYPE_DRY: return "dry";
  361. case COMMON_SAMPLER_TYPE_TOP_K: return "top_k";
  362. case COMMON_SAMPLER_TYPE_TYPICAL_P: return "typ_p";
  363. case COMMON_SAMPLER_TYPE_TOP_P: return "top_p";
  364. case COMMON_SAMPLER_TYPE_MIN_P: return "min_p";
  365. case COMMON_SAMPLER_TYPE_TEMPERATURE: return "temperature";
  366. case COMMON_SAMPLER_TYPE_XTC: return "xtc";
  367. case COMMON_SAMPLER_TYPE_INFILL: return "infill";
  368. default : return "";
  369. }
  370. }
  371. std::vector<common_sampler_type> common_sampler_types_from_names(const std::vector<std::string> & names, bool allow_alt_names) {
  372. std::unordered_map<std::string, common_sampler_type> sampler_canonical_name_map {
  373. { "dry", COMMON_SAMPLER_TYPE_DRY },
  374. { "top_k", COMMON_SAMPLER_TYPE_TOP_K },
  375. { "top_p", COMMON_SAMPLER_TYPE_TOP_P },
  376. { "typ_p", COMMON_SAMPLER_TYPE_TYPICAL_P },
  377. { "min_p", COMMON_SAMPLER_TYPE_MIN_P },
  378. { "temperature", COMMON_SAMPLER_TYPE_TEMPERATURE },
  379. { "xtc", COMMON_SAMPLER_TYPE_XTC },
  380. { "infill", COMMON_SAMPLER_TYPE_INFILL },
  381. };
  382. // since samplers names are written multiple ways
  383. // make it ready for both system names and input names
  384. std::unordered_map<std::string, common_sampler_type> sampler_alt_name_map {
  385. { "top-k", COMMON_SAMPLER_TYPE_TOP_K },
  386. { "top-p", COMMON_SAMPLER_TYPE_TOP_P },
  387. { "nucleus", COMMON_SAMPLER_TYPE_TOP_P },
  388. { "typical-p", COMMON_SAMPLER_TYPE_TYPICAL_P },
  389. { "typical", COMMON_SAMPLER_TYPE_TYPICAL_P },
  390. { "typ-p", COMMON_SAMPLER_TYPE_TYPICAL_P },
  391. { "typ", COMMON_SAMPLER_TYPE_TYPICAL_P },
  392. { "min-p", COMMON_SAMPLER_TYPE_MIN_P },
  393. { "temp", COMMON_SAMPLER_TYPE_TEMPERATURE },
  394. };
  395. std::vector<common_sampler_type> samplers;
  396. samplers.reserve(names.size());
  397. for (const auto & name : names) {
  398. auto sampler = sampler_canonical_name_map.find(name);
  399. if (sampler != sampler_canonical_name_map.end()) {
  400. samplers.push_back(sampler->second);
  401. } else {
  402. if (allow_alt_names) {
  403. sampler = sampler_alt_name_map.find(name);
  404. if (sampler != sampler_alt_name_map.end()) {
  405. samplers.push_back(sampler->second);
  406. }
  407. }
  408. }
  409. }
  410. return samplers;
  411. }
  412. std::vector<common_sampler_type> common_sampler_types_from_chars(const std::string & chars) {
  413. std::unordered_map<char, common_sampler_type> sampler_name_map = {
  414. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_DRY), COMMON_SAMPLER_TYPE_DRY },
  415. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_K), COMMON_SAMPLER_TYPE_TOP_K },
  416. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TYPICAL_P), COMMON_SAMPLER_TYPE_TYPICAL_P },
  417. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_P), COMMON_SAMPLER_TYPE_TOP_P },
  418. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_MIN_P), COMMON_SAMPLER_TYPE_MIN_P },
  419. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TEMPERATURE), COMMON_SAMPLER_TYPE_TEMPERATURE },
  420. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_XTC), COMMON_SAMPLER_TYPE_XTC },
  421. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_INFILL), COMMON_SAMPLER_TYPE_INFILL },
  422. };
  423. std::vector<common_sampler_type> samplers;
  424. samplers.reserve(chars.size());
  425. for (const auto & c : chars) {
  426. const auto sampler = sampler_name_map.find(c);
  427. if (sampler != sampler_name_map.end()) {
  428. samplers.push_back(sampler->second);
  429. }
  430. }
  431. return samplers;
  432. }