sampling.cpp 19 KB

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