sampling.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. #include "sampling.h"
  2. #include "common.h"
  3. #include "log.h"
  4. #include <algorithm>
  5. #include <cmath>
  6. #include <cstring>
  7. #include <unordered_map>
  8. // the ring buffer works similarly to std::deque, but with a fixed capacity
  9. // TODO: deduplicate with llama-impl.h
  10. template<typename T>
  11. struct ring_buffer {
  12. ring_buffer(size_t cap) : capacity(cap), data(cap) {}
  13. T & front() {
  14. if (sz == 0) {
  15. throw std::runtime_error("ring buffer is empty");
  16. }
  17. return data[first];
  18. }
  19. const T & front() const {
  20. if (sz == 0) {
  21. throw std::runtime_error("ring buffer is empty");
  22. }
  23. return data[first];
  24. }
  25. T & back() {
  26. if (sz == 0) {
  27. throw std::runtime_error("ring buffer is empty");
  28. }
  29. return data[pos];
  30. }
  31. const T & back() const {
  32. if (sz == 0) {
  33. throw std::runtime_error("ring buffer is empty");
  34. }
  35. return data[pos];
  36. }
  37. void push_back(const T & value) {
  38. if (sz == capacity) {
  39. // advance the start when buffer is full
  40. first = (first + 1) % capacity;
  41. } else {
  42. sz++;
  43. }
  44. data[pos] = value;
  45. pos = (pos + 1) % capacity;
  46. }
  47. T pop_front() {
  48. if (sz == 0) {
  49. throw std::runtime_error("ring buffer is empty");
  50. }
  51. T value = data[first];
  52. first = (first + 1) % capacity;
  53. sz--;
  54. return value;
  55. }
  56. const T & rat(size_t i) const {
  57. if (i >= sz) {
  58. throw std::runtime_error("ring buffer: index out of bounds");
  59. }
  60. return data[(first + sz - i - 1) % capacity];
  61. }
  62. std::vector<T> to_vector() const {
  63. std::vector<T> result;
  64. result.reserve(sz);
  65. for (size_t i = 0; i < sz; i++) {
  66. result.push_back(data[(first + i) % capacity]);
  67. }
  68. return result;
  69. }
  70. void clear() {
  71. // here only reset the status of the buffer
  72. sz = 0;
  73. first = 0;
  74. pos = 0;
  75. }
  76. bool empty() const {
  77. return sz == 0;
  78. }
  79. size_t size() const {
  80. return sz;
  81. }
  82. size_t capacity = 0;
  83. size_t sz = 0;
  84. size_t first = 0;
  85. size_t pos = 0;
  86. std::vector<T> data;
  87. };
  88. struct common_sampler {
  89. common_params_sampling params;
  90. struct llama_sampler * grmr;
  91. struct llama_sampler * chain;
  92. ring_buffer<llama_token> prev;
  93. std::vector<llama_token_data> cur;
  94. llama_token_data_array cur_p;
  95. void reset() {
  96. prev.clear();
  97. llama_sampler_reset(grmr);
  98. llama_sampler_reset(chain);
  99. }
  100. void set_logits(struct llama_context * ctx, int idx) {
  101. const auto * logits = llama_get_logits_ith(ctx, idx);
  102. const llama_model * model = llama_get_model(ctx);
  103. const llama_vocab * vocab = llama_model_get_vocab(model);
  104. const int n_vocab = llama_vocab_n_tokens(vocab);
  105. cur.resize(n_vocab);
  106. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  107. cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
  108. }
  109. cur_p = { cur.data(), cur.size(), -1, false };
  110. }
  111. common_time_meas tm() {
  112. return common_time_meas(t_total_us, params.no_perf);
  113. }
  114. mutable int64_t t_total_us = 0;
  115. };
  116. std::string common_params_sampling::print() const {
  117. char result[1024];
  118. snprintf(result, sizeof(result),
  119. "\trepeat_last_n = %d, repeat_penalty = %.3f, frequency_penalty = %.3f, presence_penalty = %.3f\n"
  120. "\tdry_multiplier = %.3f, dry_base = %.3f, dry_allowed_length = %d, dry_penalty_last_n = %d\n"
  121. "\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"
  122. "\tmirostat = %d, mirostat_lr = %.3f, mirostat_ent = %.3f",
  123. penalty_last_n, penalty_repeat, penalty_freq, penalty_present,
  124. dry_multiplier, dry_base, dry_allowed_length, dry_penalty_last_n,
  125. top_k, top_p, min_p, xtc_probability, xtc_threshold, typ_p, top_n_sigma, temp,
  126. mirostat, mirostat_eta, mirostat_tau);
  127. return std::string(result);
  128. }
  129. struct common_sampler * common_sampler_init(const struct llama_model * model, const struct common_params_sampling & params) {
  130. const llama_vocab * vocab = llama_model_get_vocab(model);
  131. llama_sampler_chain_params lparams = llama_sampler_chain_default_params();
  132. lparams.no_perf = params.no_perf;
  133. struct llama_sampler * grmr;
  134. if (params.grammar.compare(0, 11, "%llguidance") == 0) {
  135. #ifdef LLAMA_USE_LLGUIDANCE
  136. grmr = llama_sampler_init_llg(vocab, "lark", params.grammar.c_str());
  137. #else
  138. GGML_ABORT("llguidance (cmake -DLLAMA_LLGUIDANCE=ON) is not enabled");
  139. #endif // LLAMA_USE_LLGUIDANCE
  140. } else {
  141. std::vector<std::string> trigger_patterns;
  142. std::vector<std::string> patterns_anywhere;
  143. std::vector<llama_token> trigger_tokens;
  144. for (const auto & trigger : params.grammar_triggers) {
  145. switch (trigger.type) {
  146. case COMMON_GRAMMAR_TRIGGER_TYPE_WORD:
  147. {
  148. const auto & word = trigger.value;
  149. patterns_anywhere.push_back(regex_escape(word));
  150. break;
  151. }
  152. case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN:
  153. {
  154. patterns_anywhere.push_back(trigger.value);
  155. break;
  156. }
  157. case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL:
  158. {
  159. trigger_patterns.push_back(trigger.value);
  160. break;
  161. }
  162. case COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN:
  163. {
  164. const auto token = trigger.token;
  165. trigger_tokens.push_back(token);
  166. break;
  167. }
  168. default:
  169. GGML_ASSERT(false && "unknown trigger type");
  170. }
  171. }
  172. if (!patterns_anywhere.empty()) {
  173. trigger_patterns.push_back("^[\\s\\S]*?(" + string_join(patterns_anywhere, "|") + ")[\\s\\S]*");
  174. }
  175. std::vector<const char *> trigger_patterns_c;
  176. trigger_patterns_c.reserve(trigger_patterns.size());
  177. for (const auto & regex : trigger_patterns) {
  178. trigger_patterns_c.push_back(regex.c_str());
  179. }
  180. grmr = params.grammar_lazy
  181. ? llama_sampler_init_grammar_lazy_patterns(vocab, params.grammar.c_str(), "root",
  182. trigger_patterns_c.data(), trigger_patterns_c.size(),
  183. trigger_tokens.data(), trigger_tokens.size())
  184. : llama_sampler_init_grammar(vocab, params.grammar.c_str(), "root");
  185. if (!grmr) {
  186. return nullptr;
  187. }
  188. }
  189. auto * result = new common_sampler {
  190. /* .params = */ params,
  191. /* .grmr = */ grmr,
  192. /* .chain = */ llama_sampler_chain_init(lparams),
  193. /* .prev = */ ring_buffer<llama_token>(std::max(32, params.n_prev)),
  194. /* .cur = */ {},
  195. /* .cur_p = */ {},
  196. };
  197. llama_sampler_chain_add(result->chain,
  198. llama_sampler_init_logit_bias(
  199. llama_vocab_n_tokens(vocab),
  200. params.logit_bias.size(),
  201. params.logit_bias.data()));
  202. if (params.mirostat == 0) {
  203. for (const auto & cnstr : params.samplers) {
  204. switch (cnstr) {
  205. case COMMON_SAMPLER_TYPE_DRY:
  206. {
  207. std::vector<const char *> c_breakers;
  208. c_breakers.reserve(params.dry_sequence_breakers.size());
  209. for (const auto & str : params.dry_sequence_breakers) {
  210. c_breakers.push_back(str.c_str());
  211. }
  212. 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()));
  213. }
  214. break;
  215. case COMMON_SAMPLER_TYPE_TOP_K:
  216. llama_sampler_chain_add(result->chain, llama_sampler_init_top_k (params.top_k));
  217. break;
  218. case COMMON_SAMPLER_TYPE_TOP_P:
  219. llama_sampler_chain_add(result->chain, llama_sampler_init_top_p (params.top_p, params.min_keep));
  220. break;
  221. case COMMON_SAMPLER_TYPE_TOP_N_SIGMA:
  222. llama_sampler_chain_add(result->chain, llama_sampler_init_top_n_sigma (params.top_n_sigma));
  223. break;
  224. case COMMON_SAMPLER_TYPE_MIN_P:
  225. llama_sampler_chain_add(result->chain, llama_sampler_init_min_p (params.min_p, params.min_keep));
  226. break;
  227. case COMMON_SAMPLER_TYPE_XTC:
  228. llama_sampler_chain_add(result->chain, llama_sampler_init_xtc (params.xtc_probability, params.xtc_threshold, params.min_keep, params.seed));
  229. break;
  230. case COMMON_SAMPLER_TYPE_TYPICAL_P:
  231. llama_sampler_chain_add(result->chain, llama_sampler_init_typical (params.typ_p, params.min_keep));
  232. break;
  233. case COMMON_SAMPLER_TYPE_TEMPERATURE:
  234. llama_sampler_chain_add(result->chain, llama_sampler_init_temp_ext (params.temp, params.dynatemp_range, params.dynatemp_exponent));
  235. break;
  236. case COMMON_SAMPLER_TYPE_INFILL:
  237. llama_sampler_chain_add(result->chain, llama_sampler_init_infill (vocab));
  238. break;
  239. case COMMON_SAMPLER_TYPE_PENALTIES:
  240. llama_sampler_chain_add(result->chain, llama_sampler_init_penalties (params.penalty_last_n, params.penalty_repeat, params.penalty_freq, params.penalty_present));
  241. break;
  242. default:
  243. GGML_ASSERT(false && "unknown sampler type");
  244. }
  245. }
  246. llama_sampler_chain_add(result->chain, llama_sampler_init_dist(params.seed));
  247. } else if (params.mirostat == 1) {
  248. llama_sampler_chain_add(result->chain, llama_sampler_init_temp(params.temp));
  249. llama_sampler_chain_add(result->chain, llama_sampler_init_mirostat(llama_vocab_n_tokens(vocab), params.seed, params.mirostat_tau, params.mirostat_eta, 100));
  250. } else if (params.mirostat == 2) {
  251. llama_sampler_chain_add(result->chain, llama_sampler_init_temp(params.temp));
  252. llama_sampler_chain_add(result->chain, llama_sampler_init_mirostat_v2(params.seed, params.mirostat_tau, params.mirostat_eta));
  253. } else {
  254. GGML_ASSERT(false && "unknown mirostat version");
  255. }
  256. return result;
  257. }
  258. void common_sampler_free(struct common_sampler * gsmpl) {
  259. if (gsmpl) {
  260. llama_sampler_free(gsmpl->grmr);
  261. llama_sampler_free(gsmpl->chain);
  262. delete gsmpl;
  263. }
  264. }
  265. void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool accept_grammar) {
  266. const auto tm = gsmpl->tm();
  267. if (accept_grammar) {
  268. llama_sampler_accept(gsmpl->grmr, token);
  269. }
  270. llama_sampler_accept(gsmpl->chain, token);
  271. gsmpl->prev.push_back(token);
  272. }
  273. void common_sampler_reset(struct common_sampler * gsmpl) {
  274. gsmpl->reset();
  275. }
  276. struct common_sampler * common_sampler_clone(common_sampler * gsmpl) {
  277. return new common_sampler {
  278. /* .params = */ gsmpl->params,
  279. /* .grmr = */ llama_sampler_clone(gsmpl->grmr),
  280. /* .chain = */ llama_sampler_clone(gsmpl->chain),
  281. /* .prev = */ gsmpl->prev,
  282. /* .cur = */ gsmpl->cur,
  283. /* .cur_p = */ gsmpl->cur_p,
  284. };
  285. }
  286. void common_perf_print(const struct llama_context * ctx, const struct common_sampler * gsmpl) {
  287. // TODO: measure grammar performance
  288. const double t_sampling_ms = gsmpl ? 1e-3*gsmpl->t_total_us : 0;
  289. llama_perf_sampler_data data_smpl;
  290. llama_perf_context_data data_ctx;
  291. memset(&data_smpl, 0, sizeof(data_smpl));
  292. memset(&data_ctx, 0, sizeof(data_ctx));
  293. if (gsmpl) {
  294. auto & data = data_smpl;
  295. data = llama_perf_sampler(gsmpl->chain);
  296. // note: the sampling time includes the samplers time + extra time spent in common/sampling
  297. LOG_INF("%s: sampling time = %10.2f ms\n", __func__, t_sampling_ms);
  298. LOG_INF("%s: samplers time = %10.2f ms / %5d tokens\n", __func__, data.t_sample_ms, data.n_sample);
  299. }
  300. if (ctx) {
  301. auto & data = data_ctx;
  302. data = llama_perf_context(ctx);
  303. const double t_end_ms = 1e-3 * ggml_time_us();
  304. const double t_total_ms = t_end_ms - data.t_start_ms;
  305. const double t_unacc_ms = t_total_ms - (t_sampling_ms + data.t_p_eval_ms + data.t_eval_ms);
  306. const double t_unacc_pc = 100.0 * t_unacc_ms / t_total_ms;
  307. LOG_INF("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
  308. LOG_INF("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  309. __func__, data.t_p_eval_ms, data.n_p_eval, data.t_p_eval_ms / data.n_p_eval, 1e3 / data.t_p_eval_ms * data.n_p_eval);
  310. LOG_INF("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  311. __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
  312. LOG_INF("%s: total time = %10.2f ms / %5d tokens\n", __func__, (t_end_ms - data.t_start_ms), (data.n_p_eval + data.n_eval));
  313. LOG_INF("%s: unaccounted time = %10.2f ms / %5.1f %% (total - sampling - prompt eval - eval) / (total)\n", __func__, t_unacc_ms, t_unacc_pc);
  314. LOG_INF("%s: graphs reused = %10d\n", __func__, data.n_reused);
  315. llama_memory_breakdown_print(ctx);
  316. }
  317. }
  318. llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
  319. llama_synchronize(ctx);
  320. // start measuring sampling time after the llama_context synchronization in order to not measure any ongoing async operations
  321. const auto tm = gsmpl->tm();
  322. gsmpl->set_logits(ctx, idx);
  323. auto & grmr = gsmpl->grmr;
  324. auto & chain = gsmpl->chain;
  325. auto & cur_p = gsmpl->cur_p; // initialized by set_logits
  326. if (grammar_first) {
  327. llama_sampler_apply(grmr, &cur_p);
  328. }
  329. llama_sampler_apply(chain, &cur_p);
  330. GGML_ASSERT(cur_p.selected != -1 && "no selected token during sampling - check your sampling configuration");
  331. const llama_token id = cur_p.data[cur_p.selected].id;
  332. if (grammar_first) {
  333. return id;
  334. }
  335. // check if it the sampled token fits the grammar
  336. {
  337. llama_token_data single_token_data = { id, 1.0f, 0.0f };
  338. llama_token_data_array single_token_data_array = { &single_token_data, 1, -1, false };
  339. llama_sampler_apply(grmr, &single_token_data_array);
  340. const bool is_valid = single_token_data_array.data[0].logit != -INFINITY;
  341. if (is_valid) {
  342. return id;
  343. }
  344. }
  345. // resampling:
  346. // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain
  347. gsmpl->set_logits(ctx, idx);
  348. llama_sampler_apply(grmr, &cur_p);
  349. llama_sampler_apply(chain, &cur_p);
  350. GGML_ASSERT(cur_p.selected != -1 && "no selected token during re-sampling - check your sampling configuration");
  351. return cur_p.data[cur_p.selected].id;
  352. }
  353. 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) {
  354. GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1");
  355. std::vector<llama_token> result;
  356. result.reserve(idxs.size());
  357. size_t i = 0;
  358. for (; i < draft.size(); i++) {
  359. const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
  360. common_sampler_accept(gsmpl, id, true);
  361. result.push_back(id);
  362. if (draft[i] != id) {
  363. break;
  364. }
  365. }
  366. if (i == draft.size()) {
  367. const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
  368. common_sampler_accept(gsmpl, id, true);
  369. result.push_back(id);
  370. }
  371. return result;
  372. }
  373. 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) {
  374. std::vector<int> idxs(draft.size() + 1);
  375. for (size_t i = 0; i < idxs.size(); ++i) {
  376. idxs[i] = i;
  377. }
  378. return common_sampler_sample_and_accept_n(gsmpl, ctx, idxs, draft, grammar_first);
  379. }
  380. uint32_t common_sampler_get_seed(const struct common_sampler * gsmpl) {
  381. return llama_sampler_get_seed(gsmpl->chain);
  382. }
  383. // helpers
  384. llama_token_data_array * common_sampler_get_candidates(struct common_sampler * gsmpl, bool do_sort) {
  385. const auto tm = gsmpl->tm();
  386. auto * res = &gsmpl->cur_p;
  387. if (do_sort && !res->sorted) {
  388. // remember the selected token before sorting
  389. const llama_token id = res->data[res->selected].id;
  390. std::sort(res->data, res->data + res->size, [](const llama_token_data & a, const llama_token_data & b) {
  391. return a.p > b.p;
  392. });
  393. // restore the selected token after sorting
  394. for (size_t i = 0; i < res->size; ++i) {
  395. if (res->data[i].id == id) {
  396. res->selected = i;
  397. break;
  398. }
  399. }
  400. res->sorted = true;
  401. }
  402. return res;
  403. }
  404. llama_token common_sampler_last(const struct common_sampler * gsmpl) {
  405. return gsmpl->prev.rat(0);
  406. }
  407. std::string common_sampler_print(const struct common_sampler * gsmpl) {
  408. std::string result = "logits ";
  409. for (int i = 0; i < llama_sampler_chain_n(gsmpl->chain); i++) {
  410. const auto * smpl = llama_sampler_chain_get(gsmpl->chain, i);
  411. result += std::string("-> ") + llama_sampler_name(smpl) + " ";
  412. }
  413. return result;
  414. }
  415. std::string common_sampler_prev_str(common_sampler * gsmpl, llama_context * ctx_main, int n) {
  416. n = std::min(n, (int) gsmpl->prev.size());
  417. if (n <= 0) {
  418. return "";
  419. }
  420. std::string result;
  421. result.reserve(8*n); // 8 is the average length of a token [citation needed], TODO: compute this from the vocab
  422. for (int i = n - 1; i >= 0; i--) {
  423. const llama_token id = gsmpl->prev.rat(i);
  424. GGML_ASSERT(id != LLAMA_TOKEN_NULL && "null token in the sampling history - should not happen");
  425. result += common_token_to_piece(ctx_main, id);
  426. }
  427. return result;
  428. }
  429. char common_sampler_type_to_chr(enum common_sampler_type cnstr) {
  430. switch (cnstr) {
  431. case COMMON_SAMPLER_TYPE_DRY: return 'd';
  432. case COMMON_SAMPLER_TYPE_TOP_K: return 'k';
  433. case COMMON_SAMPLER_TYPE_TYPICAL_P: return 'y';
  434. case COMMON_SAMPLER_TYPE_TOP_P: return 'p';
  435. case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: return 's';
  436. case COMMON_SAMPLER_TYPE_MIN_P: return 'm';
  437. case COMMON_SAMPLER_TYPE_TEMPERATURE: return 't';
  438. case COMMON_SAMPLER_TYPE_XTC: return 'x';
  439. case COMMON_SAMPLER_TYPE_INFILL: return 'i';
  440. case COMMON_SAMPLER_TYPE_PENALTIES: return 'e';
  441. default : return '?';
  442. }
  443. }
  444. std::string common_sampler_type_to_str(enum common_sampler_type cnstr) {
  445. switch (cnstr) {
  446. case COMMON_SAMPLER_TYPE_DRY: return "dry";
  447. case COMMON_SAMPLER_TYPE_TOP_K: return "top_k";
  448. case COMMON_SAMPLER_TYPE_TYPICAL_P: return "typ_p";
  449. case COMMON_SAMPLER_TYPE_TOP_P: return "top_p";
  450. case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: return "top_n_sigma";
  451. case COMMON_SAMPLER_TYPE_MIN_P: return "min_p";
  452. case COMMON_SAMPLER_TYPE_TEMPERATURE: return "temperature";
  453. case COMMON_SAMPLER_TYPE_XTC: return "xtc";
  454. case COMMON_SAMPLER_TYPE_INFILL: return "infill";
  455. case COMMON_SAMPLER_TYPE_PENALTIES: return "penalties";
  456. default : return "";
  457. }
  458. }
  459. std::vector<common_sampler_type> common_sampler_types_from_names(const std::vector<std::string> & names, bool allow_alt_names) {
  460. std::unordered_map<std::string, common_sampler_type> sampler_canonical_name_map {
  461. { "dry", COMMON_SAMPLER_TYPE_DRY },
  462. { "top_k", COMMON_SAMPLER_TYPE_TOP_K },
  463. { "top_p", COMMON_SAMPLER_TYPE_TOP_P },
  464. { "top_n_sigma", COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
  465. { "typ_p", COMMON_SAMPLER_TYPE_TYPICAL_P },
  466. { "min_p", COMMON_SAMPLER_TYPE_MIN_P },
  467. { "temperature", COMMON_SAMPLER_TYPE_TEMPERATURE },
  468. { "xtc", COMMON_SAMPLER_TYPE_XTC },
  469. { "infill", COMMON_SAMPLER_TYPE_INFILL },
  470. { "penalties", COMMON_SAMPLER_TYPE_PENALTIES },
  471. };
  472. // since samplers names are written multiple ways
  473. // make it ready for both system names and input names
  474. std::unordered_map<std::string, common_sampler_type> sampler_alt_name_map {
  475. { "top-k", COMMON_SAMPLER_TYPE_TOP_K },
  476. { "top-p", COMMON_SAMPLER_TYPE_TOP_P },
  477. { "top-n-sigma", COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
  478. { "nucleus", COMMON_SAMPLER_TYPE_TOP_P },
  479. { "typical-p", COMMON_SAMPLER_TYPE_TYPICAL_P },
  480. { "typical", COMMON_SAMPLER_TYPE_TYPICAL_P },
  481. { "typ-p", COMMON_SAMPLER_TYPE_TYPICAL_P },
  482. { "typ", COMMON_SAMPLER_TYPE_TYPICAL_P },
  483. { "min-p", COMMON_SAMPLER_TYPE_MIN_P },
  484. { "temp", COMMON_SAMPLER_TYPE_TEMPERATURE },
  485. };
  486. std::vector<common_sampler_type> samplers;
  487. samplers.reserve(names.size());
  488. for (const auto & name : names) {
  489. auto sampler = sampler_canonical_name_map.find(name);
  490. if (sampler != sampler_canonical_name_map.end()) {
  491. samplers.push_back(sampler->second);
  492. continue;
  493. }
  494. if (allow_alt_names) {
  495. sampler = sampler_alt_name_map.find(name);
  496. if (sampler != sampler_alt_name_map.end()) {
  497. samplers.push_back(sampler->second);
  498. continue;
  499. }
  500. }
  501. LOG_WRN("%s: unable to match sampler by name '%s'\n", __func__, name.c_str());
  502. }
  503. return samplers;
  504. }
  505. std::vector<common_sampler_type> common_sampler_types_from_chars(const std::string & chars) {
  506. std::unordered_map<char, common_sampler_type> sampler_name_map = {
  507. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_DRY), COMMON_SAMPLER_TYPE_DRY },
  508. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_K), COMMON_SAMPLER_TYPE_TOP_K },
  509. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TYPICAL_P), COMMON_SAMPLER_TYPE_TYPICAL_P },
  510. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_P), COMMON_SAMPLER_TYPE_TOP_P },
  511. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_N_SIGMA), COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
  512. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_MIN_P), COMMON_SAMPLER_TYPE_MIN_P },
  513. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TEMPERATURE), COMMON_SAMPLER_TYPE_TEMPERATURE },
  514. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_XTC), COMMON_SAMPLER_TYPE_XTC },
  515. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_INFILL), COMMON_SAMPLER_TYPE_INFILL },
  516. { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_PENALTIES), COMMON_SAMPLER_TYPE_PENALTIES },
  517. };
  518. std::vector<common_sampler_type> samplers;
  519. samplers.reserve(chars.size());
  520. for (const auto & c : chars) {
  521. const auto sampler = sampler_name_map.find(c);
  522. if (sampler != sampler_name_map.end()) {
  523. samplers.push_back(sampler->second);
  524. } else {
  525. LOG_WRN("%s: unable to match sampler by char '%c'\n", __func__, c);
  526. }
  527. }
  528. return samplers;
  529. }