sampling.cpp 26 KB

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