sampling.cpp 24 KB

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