1
0

sampling.cpp 24 KB

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